xref: /freebsd/contrib/llvm-project/lld/ELF/InputFiles.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
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"
30*e8d8bef9SDimitry 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) {
108*e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Load input files", path);
109*e8d8bef9SDimitry 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);
116*e8d8bef9SDimitry Andric   config->dependencyFiles.insert(llvm::CachedHashString(path));
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   auto mbOrErr = MemoryBuffer::getFile(path, -1, false);
1190b57cec5SDimitry Andric   if (auto ec = mbOrErr.getError()) {
1200b57cec5SDimitry Andric     error("cannot open " + path + ": " + ec.message());
1210b57cec5SDimitry Andric     return None;
1220b57cec5SDimitry Andric   }
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
1250b57cec5SDimitry Andric   MemoryBufferRef mbref = mb->getMemBufferRef();
1260b57cec5SDimitry Andric   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric   if (tar)
1290b57cec5SDimitry Andric     tar->append(relativeToRoot(path), mbref.getBuffer());
1300b57cec5SDimitry Andric   return mbref;
1310b57cec5SDimitry Andric }
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric // All input object files must be for the same architecture
1340b57cec5SDimitry Andric // (e.g. it does not make sense to link x86 object files with
1350b57cec5SDimitry Andric // MIPS object files.) This function checks for that error.
1360b57cec5SDimitry Andric static bool isCompatible(InputFile *file) {
1370b57cec5SDimitry Andric   if (!file->isElf() && !isa<BitcodeFile>(file))
1380b57cec5SDimitry Andric     return true;
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric   if (file->ekind == config->ekind && file->emachine == config->emachine) {
1410b57cec5SDimitry Andric     if (config->emachine != EM_MIPS)
1420b57cec5SDimitry Andric       return true;
1430b57cec5SDimitry Andric     if (isMipsN32Abi(file) == config->mipsN32Abi)
1440b57cec5SDimitry Andric       return true;
1450b57cec5SDimitry Andric   }
1460b57cec5SDimitry Andric 
1475ffd83dbSDimitry Andric   StringRef target =
1485ffd83dbSDimitry Andric       !config->bfdname.empty() ? config->bfdname : config->emulation;
1495ffd83dbSDimitry Andric   if (!target.empty()) {
1505ffd83dbSDimitry Andric     error(toString(file) + " is incompatible with " + target);
15185868e8aSDimitry Andric     return false;
15285868e8aSDimitry Andric   }
15385868e8aSDimitry Andric 
1540b57cec5SDimitry Andric   InputFile *existing;
1550b57cec5SDimitry Andric   if (!objectFiles.empty())
1560b57cec5SDimitry Andric     existing = objectFiles[0];
1570b57cec5SDimitry Andric   else if (!sharedFiles.empty())
1580b57cec5SDimitry Andric     existing = sharedFiles[0];
1595ffd83dbSDimitry Andric   else if (!bitcodeFiles.empty())
1600b57cec5SDimitry Andric     existing = bitcodeFiles[0];
1615ffd83dbSDimitry Andric   else
1625ffd83dbSDimitry Andric     llvm_unreachable("Must have -m, OUTPUT_FORMAT or existing input file to "
1635ffd83dbSDimitry Andric                      "determine target emulation");
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   error(toString(file) + " is incompatible with " + toString(existing));
1660b57cec5SDimitry Andric   return false;
1670b57cec5SDimitry Andric }
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric template <class ELFT> static void doParseFile(InputFile *file) {
1700b57cec5SDimitry Andric   if (!isCompatible(file))
1710b57cec5SDimitry Andric     return;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   // Binary file
1740b57cec5SDimitry Andric   if (auto *f = dyn_cast<BinaryFile>(file)) {
1750b57cec5SDimitry Andric     binaryFiles.push_back(f);
1760b57cec5SDimitry Andric     f->parse();
1770b57cec5SDimitry Andric     return;
1780b57cec5SDimitry Andric   }
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   // .a file
1810b57cec5SDimitry Andric   if (auto *f = dyn_cast<ArchiveFile>(file)) {
1825ffd83dbSDimitry Andric     archiveFiles.push_back(f);
1830b57cec5SDimitry Andric     f->parse();
1840b57cec5SDimitry Andric     return;
1850b57cec5SDimitry Andric   }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   // Lazy object file
1880b57cec5SDimitry Andric   if (auto *f = dyn_cast<LazyObjFile>(file)) {
1890b57cec5SDimitry Andric     lazyObjFiles.push_back(f);
1900b57cec5SDimitry Andric     f->parse<ELFT>();
1910b57cec5SDimitry Andric     return;
1920b57cec5SDimitry Andric   }
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   if (config->trace)
1950b57cec5SDimitry Andric     message(toString(file));
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   // .so file
1980b57cec5SDimitry Andric   if (auto *f = dyn_cast<SharedFile>(file)) {
1990b57cec5SDimitry Andric     f->parse<ELFT>();
2000b57cec5SDimitry Andric     return;
2010b57cec5SDimitry Andric   }
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric   // LLVM bitcode file
2040b57cec5SDimitry Andric   if (auto *f = dyn_cast<BitcodeFile>(file)) {
2050b57cec5SDimitry Andric     bitcodeFiles.push_back(f);
2060b57cec5SDimitry Andric     f->parse<ELFT>();
2070b57cec5SDimitry Andric     return;
2080b57cec5SDimitry Andric   }
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric   // Regular object file
2110b57cec5SDimitry Andric   objectFiles.push_back(file);
2120b57cec5SDimitry Andric   cast<ObjFile<ELFT>>(file)->parse();
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric // Add symbols in File to the symbol table.
2165ffd83dbSDimitry Andric void elf::parseFile(InputFile *file) {
2170b57cec5SDimitry Andric   switch (config->ekind) {
2180b57cec5SDimitry Andric   case ELF32LEKind:
2190b57cec5SDimitry Andric     doParseFile<ELF32LE>(file);
2200b57cec5SDimitry Andric     return;
2210b57cec5SDimitry Andric   case ELF32BEKind:
2220b57cec5SDimitry Andric     doParseFile<ELF32BE>(file);
2230b57cec5SDimitry Andric     return;
2240b57cec5SDimitry Andric   case ELF64LEKind:
2250b57cec5SDimitry Andric     doParseFile<ELF64LE>(file);
2260b57cec5SDimitry Andric     return;
2270b57cec5SDimitry Andric   case ELF64BEKind:
2280b57cec5SDimitry Andric     doParseFile<ELF64BE>(file);
2290b57cec5SDimitry Andric     return;
2300b57cec5SDimitry Andric   default:
2310b57cec5SDimitry Andric     llvm_unreachable("unknown ELFT");
2320b57cec5SDimitry Andric   }
2330b57cec5SDimitry Andric }
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric // Concatenates arguments to construct a string representing an error location.
2360b57cec5SDimitry Andric static std::string createFileLineMsg(StringRef path, unsigned line) {
2375ffd83dbSDimitry Andric   std::string filename = std::string(path::filename(path));
2380b57cec5SDimitry Andric   std::string lineno = ":" + std::to_string(line);
2390b57cec5SDimitry Andric   if (filename == path)
2400b57cec5SDimitry Andric     return filename + lineno;
2410b57cec5SDimitry Andric   return filename + lineno + " (" + path.str() + lineno + ")";
2420b57cec5SDimitry Andric }
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric template <class ELFT>
2450b57cec5SDimitry Andric static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym,
2460b57cec5SDimitry Andric                                 InputSectionBase &sec, uint64_t offset) {
2470b57cec5SDimitry Andric   // In DWARF, functions and variables are stored to different places.
2480b57cec5SDimitry Andric   // First, lookup a function for a given offset.
2490b57cec5SDimitry Andric   if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
2500b57cec5SDimitry Andric     return createFileLineMsg(info->FileName, info->Line);
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric   // If it failed, lookup again as a variable.
2530b57cec5SDimitry Andric   if (Optional<std::pair<std::string, unsigned>> fileLine =
2540b57cec5SDimitry Andric           file.getVariableLoc(sym.getName()))
2550b57cec5SDimitry Andric     return createFileLineMsg(fileLine->first, fileLine->second);
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   // File.sourceFile contains STT_FILE symbol, and that is a last resort.
2585ffd83dbSDimitry Andric   return std::string(file.sourceFile);
2590b57cec5SDimitry Andric }
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec,
2620b57cec5SDimitry Andric                                  uint64_t offset) {
2630b57cec5SDimitry Andric   if (kind() != ObjKind)
2640b57cec5SDimitry Andric     return "";
2650b57cec5SDimitry Andric   switch (config->ekind) {
2660b57cec5SDimitry Andric   default:
2670b57cec5SDimitry Andric     llvm_unreachable("Invalid kind");
2680b57cec5SDimitry Andric   case ELF32LEKind:
2690b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset);
2700b57cec5SDimitry Andric   case ELF32BEKind:
2710b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset);
2720b57cec5SDimitry Andric   case ELF64LEKind:
2730b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset);
2740b57cec5SDimitry Andric   case ELF64BEKind:
2750b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset);
2760b57cec5SDimitry Andric   }
2770b57cec5SDimitry Andric }
2780b57cec5SDimitry Andric 
279*e8d8bef9SDimitry Andric StringRef InputFile::getNameForScript() const {
280*e8d8bef9SDimitry Andric   if (archiveName.empty())
281*e8d8bef9SDimitry Andric     return getName();
282*e8d8bef9SDimitry Andric 
283*e8d8bef9SDimitry Andric   if (nameForScriptCache.empty())
284*e8d8bef9SDimitry Andric     nameForScriptCache = (archiveName + Twine(':') + getName()).str();
285*e8d8bef9SDimitry Andric 
286*e8d8bef9SDimitry Andric   return nameForScriptCache;
287*e8d8bef9SDimitry Andric }
288*e8d8bef9SDimitry Andric 
2895ffd83dbSDimitry Andric template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() {
2905ffd83dbSDimitry Andric   llvm::call_once(initDwarf, [this]() {
2915ffd83dbSDimitry Andric     dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
2925ffd83dbSDimitry Andric         std::make_unique<LLDDwarfObj<ELFT>>(this), "",
2935ffd83dbSDimitry Andric         [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
2945ffd83dbSDimitry Andric         [&](Error warning) {
2955ffd83dbSDimitry Andric           warn(getName() + ": " + toString(std::move(warning)));
2965ffd83dbSDimitry Andric         }));
2975ffd83dbSDimitry Andric   });
2985ffd83dbSDimitry Andric 
2995ffd83dbSDimitry Andric   return dwarf.get();
3000b57cec5SDimitry Andric }
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric // Returns the pair of file name and line number describing location of data
3030b57cec5SDimitry Andric // object (variable, array, etc) definition.
3040b57cec5SDimitry Andric template <class ELFT>
3050b57cec5SDimitry Andric Optional<std::pair<std::string, unsigned>>
3060b57cec5SDimitry Andric ObjFile<ELFT>::getVariableLoc(StringRef name) {
3075ffd83dbSDimitry Andric   return getDwarf()->getVariableLoc(name);
3080b57cec5SDimitry Andric }
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric // Returns source line information for a given offset
3110b57cec5SDimitry Andric // using DWARF debug info.
3120b57cec5SDimitry Andric template <class ELFT>
3130b57cec5SDimitry Andric Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s,
3140b57cec5SDimitry Andric                                                   uint64_t offset) {
3150b57cec5SDimitry Andric   // Detect SectionIndex for specified section.
3160b57cec5SDimitry Andric   uint64_t sectionIndex = object::SectionedAddress::UndefSection;
3170b57cec5SDimitry Andric   ArrayRef<InputSectionBase *> sections = s->file->getSections();
3180b57cec5SDimitry Andric   for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) {
3190b57cec5SDimitry Andric     if (s == sections[curIndex]) {
3200b57cec5SDimitry Andric       sectionIndex = curIndex;
3210b57cec5SDimitry Andric       break;
3220b57cec5SDimitry Andric     }
3230b57cec5SDimitry Andric   }
3240b57cec5SDimitry Andric 
3255ffd83dbSDimitry Andric   return getDwarf()->getDILineInfo(offset, sectionIndex);
3260b57cec5SDimitry Andric }
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) {
3290b57cec5SDimitry Andric   ekind = getELFKind(mb, "");
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   switch (ekind) {
3320b57cec5SDimitry Andric   case ELF32LEKind:
3330b57cec5SDimitry Andric     init<ELF32LE>();
3340b57cec5SDimitry Andric     break;
3350b57cec5SDimitry Andric   case ELF32BEKind:
3360b57cec5SDimitry Andric     init<ELF32BE>();
3370b57cec5SDimitry Andric     break;
3380b57cec5SDimitry Andric   case ELF64LEKind:
3390b57cec5SDimitry Andric     init<ELF64LE>();
3400b57cec5SDimitry Andric     break;
3410b57cec5SDimitry Andric   case ELF64BEKind:
3420b57cec5SDimitry Andric     init<ELF64BE>();
3430b57cec5SDimitry Andric     break;
3440b57cec5SDimitry Andric   default:
3450b57cec5SDimitry Andric     llvm_unreachable("getELFKind");
3460b57cec5SDimitry Andric   }
3470b57cec5SDimitry Andric }
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric template <typename Elf_Shdr>
3500b57cec5SDimitry Andric static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
3510b57cec5SDimitry Andric   for (const Elf_Shdr &sec : sections)
3520b57cec5SDimitry Andric     if (sec.sh_type == type)
3530b57cec5SDimitry Andric       return &sec;
3540b57cec5SDimitry Andric   return nullptr;
3550b57cec5SDimitry Andric }
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric template <class ELFT> void ELFFileBase::init() {
3580b57cec5SDimitry Andric   using Elf_Shdr = typename ELFT::Shdr;
3590b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric   // Initialize trivial attributes.
3620b57cec5SDimitry Andric   const ELFFile<ELFT> &obj = getObj<ELFT>();
363*e8d8bef9SDimitry Andric   emachine = obj.getHeader().e_machine;
364*e8d8bef9SDimitry Andric   osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI];
365*e8d8bef9SDimitry Andric   abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION];
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   // Find a symbol table.
3700b57cec5SDimitry Andric   bool isDSO =
3710b57cec5SDimitry Andric       (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
3720b57cec5SDimitry Andric   const Elf_Shdr *symtabSec =
3730b57cec5SDimitry Andric       findSection(sections, isDSO ? SHT_DYNSYM : SHT_SYMTAB);
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   if (!symtabSec)
3760b57cec5SDimitry Andric     return;
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   // Initialize members corresponding to a symbol table.
3790b57cec5SDimitry Andric   firstGlobal = symtabSec->sh_info;
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric   ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
3820b57cec5SDimitry Andric   if (firstGlobal == 0 || firstGlobal > eSyms.size())
3830b57cec5SDimitry Andric     fatal(toString(this) + ": invalid sh_info in symbol table");
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   elfSyms = reinterpret_cast<const void *>(eSyms.data());
3860b57cec5SDimitry Andric   numELFSyms = eSyms.size();
3870b57cec5SDimitry Andric   stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
3880b57cec5SDimitry Andric }
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric template <class ELFT>
3910b57cec5SDimitry Andric uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
3920b57cec5SDimitry Andric   return CHECK(
393*e8d8bef9SDimitry Andric       this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable),
3940b57cec5SDimitry Andric       this);
3950b57cec5SDimitry Andric }
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
3980b57cec5SDimitry Andric   if (this->symbols.empty())
3990b57cec5SDimitry Andric     return {};
4000b57cec5SDimitry Andric   return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1);
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
4040b57cec5SDimitry Andric   return makeArrayRef(this->symbols).slice(this->firstGlobal);
4050b57cec5SDimitry Andric }
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
4080b57cec5SDimitry Andric   // Read a section table. justSymbols is usually false.
4090b57cec5SDimitry Andric   if (this->justSymbols)
4100b57cec5SDimitry Andric     initializeJustSymbols();
4110b57cec5SDimitry Andric   else
4120b57cec5SDimitry Andric     initializeSections(ignoreComdats);
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric   // Read a symbol table.
4150b57cec5SDimitry Andric   initializeSymbols();
4160b57cec5SDimitry Andric }
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric // Sections with SHT_GROUP and comdat bits define comdat section groups.
4190b57cec5SDimitry Andric // They are identified and deduplicated by group name. This function
4200b57cec5SDimitry Andric // returns a group name.
4210b57cec5SDimitry Andric template <class ELFT>
4220b57cec5SDimitry Andric StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
4230b57cec5SDimitry Andric                                               const Elf_Shdr &sec) {
4240b57cec5SDimitry Andric   typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
4250b57cec5SDimitry Andric   if (sec.sh_info >= symbols.size())
4260b57cec5SDimitry Andric     fatal(toString(this) + ": invalid symbol index");
4270b57cec5SDimitry Andric   const typename ELFT::Sym &sym = symbols[sec.sh_info];
4280b57cec5SDimitry Andric   StringRef signature = CHECK(sym.getName(this->stringTable), this);
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   // As a special case, if a symbol is a section symbol and has no name,
4310b57cec5SDimitry Andric   // we use a section name as a signature.
4320b57cec5SDimitry Andric   //
4330b57cec5SDimitry Andric   // Such SHT_GROUP sections are invalid from the perspective of the ELF
4340b57cec5SDimitry Andric   // standard, but GNU gold 1.14 (the newest version as of July 2017) or
4350b57cec5SDimitry Andric   // older produce such sections as outputs for the -r option, so we need
4360b57cec5SDimitry Andric   // a bug-compatibility.
4370b57cec5SDimitry Andric   if (signature.empty() && sym.getType() == STT_SECTION)
4380b57cec5SDimitry Andric     return getSectionName(sec);
4390b57cec5SDimitry Andric   return signature;
4400b57cec5SDimitry Andric }
4410b57cec5SDimitry Andric 
44285868e8aSDimitry Andric template <class ELFT>
44385868e8aSDimitry Andric bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
4445ffd83dbSDimitry Andric   if (!(sec.sh_flags & SHF_MERGE))
4455ffd83dbSDimitry Andric     return false;
4465ffd83dbSDimitry Andric 
4470b57cec5SDimitry Andric   // On a regular link we don't merge sections if -O0 (default is -O1). This
4480b57cec5SDimitry Andric   // sometimes makes the linker significantly faster, although the output will
4490b57cec5SDimitry Andric   // be bigger.
4500b57cec5SDimitry Andric   //
4510b57cec5SDimitry Andric   // Doing the same for -r would create a problem as it would combine sections
4520b57cec5SDimitry Andric   // with different sh_entsize. One option would be to just copy every SHF_MERGE
4530b57cec5SDimitry Andric   // section as is to the output. While this would produce a valid ELF file with
4540b57cec5SDimitry Andric   // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
4550b57cec5SDimitry Andric   // they see two .debug_str. We could have separate logic for combining
4560b57cec5SDimitry Andric   // SHF_MERGE sections based both on their name and sh_entsize, but that seems
4570b57cec5SDimitry Andric   // to be more trouble than it is worth. Instead, we just use the regular (-O1)
4580b57cec5SDimitry Andric   // logic for -r.
4590b57cec5SDimitry Andric   if (config->optimize == 0 && !config->relocatable)
4600b57cec5SDimitry Andric     return false;
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   // A mergeable section with size 0 is useless because they don't have
4630b57cec5SDimitry Andric   // any data to merge. A mergeable string section with size 0 can be
4640b57cec5SDimitry Andric   // argued as invalid because it doesn't end with a null character.
4650b57cec5SDimitry Andric   // We'll avoid a mess by handling them as if they were non-mergeable.
4660b57cec5SDimitry Andric   if (sec.sh_size == 0)
4670b57cec5SDimitry Andric     return false;
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   // Check for sh_entsize. The ELF spec is not clear about the zero
4700b57cec5SDimitry Andric   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
4710b57cec5SDimitry Andric   // the section does not hold a table of fixed-size entries". We know
4720b57cec5SDimitry Andric   // that Rust 1.13 produces a string mergeable section with a zero
4730b57cec5SDimitry Andric   // sh_entsize. Here we just accept it rather than being picky about it.
4740b57cec5SDimitry Andric   uint64_t entSize = sec.sh_entsize;
4750b57cec5SDimitry Andric   if (entSize == 0)
4760b57cec5SDimitry Andric     return false;
4770b57cec5SDimitry Andric   if (sec.sh_size % entSize)
47885868e8aSDimitry Andric     fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" +
47985868e8aSDimitry Andric           Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" +
48085868e8aSDimitry Andric           Twine(entSize) + ")");
4810b57cec5SDimitry Andric 
4825ffd83dbSDimitry Andric   if (sec.sh_flags & SHF_WRITE)
48385868e8aSDimitry Andric     fatal(toString(this) + ":(" + name +
48485868e8aSDimitry Andric           "): writable SHF_MERGE section is not supported");
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   return true;
4870b57cec5SDimitry Andric }
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric // This is for --just-symbols.
4900b57cec5SDimitry Andric //
4910b57cec5SDimitry Andric // --just-symbols is a very minor feature that allows you to link your
4920b57cec5SDimitry Andric // output against other existing program, so that if you load both your
4930b57cec5SDimitry Andric // program and the other program into memory, your output can refer the
4940b57cec5SDimitry Andric // other program's symbols.
4950b57cec5SDimitry Andric //
4960b57cec5SDimitry Andric // When the option is given, we link "just symbols". The section table is
4970b57cec5SDimitry Andric // initialized with null pointers.
4980b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
4990b57cec5SDimitry Andric   ArrayRef<Elf_Shdr> sections = CHECK(this->getObj().sections(), this);
5000b57cec5SDimitry Andric   this->sections.resize(sections.size());
5010b57cec5SDimitry Andric }
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric // An ELF object file may contain a `.deplibs` section. If it exists, the
5040b57cec5SDimitry Andric // section contains a list of library specifiers such as `m` for libm. This
5050b57cec5SDimitry Andric // function resolves a given name by finding the first matching library checking
5060b57cec5SDimitry Andric // the various ways that a library can be specified to LLD. This ELF extension
5070b57cec5SDimitry Andric // is a form of autolinking and is called `dependent libraries`. It is currently
5080b57cec5SDimitry Andric // unique to LLVM and lld.
5090b57cec5SDimitry Andric static void addDependentLibrary(StringRef specifier, const InputFile *f) {
5100b57cec5SDimitry Andric   if (!config->dependentLibraries)
5110b57cec5SDimitry Andric     return;
5120b57cec5SDimitry Andric   if (fs::exists(specifier))
5130b57cec5SDimitry Andric     driver->addFile(specifier, /*withLOption=*/false);
5140b57cec5SDimitry Andric   else if (Optional<std::string> s = findFromSearchPaths(specifier))
5150b57cec5SDimitry Andric     driver->addFile(*s, /*withLOption=*/true);
5160b57cec5SDimitry Andric   else if (Optional<std::string> s = searchLibraryBaseName(specifier))
5170b57cec5SDimitry Andric     driver->addFile(*s, /*withLOption=*/true);
5180b57cec5SDimitry Andric   else
5190b57cec5SDimitry Andric     error(toString(f) +
5200b57cec5SDimitry Andric           ": unable to find library from dependent library specifier: " +
5210b57cec5SDimitry Andric           specifier);
5220b57cec5SDimitry Andric }
5230b57cec5SDimitry Andric 
524480093f4SDimitry Andric // Record the membership of a section group so that in the garbage collection
525480093f4SDimitry Andric // pass, section group members are kept or discarded as a unit.
526480093f4SDimitry Andric template <class ELFT>
527480093f4SDimitry Andric static void handleSectionGroup(ArrayRef<InputSectionBase *> sections,
528480093f4SDimitry Andric                                ArrayRef<typename ELFT::Word> entries) {
529480093f4SDimitry Andric   bool hasAlloc = false;
530480093f4SDimitry Andric   for (uint32_t index : entries.slice(1)) {
531480093f4SDimitry Andric     if (index >= sections.size())
532480093f4SDimitry Andric       return;
533480093f4SDimitry Andric     if (InputSectionBase *s = sections[index])
534480093f4SDimitry Andric       if (s != &InputSection::discarded && s->flags & SHF_ALLOC)
535480093f4SDimitry Andric         hasAlloc = true;
536480093f4SDimitry Andric   }
537480093f4SDimitry Andric 
538480093f4SDimitry Andric   // If any member has the SHF_ALLOC flag, the whole group is subject to garbage
539480093f4SDimitry Andric   // collection. See the comment in markLive(). This rule retains .debug_types
540480093f4SDimitry Andric   // and .rela.debug_types.
541480093f4SDimitry Andric   if (!hasAlloc)
542480093f4SDimitry Andric     return;
543480093f4SDimitry Andric 
544480093f4SDimitry Andric   // Connect the members in a circular doubly-linked list via
545480093f4SDimitry Andric   // nextInSectionGroup.
546480093f4SDimitry Andric   InputSectionBase *head;
547480093f4SDimitry Andric   InputSectionBase *prev = nullptr;
548480093f4SDimitry Andric   for (uint32_t index : entries.slice(1)) {
549480093f4SDimitry Andric     InputSectionBase *s = sections[index];
550480093f4SDimitry Andric     if (!s || s == &InputSection::discarded)
551480093f4SDimitry Andric       continue;
552480093f4SDimitry Andric     if (prev)
553480093f4SDimitry Andric       prev->nextInSectionGroup = s;
554480093f4SDimitry Andric     else
555480093f4SDimitry Andric       head = s;
556480093f4SDimitry Andric     prev = s;
557480093f4SDimitry Andric   }
558480093f4SDimitry Andric   if (prev)
559480093f4SDimitry Andric     prev->nextInSectionGroup = head;
560480093f4SDimitry Andric }
561480093f4SDimitry Andric 
5620b57cec5SDimitry Andric template <class ELFT>
5630b57cec5SDimitry Andric void ObjFile<ELFT>::initializeSections(bool ignoreComdats) {
5640b57cec5SDimitry Andric   const ELFFile<ELFT> &obj = this->getObj();
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric   ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this);
5670b57cec5SDimitry Andric   uint64_t size = objSections.size();
5680b57cec5SDimitry Andric   this->sections.resize(size);
5690b57cec5SDimitry Andric   this->sectionStringTable =
5700b57cec5SDimitry Andric       CHECK(obj.getSectionStringTable(objSections), this);
5710b57cec5SDimitry Andric 
572480093f4SDimitry Andric   std::vector<ArrayRef<Elf_Word>> selectedGroups;
573480093f4SDimitry Andric 
57485868e8aSDimitry Andric   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
5750b57cec5SDimitry Andric     if (this->sections[i] == &InputSection::discarded)
5760b57cec5SDimitry Andric       continue;
5770b57cec5SDimitry Andric     const Elf_Shdr &sec = objSections[i];
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric     if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
5800b57cec5SDimitry Andric       cgProfile =
581*e8d8bef9SDimitry Andric           check(obj.template getSectionContentsAsArray<Elf_CGProfile>(sec));
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)
5950b57cec5SDimitry Andric           warn(toString(this) + ": --icf=safe is incompatible with object "
5960b57cec5SDimitry Andric                                 "files created using objcopy or ld -r");
5970b57cec5SDimitry Andric       }
5980b57cec5SDimitry Andric       this->sections[i] = &InputSection::discarded;
5990b57cec5SDimitry Andric       continue;
6000b57cec5SDimitry Andric     }
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric     switch (sec.sh_type) {
6030b57cec5SDimitry Andric     case SHT_GROUP: {
6040b57cec5SDimitry Andric       // De-duplicate section groups by their signatures.
6050b57cec5SDimitry Andric       StringRef signature = getShtGroupSignature(objSections, sec);
6060b57cec5SDimitry Andric       this->sections[i] = &InputSection::discarded;
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric       ArrayRef<Elf_Word> entries =
610*e8d8bef9SDimitry Andric           CHECK(obj.template getSectionContentsAsArray<Elf_Word>(sec), this);
6110b57cec5SDimitry Andric       if (entries.empty())
6120b57cec5SDimitry Andric         fatal(toString(this) + ": empty SHT_GROUP");
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric       // The first word of a SHT_GROUP section contains flags. Currently,
6150b57cec5SDimitry Andric       // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
6160b57cec5SDimitry Andric       // An group with the empty flag doesn't define anything; such sections
6170b57cec5SDimitry Andric       // are just skipped.
6180b57cec5SDimitry Andric       if (entries[0] == 0)
6190b57cec5SDimitry Andric         continue;
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric       if (entries[0] != GRP_COMDAT)
6220b57cec5SDimitry Andric         fatal(toString(this) + ": unsupported SHT_GROUP format");
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric       bool isNew =
6250b57cec5SDimitry Andric           ignoreComdats ||
6260b57cec5SDimitry Andric           symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
6270b57cec5SDimitry Andric               .second;
6280b57cec5SDimitry Andric       if (isNew) {
6290b57cec5SDimitry Andric         if (config->relocatable)
6300b57cec5SDimitry Andric           this->sections[i] = createInputSection(sec);
631480093f4SDimitry Andric         selectedGroups.push_back(entries);
6320b57cec5SDimitry Andric         continue;
6330b57cec5SDimitry Andric       }
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric       // Otherwise, discard group members.
6360b57cec5SDimitry Andric       for (uint32_t secIndex : entries.slice(1)) {
6370b57cec5SDimitry Andric         if (secIndex >= size)
6380b57cec5SDimitry Andric           fatal(toString(this) +
6390b57cec5SDimitry Andric                 ": invalid section index in group: " + Twine(secIndex));
6400b57cec5SDimitry Andric         this->sections[secIndex] = &InputSection::discarded;
6410b57cec5SDimitry Andric       }
6420b57cec5SDimitry Andric       break;
6430b57cec5SDimitry Andric     }
6440b57cec5SDimitry Andric     case SHT_SYMTAB_SHNDX:
6450b57cec5SDimitry Andric       shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
6460b57cec5SDimitry Andric       break;
6470b57cec5SDimitry Andric     case SHT_SYMTAB:
6480b57cec5SDimitry Andric     case SHT_STRTAB:
6495ffd83dbSDimitry Andric     case SHT_REL:
6505ffd83dbSDimitry Andric     case SHT_RELA:
6510b57cec5SDimitry Andric     case SHT_NULL:
6520b57cec5SDimitry Andric       break;
6530b57cec5SDimitry Andric     default:
6540b57cec5SDimitry Andric       this->sections[i] = createInputSection(sec);
6550b57cec5SDimitry Andric     }
65685868e8aSDimitry Andric   }
65785868e8aSDimitry Andric 
6585ffd83dbSDimitry Andric   // We have a second loop. It is used to:
6595ffd83dbSDimitry Andric   // 1) handle SHF_LINK_ORDER sections.
6605ffd83dbSDimitry Andric   // 2) create SHT_REL[A] sections. In some cases the section header index of a
6615ffd83dbSDimitry Andric   //    relocation section may be smaller than that of the relocated section. In
6625ffd83dbSDimitry Andric   //    such cases, the relocation section would attempt to reference a target
6635ffd83dbSDimitry Andric   //    section that has not yet been created. For simplicity, delay creation of
6645ffd83dbSDimitry Andric   //    relocation sections until now.
66585868e8aSDimitry Andric   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
66685868e8aSDimitry Andric     if (this->sections[i] == &InputSection::discarded)
66785868e8aSDimitry Andric       continue;
66885868e8aSDimitry Andric     const Elf_Shdr &sec = objSections[i];
6695ffd83dbSDimitry Andric 
6705ffd83dbSDimitry Andric     if (sec.sh_type == SHT_REL || sec.sh_type == SHT_RELA)
6715ffd83dbSDimitry Andric       this->sections[i] = createInputSection(sec);
6725ffd83dbSDimitry Andric 
673*e8d8bef9SDimitry Andric     // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have
674*e8d8bef9SDimitry Andric     // the flag.
675*e8d8bef9SDimitry Andric     if (!(sec.sh_flags & SHF_LINK_ORDER) || !sec.sh_link)
67685868e8aSDimitry Andric       continue;
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric     InputSectionBase *linkSec = nullptr;
6790b57cec5SDimitry Andric     if (sec.sh_link < this->sections.size())
6800b57cec5SDimitry Andric       linkSec = this->sections[sec.sh_link];
6810b57cec5SDimitry Andric     if (!linkSec)
68285868e8aSDimitry Andric       fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
6830b57cec5SDimitry Andric 
684*e8d8bef9SDimitry Andric     // A SHF_LINK_ORDER section is discarded if its linked-to section is
685*e8d8bef9SDimitry Andric     // discarded.
6860b57cec5SDimitry Andric     InputSection *isec = cast<InputSection>(this->sections[i]);
6870b57cec5SDimitry Andric     linkSec->dependentSections.push_back(isec);
6880b57cec5SDimitry Andric     if (!isa<InputSection>(linkSec))
6890b57cec5SDimitry Andric       error("a section " + isec->name +
69085868e8aSDimitry Andric             " with SHF_LINK_ORDER should not refer a non-regular section: " +
6910b57cec5SDimitry Andric             toString(linkSec));
6920b57cec5SDimitry Andric   }
693480093f4SDimitry Andric 
694480093f4SDimitry Andric   for (ArrayRef<Elf_Word> entries : selectedGroups)
695480093f4SDimitry Andric     handleSectionGroup<ELFT>(this->sections, entries);
6960b57cec5SDimitry Andric }
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
6990b57cec5SDimitry Andric // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
7000b57cec5SDimitry Andric // the input objects have been compiled.
7010b57cec5SDimitry Andric static void updateARMVFPArgs(const ARMAttributeParser &attributes,
7020b57cec5SDimitry Andric                              const InputFile *f) {
7035ffd83dbSDimitry Andric   Optional<unsigned> attr =
7045ffd83dbSDimitry Andric       attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
7055ffd83dbSDimitry Andric   if (!attr.hasValue())
7060b57cec5SDimitry Andric     // If an ABI tag isn't present then it is implicitly given the value of 0
7070b57cec5SDimitry Andric     // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
7080b57cec5SDimitry Andric     // including some in glibc that don't use FP args (and should have value 3)
7090b57cec5SDimitry Andric     // don't have the attribute so we do not consider an implicit value of 0
7100b57cec5SDimitry Andric     // as a clash.
7110b57cec5SDimitry Andric     return;
7120b57cec5SDimitry Andric 
7135ffd83dbSDimitry Andric   unsigned vfpArgs = attr.getValue();
7140b57cec5SDimitry Andric   ARMVFPArgKind arg;
7150b57cec5SDimitry Andric   switch (vfpArgs) {
7160b57cec5SDimitry Andric   case ARMBuildAttrs::BaseAAPCS:
7170b57cec5SDimitry Andric     arg = ARMVFPArgKind::Base;
7180b57cec5SDimitry Andric     break;
7190b57cec5SDimitry Andric   case ARMBuildAttrs::HardFPAAPCS:
7200b57cec5SDimitry Andric     arg = ARMVFPArgKind::VFP;
7210b57cec5SDimitry Andric     break;
7220b57cec5SDimitry Andric   case ARMBuildAttrs::ToolChainFPPCS:
7230b57cec5SDimitry Andric     // Tool chain specific convention that conforms to neither AAPCS variant.
7240b57cec5SDimitry Andric     arg = ARMVFPArgKind::ToolChain;
7250b57cec5SDimitry Andric     break;
7260b57cec5SDimitry Andric   case ARMBuildAttrs::CompatibleFPAAPCS:
7270b57cec5SDimitry Andric     // Object compatible with all conventions.
7280b57cec5SDimitry Andric     return;
7290b57cec5SDimitry Andric   default:
7300b57cec5SDimitry Andric     error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs));
7310b57cec5SDimitry Andric     return;
7320b57cec5SDimitry Andric   }
7330b57cec5SDimitry Andric   // Follow ld.bfd and error if there is a mix of calling conventions.
7340b57cec5SDimitry Andric   if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default)
7350b57cec5SDimitry Andric     error(toString(f) + ": incompatible Tag_ABI_VFP_args");
7360b57cec5SDimitry Andric   else
7370b57cec5SDimitry Andric     config->armVFPArgs = arg;
7380b57cec5SDimitry Andric }
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric // The ARM support in lld makes some use of instructions that are not available
7410b57cec5SDimitry Andric // on all ARM architectures. Namely:
7420b57cec5SDimitry Andric // - Use of BLX instruction for interworking between ARM and Thumb state.
7430b57cec5SDimitry Andric // - Use of the extended Thumb branch encoding in relocation.
7440b57cec5SDimitry Andric // - Use of the MOVT/MOVW instructions in Thumb Thunks.
7450b57cec5SDimitry Andric // The ARM Attributes section contains information about the architecture chosen
7460b57cec5SDimitry Andric // at compile time. We follow the convention that if at least one input object
7470b57cec5SDimitry Andric // is compiled with an architecture that supports these features then lld is
7480b57cec5SDimitry Andric // permitted to use them.
7490b57cec5SDimitry Andric static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
7505ffd83dbSDimitry Andric   Optional<unsigned> attr =
7515ffd83dbSDimitry Andric       attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
7525ffd83dbSDimitry Andric   if (!attr.hasValue())
7530b57cec5SDimitry Andric     return;
7545ffd83dbSDimitry Andric   auto arch = attr.getValue();
7550b57cec5SDimitry Andric   switch (arch) {
7560b57cec5SDimitry Andric   case ARMBuildAttrs::Pre_v4:
7570b57cec5SDimitry Andric   case ARMBuildAttrs::v4:
7580b57cec5SDimitry Andric   case ARMBuildAttrs::v4T:
7590b57cec5SDimitry Andric     // Architectures prior to v5 do not support BLX instruction
7600b57cec5SDimitry Andric     break;
7610b57cec5SDimitry Andric   case ARMBuildAttrs::v5T:
7620b57cec5SDimitry Andric   case ARMBuildAttrs::v5TE:
7630b57cec5SDimitry Andric   case ARMBuildAttrs::v5TEJ:
7640b57cec5SDimitry Andric   case ARMBuildAttrs::v6:
7650b57cec5SDimitry Andric   case ARMBuildAttrs::v6KZ:
7660b57cec5SDimitry Andric   case ARMBuildAttrs::v6K:
7670b57cec5SDimitry Andric     config->armHasBlx = true;
7680b57cec5SDimitry Andric     // Architectures used in pre-Cortex processors do not support
7690b57cec5SDimitry Andric     // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
7700b57cec5SDimitry Andric     // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
7710b57cec5SDimitry Andric     break;
7720b57cec5SDimitry Andric   default:
7730b57cec5SDimitry Andric     // All other Architectures have BLX and extended branch encoding
7740b57cec5SDimitry Andric     config->armHasBlx = true;
7750b57cec5SDimitry Andric     config->armJ1J2BranchEncoding = true;
7760b57cec5SDimitry Andric     if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
7770b57cec5SDimitry Andric       // All Architectures used in Cortex processors with the exception
7780b57cec5SDimitry Andric       // of v6-M and v6S-M have the MOVT and MOVW instructions.
7790b57cec5SDimitry Andric       config->armHasMovtMovw = true;
7800b57cec5SDimitry Andric     break;
7810b57cec5SDimitry Andric   }
7820b57cec5SDimitry Andric }
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric // If a source file is compiled with x86 hardware-assisted call flow control
7850b57cec5SDimitry Andric // enabled, the generated object file contains feature flags indicating that
7860b57cec5SDimitry Andric // fact. This function reads the feature flags and returns it.
7870b57cec5SDimitry Andric //
7880b57cec5SDimitry Andric // Essentially we want to read a single 32-bit value in this function, but this
7890b57cec5SDimitry Andric // function is rather complicated because the value is buried deep inside a
7900b57cec5SDimitry Andric // .note.gnu.property section.
7910b57cec5SDimitry Andric //
7920b57cec5SDimitry Andric // The section consists of one or more NOTE records. Each NOTE record consists
7930b57cec5SDimitry Andric // of zero or more type-length-value fields. We want to find a field of a
7940b57cec5SDimitry Andric // certain type. It seems a bit too much to just store a 32-bit value, perhaps
7950b57cec5SDimitry Andric // the ABI is unnecessarily complicated.
796*e8d8bef9SDimitry Andric template <class ELFT> static uint32_t readAndFeatures(const InputSection &sec) {
7970b57cec5SDimitry Andric   using Elf_Nhdr = typename ELFT::Nhdr;
7980b57cec5SDimitry Andric   using Elf_Note = typename ELFT::Note;
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   uint32_t featuresSet = 0;
801*e8d8bef9SDimitry Andric   ArrayRef<uint8_t> data = sec.data();
802*e8d8bef9SDimitry Andric   auto reportFatal = [&](const uint8_t *place, const char *msg) {
803*e8d8bef9SDimitry Andric     fatal(toString(sec.file) + ":(" + sec.name + "+0x" +
804*e8d8bef9SDimitry Andric           Twine::utohexstr(place - sec.data().data()) + "): " + msg);
805*e8d8bef9SDimitry Andric   };
8060b57cec5SDimitry Andric   while (!data.empty()) {
8070b57cec5SDimitry Andric     // Read one NOTE record.
8080b57cec5SDimitry Andric     auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
809*e8d8bef9SDimitry Andric     if (data.size() < sizeof(Elf_Nhdr) || data.size() < nhdr->getSize())
810*e8d8bef9SDimitry Andric       reportFatal(data.data(), "data is too short");
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric     Elf_Note note(*nhdr);
8130b57cec5SDimitry Andric     if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
8140b57cec5SDimitry Andric       data = data.slice(nhdr->getSize());
8150b57cec5SDimitry Andric       continue;
8160b57cec5SDimitry Andric     }
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric     uint32_t featureAndType = config->emachine == EM_AARCH64
8190b57cec5SDimitry Andric                                   ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
8200b57cec5SDimitry Andric                                   : GNU_PROPERTY_X86_FEATURE_1_AND;
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric     // Read a body of a NOTE record, which consists of type-length-value fields.
8230b57cec5SDimitry Andric     ArrayRef<uint8_t> desc = note.getDesc();
8240b57cec5SDimitry Andric     while (!desc.empty()) {
825*e8d8bef9SDimitry Andric       const uint8_t *place = desc.data();
8260b57cec5SDimitry Andric       if (desc.size() < 8)
827*e8d8bef9SDimitry Andric         reportFatal(place, "program property is too short");
828*e8d8bef9SDimitry Andric       uint32_t type = read32<ELFT::TargetEndianness>(desc.data());
829*e8d8bef9SDimitry Andric       uint32_t size = read32<ELFT::TargetEndianness>(desc.data() + 4);
830*e8d8bef9SDimitry Andric       desc = desc.slice(8);
831*e8d8bef9SDimitry Andric       if (desc.size() < size)
832*e8d8bef9SDimitry Andric         reportFatal(place, "program property is too short");
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric       if (type == featureAndType) {
8350b57cec5SDimitry Andric         // We found a FEATURE_1_AND field. There may be more than one of these
836480093f4SDimitry Andric         // in a .note.gnu.property section, for a relocatable object we
8370b57cec5SDimitry Andric         // accumulate the bits set.
838*e8d8bef9SDimitry Andric         if (size < 4)
839*e8d8bef9SDimitry Andric           reportFatal(place, "FEATURE_1_AND entry is too short");
840*e8d8bef9SDimitry Andric         featuresSet |= read32<ELFT::TargetEndianness>(desc.data());
8410b57cec5SDimitry Andric       }
8420b57cec5SDimitry Andric 
843*e8d8bef9SDimitry Andric       // Padding is present in the note descriptor, if necessary.
844*e8d8bef9SDimitry Andric       desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size));
8450b57cec5SDimitry Andric     }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric     // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
8480b57cec5SDimitry Andric     data = data.slice(nhdr->getSize());
8490b57cec5SDimitry Andric   }
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric   return featuresSet;
8520b57cec5SDimitry Andric }
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric template <class ELFT>
8550b57cec5SDimitry Andric InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
8560b57cec5SDimitry Andric   uint32_t idx = sec.sh_info;
8570b57cec5SDimitry Andric   if (idx >= this->sections.size())
8580b57cec5SDimitry Andric     fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
8590b57cec5SDimitry Andric   InputSectionBase *target = this->sections[idx];
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric   // Strictly speaking, a relocation section must be included in the
8620b57cec5SDimitry Andric   // group of the section it relocates. However, LLVM 3.3 and earlier
8630b57cec5SDimitry Andric   // would fail to do so, so we gracefully handle that case.
8640b57cec5SDimitry Andric   if (target == &InputSection::discarded)
8650b57cec5SDimitry Andric     return nullptr;
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric   if (!target)
8680b57cec5SDimitry Andric     fatal(toString(this) + ": unsupported relocation reference");
8690b57cec5SDimitry Andric   return target;
8700b57cec5SDimitry Andric }
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric // Create a regular InputSection class that has the same contents
8730b57cec5SDimitry Andric // as a given section.
8740b57cec5SDimitry Andric static InputSection *toRegularSection(MergeInputSection *sec) {
8750b57cec5SDimitry Andric   return make<InputSection>(sec->file, sec->flags, sec->type, sec->alignment,
8760b57cec5SDimitry Andric                             sec->data(), sec->name);
8770b57cec5SDimitry Andric }
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric template <class ELFT>
8800b57cec5SDimitry Andric InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
8810b57cec5SDimitry Andric   StringRef name = getSectionName(sec);
8820b57cec5SDimitry Andric 
883*e8d8bef9SDimitry Andric   if (config->emachine == EM_ARM && sec.sh_type == SHT_ARM_ATTRIBUTES) {
8840b57cec5SDimitry Andric     ARMAttributeParser attributes;
885*e8d8bef9SDimitry Andric     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec));
8865ffd83dbSDimitry Andric     if (Error e = attributes.parse(contents, config->ekind == ELF32LEKind
8875ffd83dbSDimitry Andric                                                  ? support::little
8885ffd83dbSDimitry Andric                                                  : support::big)) {
8895ffd83dbSDimitry Andric       auto *isec = make<InputSection>(*this, sec, name);
8905ffd83dbSDimitry Andric       warn(toString(isec) + ": " + llvm::toString(std::move(e)));
891*e8d8bef9SDimitry Andric     } else {
8920b57cec5SDimitry Andric       updateSupportedARMFeatures(attributes);
8930b57cec5SDimitry Andric       updateARMVFPArgs(attributes, this);
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric       // FIXME: Retain the first attribute section we see. The eglibc ARM
8960b57cec5SDimitry Andric       // dynamic loaders require the presence of an attribute section for dlopen
897*e8d8bef9SDimitry Andric       // to work. In a full implementation we would merge all attribute
898*e8d8bef9SDimitry Andric       // sections.
899*e8d8bef9SDimitry Andric       if (in.attributes == nullptr) {
900*e8d8bef9SDimitry Andric         in.attributes = make<InputSection>(*this, sec, name);
901*e8d8bef9SDimitry Andric         return in.attributes;
9020b57cec5SDimitry Andric       }
9030b57cec5SDimitry Andric       return &InputSection::discarded;
9040b57cec5SDimitry Andric     }
905*e8d8bef9SDimitry Andric   }
906*e8d8bef9SDimitry Andric 
907*e8d8bef9SDimitry Andric   if (config->emachine == EM_RISCV && sec.sh_type == SHT_RISCV_ATTRIBUTES) {
908*e8d8bef9SDimitry Andric     RISCVAttributeParser attributes;
909*e8d8bef9SDimitry Andric     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec));
910*e8d8bef9SDimitry Andric     if (Error e = attributes.parse(contents, support::little)) {
911*e8d8bef9SDimitry Andric       auto *isec = make<InputSection>(*this, sec, name);
912*e8d8bef9SDimitry Andric       warn(toString(isec) + ": " + llvm::toString(std::move(e)));
913*e8d8bef9SDimitry Andric     } else {
914*e8d8bef9SDimitry Andric       // FIXME: Validate arch tag contains C if and only if EF_RISCV_RVC is
915*e8d8bef9SDimitry Andric       // present.
916*e8d8bef9SDimitry Andric 
917*e8d8bef9SDimitry Andric       // FIXME: Retain the first attribute section we see. Tools such as
918*e8d8bef9SDimitry Andric       // llvm-objdump make use of the attribute section to determine which
919*e8d8bef9SDimitry Andric       // standard extensions to enable. In a full implementation we would merge
920*e8d8bef9SDimitry Andric       // all attribute sections.
921*e8d8bef9SDimitry Andric       if (in.attributes == nullptr) {
922*e8d8bef9SDimitry Andric         in.attributes = make<InputSection>(*this, sec, name);
923*e8d8bef9SDimitry Andric         return in.attributes;
924*e8d8bef9SDimitry Andric       }
925*e8d8bef9SDimitry Andric       return &InputSection::discarded;
926*e8d8bef9SDimitry Andric     }
927*e8d8bef9SDimitry Andric   }
928*e8d8bef9SDimitry Andric 
929*e8d8bef9SDimitry Andric   switch (sec.sh_type) {
9300b57cec5SDimitry Andric   case SHT_LLVM_DEPENDENT_LIBRARIES: {
9310b57cec5SDimitry Andric     if (config->relocatable)
9320b57cec5SDimitry Andric       break;
9330b57cec5SDimitry Andric     ArrayRef<char> data =
934*e8d8bef9SDimitry Andric         CHECK(this->getObj().template getSectionContentsAsArray<char>(sec), this);
9350b57cec5SDimitry Andric     if (!data.empty() && data.back() != '\0') {
9360b57cec5SDimitry Andric       error(toString(this) +
9370b57cec5SDimitry Andric             ": corrupted dependent libraries section (unterminated string): " +
9380b57cec5SDimitry Andric             name);
9390b57cec5SDimitry Andric       return &InputSection::discarded;
9400b57cec5SDimitry Andric     }
9410b57cec5SDimitry Andric     for (const char *d = data.begin(), *e = data.end(); d < e;) {
9420b57cec5SDimitry Andric       StringRef s(d);
9430b57cec5SDimitry Andric       addDependentLibrary(s, this);
9440b57cec5SDimitry Andric       d += s.size() + 1;
9450b57cec5SDimitry Andric     }
9460b57cec5SDimitry Andric     return &InputSection::discarded;
9470b57cec5SDimitry Andric   }
9480b57cec5SDimitry Andric   case SHT_RELA:
9490b57cec5SDimitry Andric   case SHT_REL: {
9500b57cec5SDimitry Andric     // Find a relocation target section and associate this section with that.
9510b57cec5SDimitry Andric     // Target may have been discarded if it is in a different section group
9520b57cec5SDimitry Andric     // and the group is discarded, even though it's a violation of the
9530b57cec5SDimitry Andric     // spec. We handle that situation gracefully by discarding dangling
9540b57cec5SDimitry Andric     // relocation sections.
9550b57cec5SDimitry Andric     InputSectionBase *target = getRelocTarget(sec);
9560b57cec5SDimitry Andric     if (!target)
9570b57cec5SDimitry Andric       return nullptr;
9580b57cec5SDimitry Andric 
959480093f4SDimitry Andric     // ELF spec allows mergeable sections with relocations, but they are
960480093f4SDimitry Andric     // rare, and it is in practice hard to merge such sections by contents,
961480093f4SDimitry Andric     // because applying relocations at end of linking changes section
962480093f4SDimitry Andric     // contents. So, we simply handle such sections as non-mergeable ones.
963480093f4SDimitry Andric     // Degrading like this is acceptable because section merging is optional.
964480093f4SDimitry Andric     if (auto *ms = dyn_cast<MergeInputSection>(target)) {
965480093f4SDimitry Andric       target = toRegularSection(ms);
966480093f4SDimitry Andric       this->sections[sec.sh_info] = target;
967480093f4SDimitry Andric     }
968480093f4SDimitry Andric 
9690b57cec5SDimitry Andric     if (target->firstRelocation)
9700b57cec5SDimitry Andric       fatal(toString(this) +
9710b57cec5SDimitry Andric             ": multiple relocation sections to one section are not supported");
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric     if (sec.sh_type == SHT_RELA) {
974*e8d8bef9SDimitry Andric       ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(sec), this);
9750b57cec5SDimitry Andric       target->firstRelocation = rels.begin();
9760b57cec5SDimitry Andric       target->numRelocations = rels.size();
9770b57cec5SDimitry Andric       target->areRelocsRela = true;
9780b57cec5SDimitry Andric     } else {
979*e8d8bef9SDimitry Andric       ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(sec), this);
9800b57cec5SDimitry Andric       target->firstRelocation = rels.begin();
9810b57cec5SDimitry Andric       target->numRelocations = rels.size();
9820b57cec5SDimitry Andric       target->areRelocsRela = false;
9830b57cec5SDimitry Andric     }
9840b57cec5SDimitry Andric     assert(isUInt<31>(target->numRelocations));
9850b57cec5SDimitry Andric 
986*e8d8bef9SDimitry Andric     // Relocation sections are usually removed from the output, so return
987*e8d8bef9SDimitry Andric     // `nullptr` for the normal case. However, if -r or --emit-relocs is
988*e8d8bef9SDimitry Andric     // specified, we need to copy them to the output. (Some post link analysis
989*e8d8bef9SDimitry Andric     // tools specify --emit-relocs to obtain the information.)
990*e8d8bef9SDimitry Andric     if (!config->relocatable && !config->emitRelocs)
991*e8d8bef9SDimitry Andric       return nullptr;
9920b57cec5SDimitry Andric     InputSection *relocSec = make<InputSection>(*this, sec, name);
993*e8d8bef9SDimitry Andric     // If the relocated section is discarded (due to /DISCARD/ or
994*e8d8bef9SDimitry Andric     // --gc-sections), the relocation section should be discarded as well.
9950b57cec5SDimitry Andric     target->dependentSections.push_back(relocSec);
9960b57cec5SDimitry Andric     return relocSec;
9970b57cec5SDimitry Andric   }
9980b57cec5SDimitry Andric   }
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric   // The GNU linker uses .note.GNU-stack section as a marker indicating
10010b57cec5SDimitry Andric   // that the code in the object file does not expect that the stack is
10020b57cec5SDimitry Andric   // executable (in terms of NX bit). If all input files have the marker,
10030b57cec5SDimitry Andric   // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
10040b57cec5SDimitry Andric   // make the stack non-executable. Most object files have this section as
10050b57cec5SDimitry Andric   // of 2017.
10060b57cec5SDimitry Andric   //
10070b57cec5SDimitry Andric   // But making the stack non-executable is a norm today for security
10080b57cec5SDimitry Andric   // reasons. Failure to do so may result in a serious security issue.
10090b57cec5SDimitry Andric   // Therefore, we make LLD always add PT_GNU_STACK unless it is
10100b57cec5SDimitry Andric   // explicitly told to do otherwise (by -z execstack). Because the stack
10110b57cec5SDimitry Andric   // executable-ness is controlled solely by command line options,
10120b57cec5SDimitry Andric   // .note.GNU-stack sections are simply ignored.
10130b57cec5SDimitry Andric   if (name == ".note.GNU-stack")
10140b57cec5SDimitry Andric     return &InputSection::discarded;
10150b57cec5SDimitry Andric 
10160b57cec5SDimitry Andric   // Object files that use processor features such as Intel Control-Flow
10170b57cec5SDimitry Andric   // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
10180b57cec5SDimitry Andric   // .note.gnu.property section containing a bitfield of feature bits like the
10190b57cec5SDimitry Andric   // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
10200b57cec5SDimitry Andric   //
10210b57cec5SDimitry Andric   // Since we merge bitmaps from multiple object files to create a new
10220b57cec5SDimitry Andric   // .note.gnu.property containing a single AND'ed bitmap, we discard an input
10230b57cec5SDimitry Andric   // file's .note.gnu.property section.
10240b57cec5SDimitry Andric   if (name == ".note.gnu.property") {
1025*e8d8bef9SDimitry Andric     this->andFeatures = readAndFeatures<ELFT>(InputSection(*this, sec, name));
10260b57cec5SDimitry Andric     return &InputSection::discarded;
10270b57cec5SDimitry Andric   }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   // Split stacks is a feature to support a discontiguous stack,
10300b57cec5SDimitry Andric   // commonly used in the programming language Go. For the details,
10310b57cec5SDimitry Andric   // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
10320b57cec5SDimitry Andric   // for split stack will include a .note.GNU-split-stack section.
10330b57cec5SDimitry Andric   if (name == ".note.GNU-split-stack") {
10340b57cec5SDimitry Andric     if (config->relocatable) {
10350b57cec5SDimitry Andric       error("cannot mix split-stack and non-split-stack in a relocatable link");
10360b57cec5SDimitry Andric       return &InputSection::discarded;
10370b57cec5SDimitry Andric     }
10380b57cec5SDimitry Andric     this->splitStack = true;
10390b57cec5SDimitry Andric     return &InputSection::discarded;
10400b57cec5SDimitry Andric   }
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric   // An object file cmpiled for split stack, but where some of the
10430b57cec5SDimitry Andric   // functions were compiled with the no_split_stack_attribute will
10440b57cec5SDimitry Andric   // include a .note.GNU-no-split-stack section.
10450b57cec5SDimitry Andric   if (name == ".note.GNU-no-split-stack") {
10460b57cec5SDimitry Andric     this->someNoSplitStack = true;
10470b57cec5SDimitry Andric     return &InputSection::discarded;
10480b57cec5SDimitry Andric   }
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
10510b57cec5SDimitry Andric   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
10520b57cec5SDimitry Andric   // sections. Drop those sections to avoid duplicate symbol errors.
10530b57cec5SDimitry Andric   // FIXME: This is glibc PR20543, we should remove this hack once that has been
10540b57cec5SDimitry Andric   // fixed for a while.
10550b57cec5SDimitry Andric   if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
10560b57cec5SDimitry Andric       name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
10570b57cec5SDimitry Andric     return &InputSection::discarded;
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric   // If we are creating a new .build-id section, strip existing .build-id
10600b57cec5SDimitry Andric   // sections so that the output won't have more than one .build-id.
10610b57cec5SDimitry Andric   // This is not usually a problem because input object files normally don't
10620b57cec5SDimitry Andric   // have .build-id sections, but you can create such files by
10630b57cec5SDimitry Andric   // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
10640b57cec5SDimitry Andric   if (name == ".note.gnu.build-id" && config->buildId != BuildIdKind::None)
10650b57cec5SDimitry Andric     return &InputSection::discarded;
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric   // The linker merges EH (exception handling) frames and creates a
10680b57cec5SDimitry Andric   // .eh_frame_hdr section for runtime. So we handle them with a special
10690b57cec5SDimitry Andric   // class. For relocatable outputs, they are just passed through.
10700b57cec5SDimitry Andric   if (name == ".eh_frame" && !config->relocatable)
10710b57cec5SDimitry Andric     return make<EhInputSection>(*this, sec, name);
10720b57cec5SDimitry Andric 
107385868e8aSDimitry Andric   if (shouldMerge(sec, name))
10740b57cec5SDimitry Andric     return make<MergeInputSection>(*this, sec, name);
10750b57cec5SDimitry Andric   return make<InputSection>(*this, sec, name);
10760b57cec5SDimitry Andric }
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric template <class ELFT>
10790b57cec5SDimitry Andric StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
1080*e8d8bef9SDimitry Andric   return CHECK(getObj().getSectionName(sec, sectionStringTable), this);
10810b57cec5SDimitry Andric }
10820b57cec5SDimitry Andric 
10830b57cec5SDimitry Andric // Initialize this->Symbols. this->Symbols is a parallel array as
10840b57cec5SDimitry Andric // its corresponding ELF symbol table.
10850b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
10860b57cec5SDimitry Andric   ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
10870b57cec5SDimitry Andric   this->symbols.resize(eSyms.size());
10880b57cec5SDimitry Andric 
10895ffd83dbSDimitry Andric   // Fill in InputFile::symbols. Some entries have been initialized
10900b57cec5SDimitry Andric   // because of LazyObjFile.
10910b57cec5SDimitry Andric   for (size_t i = 0, end = eSyms.size(); i != end; ++i) {
10925ffd83dbSDimitry Andric     if (this->symbols[i])
10935ffd83dbSDimitry Andric       continue;
10940b57cec5SDimitry Andric     const Elf_Sym &eSym = eSyms[i];
10950b57cec5SDimitry Andric     uint32_t secIdx = getSectionIndex(eSym);
10960b57cec5SDimitry Andric     if (secIdx >= this->sections.size())
10970b57cec5SDimitry Andric       fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
10985ffd83dbSDimitry Andric     if (eSym.getBinding() != STB_LOCAL) {
10995ffd83dbSDimitry Andric       if (i < firstGlobal)
11005ffd83dbSDimitry Andric         error(toString(this) + ": non-local symbol (" + Twine(i) +
11015ffd83dbSDimitry Andric               ") found at index < .symtab's sh_info (" + Twine(firstGlobal) +
11025ffd83dbSDimitry Andric               ")");
11035ffd83dbSDimitry Andric       this->symbols[i] =
11045ffd83dbSDimitry Andric           symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
11055ffd83dbSDimitry Andric       continue;
11065ffd83dbSDimitry Andric     }
11075ffd83dbSDimitry Andric 
11085ffd83dbSDimitry Andric     // Handle local symbols. Local symbols are not added to the symbol
11095ffd83dbSDimitry Andric     // table because they are not visible from other object files. We
11105ffd83dbSDimitry Andric     // allocate symbol instances and add their pointers to symbols.
11115ffd83dbSDimitry Andric     if (i >= firstGlobal)
11125ffd83dbSDimitry Andric       errorOrWarn(toString(this) + ": STB_LOCAL symbol (" + Twine(i) +
11135ffd83dbSDimitry Andric                   ") found at index >= .symtab's sh_info (" +
11145ffd83dbSDimitry Andric                   Twine(firstGlobal) + ")");
11150b57cec5SDimitry Andric 
11160b57cec5SDimitry Andric     InputSectionBase *sec = this->sections[secIdx];
11175ffd83dbSDimitry Andric     uint8_t type = eSym.getType();
11185ffd83dbSDimitry Andric     if (type == STT_FILE)
11195ffd83dbSDimitry Andric       sourceFile = CHECK(eSym.getName(this->stringTable), this);
11205ffd83dbSDimitry Andric     if (this->stringTable.size() <= eSym.st_name)
11215ffd83dbSDimitry Andric       fatal(toString(this) + ": invalid symbol name offset");
11225ffd83dbSDimitry Andric     StringRefZ name = this->stringTable.data() + eSym.st_name;
11235ffd83dbSDimitry Andric 
11245ffd83dbSDimitry Andric     if (eSym.st_shndx == SHN_UNDEF)
11255ffd83dbSDimitry Andric       this->symbols[i] =
11265ffd83dbSDimitry Andric           make<Undefined>(this, name, STB_LOCAL, eSym.st_other, type);
11275ffd83dbSDimitry Andric     else if (sec == &InputSection::discarded)
11285ffd83dbSDimitry Andric       this->symbols[i] =
11295ffd83dbSDimitry Andric           make<Undefined>(this, name, STB_LOCAL, eSym.st_other, type,
11305ffd83dbSDimitry Andric                           /*discardedSecIdx=*/secIdx);
11315ffd83dbSDimitry Andric     else
11325ffd83dbSDimitry Andric       this->symbols[i] = make<Defined>(this, name, STB_LOCAL, eSym.st_other,
11335ffd83dbSDimitry Andric                                        type, eSym.st_value, eSym.st_size, sec);
11345ffd83dbSDimitry Andric   }
11355ffd83dbSDimitry Andric 
11365ffd83dbSDimitry Andric   // Symbol resolution of non-local symbols.
11375ffd83dbSDimitry Andric   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
11385ffd83dbSDimitry Andric     const Elf_Sym &eSym = eSyms[i];
11390b57cec5SDimitry Andric     uint8_t binding = eSym.getBinding();
11405ffd83dbSDimitry Andric     if (binding == STB_LOCAL)
11415ffd83dbSDimitry Andric       continue; // Errored above.
11425ffd83dbSDimitry Andric 
11435ffd83dbSDimitry Andric     uint32_t secIdx = getSectionIndex(eSym);
11445ffd83dbSDimitry Andric     InputSectionBase *sec = this->sections[secIdx];
11450b57cec5SDimitry Andric     uint8_t stOther = eSym.st_other;
11460b57cec5SDimitry Andric     uint8_t type = eSym.getType();
11470b57cec5SDimitry Andric     uint64_t value = eSym.st_value;
11480b57cec5SDimitry Andric     uint64_t size = eSym.st_size;
11490b57cec5SDimitry Andric     StringRefZ name = this->stringTable.data() + eSym.st_name;
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric     // Handle global undefined symbols.
11520b57cec5SDimitry Andric     if (eSym.st_shndx == SHN_UNDEF) {
11530b57cec5SDimitry Andric       this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
115485868e8aSDimitry Andric       this->symbols[i]->referenced = true;
11550b57cec5SDimitry Andric       continue;
11560b57cec5SDimitry Andric     }
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric     // Handle global common symbols.
11590b57cec5SDimitry Andric     if (eSym.st_shndx == SHN_COMMON) {
11600b57cec5SDimitry Andric       if (value == 0 || value >= UINT32_MAX)
11610b57cec5SDimitry Andric         fatal(toString(this) + ": common symbol '" + StringRef(name.data) +
11620b57cec5SDimitry Andric               "' has invalid alignment: " + Twine(value));
11630b57cec5SDimitry Andric       this->symbols[i]->resolve(
11640b57cec5SDimitry Andric           CommonSymbol{this, name, binding, stOther, type, value, size});
11650b57cec5SDimitry Andric       continue;
11660b57cec5SDimitry Andric     }
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric     // If a defined symbol is in a discarded section, handle it as if it
11690b57cec5SDimitry Andric     // were an undefined symbol. Such symbol doesn't comply with the
11700b57cec5SDimitry Andric     // standard, but in practice, a .eh_frame often directly refer
11710b57cec5SDimitry Andric     // COMDAT member sections, and if a comdat group is discarded, some
11720b57cec5SDimitry Andric     // defined symbol in a .eh_frame becomes dangling symbols.
11730b57cec5SDimitry Andric     if (sec == &InputSection::discarded) {
11745ffd83dbSDimitry Andric       Undefined und{this, name, binding, stOther, type, secIdx};
11755ffd83dbSDimitry Andric       Symbol *sym = this->symbols[i];
11765ffd83dbSDimitry Andric       // !ArchiveFile::parsed or LazyObjFile::fetched means that the file
11775ffd83dbSDimitry Andric       // containing this object has not finished processing, i.e. this symbol is
11785ffd83dbSDimitry Andric       // a result of a lazy symbol fetch. We should demote the lazy symbol to an
11795ffd83dbSDimitry Andric       // Undefined so that any relocations outside of the group to it will
11805ffd83dbSDimitry Andric       // trigger a discarded section error.
11815ffd83dbSDimitry Andric       if ((sym->symbolKind == Symbol::LazyArchiveKind &&
11825ffd83dbSDimitry Andric            !cast<ArchiveFile>(sym->file)->parsed) ||
11835ffd83dbSDimitry Andric           (sym->symbolKind == Symbol::LazyObjectKind &&
11845ffd83dbSDimitry Andric            cast<LazyObjFile>(sym->file)->fetched))
11855ffd83dbSDimitry Andric         sym->replace(und);
11865ffd83dbSDimitry Andric       else
11875ffd83dbSDimitry Andric         sym->resolve(und);
11880b57cec5SDimitry Andric       continue;
11890b57cec5SDimitry Andric     }
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric     // Handle global defined symbols.
11920b57cec5SDimitry Andric     if (binding == STB_GLOBAL || binding == STB_WEAK ||
11930b57cec5SDimitry Andric         binding == STB_GNU_UNIQUE) {
11940b57cec5SDimitry Andric       this->symbols[i]->resolve(
11950b57cec5SDimitry Andric           Defined{this, name, binding, stOther, type, value, size, sec});
11960b57cec5SDimitry Andric       continue;
11970b57cec5SDimitry Andric     }
11980b57cec5SDimitry Andric 
11990b57cec5SDimitry Andric     fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
12000b57cec5SDimitry Andric   }
12010b57cec5SDimitry Andric }
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&file)
12040b57cec5SDimitry Andric     : InputFile(ArchiveKind, file->getMemoryBufferRef()),
12050b57cec5SDimitry Andric       file(std::move(file)) {}
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric void ArchiveFile::parse() {
12080b57cec5SDimitry Andric   for (const Archive::Symbol &sym : file->symbols())
12090b57cec5SDimitry Andric     symtab->addSymbol(LazyArchive{*this, sym});
12105ffd83dbSDimitry Andric 
12115ffd83dbSDimitry Andric   // Inform a future invocation of ObjFile<ELFT>::initializeSymbols() that this
12125ffd83dbSDimitry Andric   // archive has been processed.
12135ffd83dbSDimitry Andric   parsed = true;
12140b57cec5SDimitry Andric }
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric // Returns a buffer pointing to a member file containing a given symbol.
12170b57cec5SDimitry Andric void ArchiveFile::fetch(const Archive::Symbol &sym) {
12180b57cec5SDimitry Andric   Archive::Child c =
12190b57cec5SDimitry Andric       CHECK(sym.getMember(), toString(this) +
12200b57cec5SDimitry Andric                                  ": could not get the member for symbol " +
12210b57cec5SDimitry Andric                                  toELFString(sym));
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric   if (!seen.insert(c.getChildOffset()).second)
12240b57cec5SDimitry Andric     return;
12250b57cec5SDimitry Andric 
12260b57cec5SDimitry Andric   MemoryBufferRef mb =
12270b57cec5SDimitry Andric       CHECK(c.getMemoryBufferRef(),
12280b57cec5SDimitry Andric             toString(this) +
12290b57cec5SDimitry Andric                 ": could not get the buffer for the member defining symbol " +
12300b57cec5SDimitry Andric                 toELFString(sym));
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric   if (tar && c.getParent()->isThin())
12330b57cec5SDimitry Andric     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
12340b57cec5SDimitry Andric 
12355ffd83dbSDimitry Andric   InputFile *file = createObjectFile(mb, getName(), c.getChildOffset());
12360b57cec5SDimitry Andric   file->groupId = groupId;
12370b57cec5SDimitry Andric   parseFile(file);
12380b57cec5SDimitry Andric }
12390b57cec5SDimitry Andric 
1240*e8d8bef9SDimitry Andric // The handling of tentative definitions (COMMON symbols) in archives is murky.
1241*e8d8bef9SDimitry Andric // A tentative defintion will be promoted to a global definition if there are no
1242*e8d8bef9SDimitry Andric // non-tentative definitions to dominate it. When we hold a tentative definition
1243*e8d8bef9SDimitry Andric // to a symbol and are inspecting archive memebers for inclusion there are 2
1244*e8d8bef9SDimitry Andric // ways we can proceed:
1245*e8d8bef9SDimitry Andric //
1246*e8d8bef9SDimitry Andric // 1) Consider the tentative definition a 'real' definition (ie promotion from
1247*e8d8bef9SDimitry Andric //    tentative to real definition has already happened) and not inspect
1248*e8d8bef9SDimitry Andric //    archive members for Global/Weak definitions to replace the tentative
1249*e8d8bef9SDimitry Andric //    definition. An archive member would only be included if it satisfies some
1250*e8d8bef9SDimitry Andric //    other undefined symbol. This is the behavior Gold uses.
1251*e8d8bef9SDimitry Andric //
1252*e8d8bef9SDimitry Andric // 2) Consider the tentative definition as still undefined (ie the promotion to
1253*e8d8bef9SDimitry Andric //    a real definiton happens only after all symbol resolution is done).
1254*e8d8bef9SDimitry Andric //    The linker searches archive memebers for global or weak definitions to
1255*e8d8bef9SDimitry Andric //    replace the tentative definition with. This is the behavior used by
1256*e8d8bef9SDimitry Andric //    GNU ld.
1257*e8d8bef9SDimitry Andric //
1258*e8d8bef9SDimitry Andric //  The second behavior is inherited from SysVR4, which based it on the FORTRAN
1259*e8d8bef9SDimitry Andric //  COMMON BLOCK model. This behavior is needed for proper initalizations in old
1260*e8d8bef9SDimitry Andric //  (pre F90) FORTRAN code that is packaged into an archive.
1261*e8d8bef9SDimitry Andric //
1262*e8d8bef9SDimitry Andric //  The following functions search archive members for defintions to replace
1263*e8d8bef9SDimitry Andric //  tentative defintions (implementing behavior 2).
1264*e8d8bef9SDimitry Andric static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName,
1265*e8d8bef9SDimitry Andric                                   StringRef archiveName) {
1266*e8d8bef9SDimitry Andric   IRSymtabFile symtabFile = check(readIRSymtab(mb));
1267*e8d8bef9SDimitry Andric   for (const irsymtab::Reader::SymbolRef &sym :
1268*e8d8bef9SDimitry Andric        symtabFile.TheReader.symbols()) {
1269*e8d8bef9SDimitry Andric     if (sym.isGlobal() && sym.getName() == symName)
1270*e8d8bef9SDimitry Andric       return !sym.isUndefined() && !sym.isCommon();
1271*e8d8bef9SDimitry Andric   }
1272*e8d8bef9SDimitry Andric   return false;
1273*e8d8bef9SDimitry Andric }
1274*e8d8bef9SDimitry Andric 
1275*e8d8bef9SDimitry Andric template <class ELFT>
1276*e8d8bef9SDimitry Andric static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName,
1277*e8d8bef9SDimitry Andric                            StringRef archiveName) {
1278*e8d8bef9SDimitry Andric   ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(mb, archiveName);
1279*e8d8bef9SDimitry Andric   StringRef stringtable = obj->getStringTable();
1280*e8d8bef9SDimitry Andric 
1281*e8d8bef9SDimitry Andric   for (auto sym : obj->template getGlobalELFSyms<ELFT>()) {
1282*e8d8bef9SDimitry Andric     Expected<StringRef> name = sym.getName(stringtable);
1283*e8d8bef9SDimitry Andric     if (name && name.get() == symName)
1284*e8d8bef9SDimitry Andric       return sym.isDefined() && !sym.isCommon();
1285*e8d8bef9SDimitry Andric   }
1286*e8d8bef9SDimitry Andric   return false;
1287*e8d8bef9SDimitry Andric }
1288*e8d8bef9SDimitry Andric 
1289*e8d8bef9SDimitry Andric static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName,
1290*e8d8bef9SDimitry Andric                            StringRef archiveName) {
1291*e8d8bef9SDimitry Andric   switch (getELFKind(mb, archiveName)) {
1292*e8d8bef9SDimitry Andric   case ELF32LEKind:
1293*e8d8bef9SDimitry Andric     return isNonCommonDef<ELF32LE>(mb, symName, archiveName);
1294*e8d8bef9SDimitry Andric   case ELF32BEKind:
1295*e8d8bef9SDimitry Andric     return isNonCommonDef<ELF32BE>(mb, symName, archiveName);
1296*e8d8bef9SDimitry Andric   case ELF64LEKind:
1297*e8d8bef9SDimitry Andric     return isNonCommonDef<ELF64LE>(mb, symName, archiveName);
1298*e8d8bef9SDimitry Andric   case ELF64BEKind:
1299*e8d8bef9SDimitry Andric     return isNonCommonDef<ELF64BE>(mb, symName, archiveName);
1300*e8d8bef9SDimitry Andric   default:
1301*e8d8bef9SDimitry Andric     llvm_unreachable("getELFKind");
1302*e8d8bef9SDimitry Andric   }
1303*e8d8bef9SDimitry Andric }
1304*e8d8bef9SDimitry Andric 
1305*e8d8bef9SDimitry Andric bool ArchiveFile::shouldFetchForCommon(const Archive::Symbol &sym) {
1306*e8d8bef9SDimitry Andric   Archive::Child c =
1307*e8d8bef9SDimitry Andric       CHECK(sym.getMember(), toString(this) +
1308*e8d8bef9SDimitry Andric                                  ": could not get the member for symbol " +
1309*e8d8bef9SDimitry Andric                                  toELFString(sym));
1310*e8d8bef9SDimitry Andric   MemoryBufferRef mb =
1311*e8d8bef9SDimitry Andric       CHECK(c.getMemoryBufferRef(),
1312*e8d8bef9SDimitry Andric             toString(this) +
1313*e8d8bef9SDimitry Andric                 ": could not get the buffer for the member defining symbol " +
1314*e8d8bef9SDimitry Andric                 toELFString(sym));
1315*e8d8bef9SDimitry Andric 
1316*e8d8bef9SDimitry Andric   if (isBitcode(mb))
1317*e8d8bef9SDimitry Andric     return isBitcodeNonCommonDef(mb, sym.getName(), getName());
1318*e8d8bef9SDimitry Andric 
1319*e8d8bef9SDimitry Andric   return isNonCommonDef(mb, sym.getName(), getName());
1320*e8d8bef9SDimitry Andric }
1321*e8d8bef9SDimitry Andric 
13225ffd83dbSDimitry Andric size_t ArchiveFile::getMemberCount() const {
13235ffd83dbSDimitry Andric   size_t count = 0;
13245ffd83dbSDimitry Andric   Error err = Error::success();
13255ffd83dbSDimitry Andric   for (const Archive::Child &c : file->children(err)) {
13265ffd83dbSDimitry Andric     (void)c;
13275ffd83dbSDimitry Andric     ++count;
13285ffd83dbSDimitry Andric   }
13295ffd83dbSDimitry Andric   // This function is used by --print-archive-stats=, where an error does not
13305ffd83dbSDimitry Andric   // really matter.
13315ffd83dbSDimitry Andric   consumeError(std::move(err));
13325ffd83dbSDimitry Andric   return count;
13335ffd83dbSDimitry Andric }
13345ffd83dbSDimitry Andric 
13350b57cec5SDimitry Andric unsigned SharedFile::vernauxNum;
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric // Parse the version definitions in the object file if present, and return a
13380b57cec5SDimitry Andric // vector whose nth element contains a pointer to the Elf_Verdef for version
13390b57cec5SDimitry Andric // identifier n. Version identifiers that are not definitions map to nullptr.
13400b57cec5SDimitry Andric template <typename ELFT>
13410b57cec5SDimitry Andric static std::vector<const void *> parseVerdefs(const uint8_t *base,
13420b57cec5SDimitry Andric                                               const typename ELFT::Shdr *sec) {
13430b57cec5SDimitry Andric   if (!sec)
13440b57cec5SDimitry Andric     return {};
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric   // We cannot determine the largest verdef identifier without inspecting
13470b57cec5SDimitry Andric   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
13480b57cec5SDimitry Andric   // sequentially starting from 1, so we predict that the largest identifier
13490b57cec5SDimitry Andric   // will be verdefCount.
13500b57cec5SDimitry Andric   unsigned verdefCount = sec->sh_info;
13510b57cec5SDimitry Andric   std::vector<const void *> verdefs(verdefCount + 1);
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric   // Build the Verdefs array by following the chain of Elf_Verdef objects
13540b57cec5SDimitry Andric   // from the start of the .gnu.version_d section.
13550b57cec5SDimitry Andric   const uint8_t *verdef = base + sec->sh_offset;
13560b57cec5SDimitry Andric   for (unsigned i = 0; i != verdefCount; ++i) {
13570b57cec5SDimitry Andric     auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
13580b57cec5SDimitry Andric     verdef += curVerdef->vd_next;
13590b57cec5SDimitry Andric     unsigned verdefIndex = curVerdef->vd_ndx;
13600b57cec5SDimitry Andric     verdefs.resize(verdefIndex + 1);
13610b57cec5SDimitry Andric     verdefs[verdefIndex] = curVerdef;
13620b57cec5SDimitry Andric   }
13630b57cec5SDimitry Andric   return verdefs;
13640b57cec5SDimitry Andric }
13650b57cec5SDimitry Andric 
13665ffd83dbSDimitry Andric // Parse SHT_GNU_verneed to properly set the name of a versioned undefined
13675ffd83dbSDimitry Andric // symbol. We detect fatal issues which would cause vulnerabilities, but do not
13685ffd83dbSDimitry Andric // implement sophisticated error checking like in llvm-readobj because the value
13695ffd83dbSDimitry Andric // of such diagnostics is low.
13705ffd83dbSDimitry Andric template <typename ELFT>
13715ffd83dbSDimitry Andric std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
13725ffd83dbSDimitry Andric                                                const typename ELFT::Shdr *sec) {
13735ffd83dbSDimitry Andric   if (!sec)
13745ffd83dbSDimitry Andric     return {};
13755ffd83dbSDimitry Andric   std::vector<uint32_t> verneeds;
1376*e8d8bef9SDimitry Andric   ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(*sec), this);
13775ffd83dbSDimitry Andric   const uint8_t *verneedBuf = data.begin();
13785ffd83dbSDimitry Andric   for (unsigned i = 0; i != sec->sh_info; ++i) {
13795ffd83dbSDimitry Andric     if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end())
13805ffd83dbSDimitry Andric       fatal(toString(this) + " has an invalid Verneed");
13815ffd83dbSDimitry Andric     auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
13825ffd83dbSDimitry Andric     const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
13835ffd83dbSDimitry Andric     for (unsigned j = 0; j != vn->vn_cnt; ++j) {
13845ffd83dbSDimitry Andric       if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end())
13855ffd83dbSDimitry Andric         fatal(toString(this) + " has an invalid Vernaux");
13865ffd83dbSDimitry Andric       auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
13875ffd83dbSDimitry Andric       if (aux->vna_name >= this->stringTable.size())
13885ffd83dbSDimitry Andric         fatal(toString(this) + " has a Vernaux with an invalid vna_name");
13895ffd83dbSDimitry Andric       uint16_t version = aux->vna_other & VERSYM_VERSION;
13905ffd83dbSDimitry Andric       if (version >= verneeds.size())
13915ffd83dbSDimitry Andric         verneeds.resize(version + 1);
13925ffd83dbSDimitry Andric       verneeds[version] = aux->vna_name;
13935ffd83dbSDimitry Andric       vernauxBuf += aux->vna_next;
13945ffd83dbSDimitry Andric     }
13955ffd83dbSDimitry Andric     verneedBuf += vn->vn_next;
13965ffd83dbSDimitry Andric   }
13975ffd83dbSDimitry Andric   return verneeds;
13985ffd83dbSDimitry Andric }
13995ffd83dbSDimitry Andric 
14000b57cec5SDimitry Andric // We do not usually care about alignments of data in shared object
14010b57cec5SDimitry Andric // files because the loader takes care of it. However, if we promote a
14020b57cec5SDimitry Andric // DSO symbol to point to .bss due to copy relocation, we need to keep
14030b57cec5SDimitry Andric // the original alignment requirements. We infer it in this function.
14040b57cec5SDimitry Andric template <typename ELFT>
14050b57cec5SDimitry Andric static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
14060b57cec5SDimitry Andric                              const typename ELFT::Sym &sym) {
14070b57cec5SDimitry Andric   uint64_t ret = UINT64_MAX;
14080b57cec5SDimitry Andric   if (sym.st_value)
14090b57cec5SDimitry Andric     ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
14100b57cec5SDimitry Andric   if (0 < sym.st_shndx && sym.st_shndx < sections.size())
14110b57cec5SDimitry Andric     ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
14120b57cec5SDimitry Andric   return (ret > UINT32_MAX) ? 0 : ret;
14130b57cec5SDimitry Andric }
14140b57cec5SDimitry Andric 
14150b57cec5SDimitry Andric // Fully parse the shared object file.
14160b57cec5SDimitry Andric //
14170b57cec5SDimitry Andric // This function parses symbol versions. If a DSO has version information,
14180b57cec5SDimitry Andric // the file has a ".gnu.version_d" section which contains symbol version
14190b57cec5SDimitry Andric // definitions. Each symbol is associated to one version through a table in
14200b57cec5SDimitry Andric // ".gnu.version" section. That table is a parallel array for the symbol
14210b57cec5SDimitry Andric // table, and each table entry contains an index in ".gnu.version_d".
14220b57cec5SDimitry Andric //
14230b57cec5SDimitry Andric // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
14240b57cec5SDimitry Andric // VER_NDX_GLOBAL. There's no table entry for these special versions in
14250b57cec5SDimitry Andric // ".gnu.version_d".
14260b57cec5SDimitry Andric //
14270b57cec5SDimitry Andric // The file format for symbol versioning is perhaps a bit more complicated
14280b57cec5SDimitry Andric // than necessary, but you can easily understand the code if you wrap your
14290b57cec5SDimitry Andric // head around the data structure described above.
14300b57cec5SDimitry Andric template <class ELFT> void SharedFile::parse() {
14310b57cec5SDimitry Andric   using Elf_Dyn = typename ELFT::Dyn;
14320b57cec5SDimitry Andric   using Elf_Shdr = typename ELFT::Shdr;
14330b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
14340b57cec5SDimitry Andric   using Elf_Verdef = typename ELFT::Verdef;
14350b57cec5SDimitry Andric   using Elf_Versym = typename ELFT::Versym;
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric   ArrayRef<Elf_Dyn> dynamicTags;
14380b57cec5SDimitry Andric   const ELFFile<ELFT> obj = this->getObj<ELFT>();
14390b57cec5SDimitry Andric   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   const Elf_Shdr *versymSec = nullptr;
14420b57cec5SDimitry Andric   const Elf_Shdr *verdefSec = nullptr;
14435ffd83dbSDimitry Andric   const Elf_Shdr *verneedSec = nullptr;
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
14460b57cec5SDimitry Andric   for (const Elf_Shdr &sec : sections) {
14470b57cec5SDimitry Andric     switch (sec.sh_type) {
14480b57cec5SDimitry Andric     default:
14490b57cec5SDimitry Andric       continue;
14500b57cec5SDimitry Andric     case SHT_DYNAMIC:
14510b57cec5SDimitry Andric       dynamicTags =
1452*e8d8bef9SDimitry Andric           CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this);
14530b57cec5SDimitry Andric       break;
14540b57cec5SDimitry Andric     case SHT_GNU_versym:
14550b57cec5SDimitry Andric       versymSec = &sec;
14560b57cec5SDimitry Andric       break;
14570b57cec5SDimitry Andric     case SHT_GNU_verdef:
14580b57cec5SDimitry Andric       verdefSec = &sec;
14590b57cec5SDimitry Andric       break;
14605ffd83dbSDimitry Andric     case SHT_GNU_verneed:
14615ffd83dbSDimitry Andric       verneedSec = &sec;
14625ffd83dbSDimitry Andric       break;
14630b57cec5SDimitry Andric     }
14640b57cec5SDimitry Andric   }
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric   if (versymSec && numELFSyms == 0) {
14670b57cec5SDimitry Andric     error("SHT_GNU_versym should be associated with symbol table");
14680b57cec5SDimitry Andric     return;
14690b57cec5SDimitry Andric   }
14700b57cec5SDimitry Andric 
14710b57cec5SDimitry Andric   // Search for a DT_SONAME tag to initialize this->soName.
14720b57cec5SDimitry Andric   for (const Elf_Dyn &dyn : dynamicTags) {
14730b57cec5SDimitry Andric     if (dyn.d_tag == DT_NEEDED) {
14740b57cec5SDimitry Andric       uint64_t val = dyn.getVal();
14750b57cec5SDimitry Andric       if (val >= this->stringTable.size())
14760b57cec5SDimitry Andric         fatal(toString(this) + ": invalid DT_NEEDED entry");
14770b57cec5SDimitry Andric       dtNeeded.push_back(this->stringTable.data() + val);
14780b57cec5SDimitry Andric     } else if (dyn.d_tag == DT_SONAME) {
14790b57cec5SDimitry Andric       uint64_t val = dyn.getVal();
14800b57cec5SDimitry Andric       if (val >= this->stringTable.size())
14810b57cec5SDimitry Andric         fatal(toString(this) + ": invalid DT_SONAME entry");
14820b57cec5SDimitry Andric       soName = this->stringTable.data() + val;
14830b57cec5SDimitry Andric     }
14840b57cec5SDimitry Andric   }
14850b57cec5SDimitry Andric 
14860b57cec5SDimitry Andric   // DSOs are uniquified not by filename but by soname.
14870b57cec5SDimitry Andric   DenseMap<StringRef, SharedFile *>::iterator it;
14880b57cec5SDimitry Andric   bool wasInserted;
14890b57cec5SDimitry Andric   std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this);
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric   // If a DSO appears more than once on the command line with and without
14920b57cec5SDimitry Andric   // --as-needed, --no-as-needed takes precedence over --as-needed because a
14930b57cec5SDimitry Andric   // user can add an extra DSO with --no-as-needed to force it to be added to
14940b57cec5SDimitry Andric   // the dependency list.
14950b57cec5SDimitry Andric   it->second->isNeeded |= isNeeded;
14960b57cec5SDimitry Andric   if (!wasInserted)
14970b57cec5SDimitry Andric     return;
14980b57cec5SDimitry Andric 
14990b57cec5SDimitry Andric   sharedFiles.push_back(this);
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric   verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
15025ffd83dbSDimitry Andric   std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
15030b57cec5SDimitry Andric 
15040b57cec5SDimitry Andric   // Parse ".gnu.version" section which is a parallel array for the symbol
15050b57cec5SDimitry Andric   // table. If a given file doesn't have a ".gnu.version" section, we use
15060b57cec5SDimitry Andric   // VER_NDX_GLOBAL.
15070b57cec5SDimitry Andric   size_t size = numELFSyms - firstGlobal;
15085ffd83dbSDimitry Andric   std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
15090b57cec5SDimitry Andric   if (versymSec) {
15100b57cec5SDimitry Andric     ArrayRef<Elf_Versym> versym =
1511*e8d8bef9SDimitry Andric         CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec),
15120b57cec5SDimitry Andric               this)
15130b57cec5SDimitry Andric             .slice(firstGlobal);
15140b57cec5SDimitry Andric     for (size_t i = 0; i < size; ++i)
15150b57cec5SDimitry Andric       versyms[i] = versym[i].vs_index;
15160b57cec5SDimitry Andric   }
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric   // System libraries can have a lot of symbols with versions. Using a
15190b57cec5SDimitry Andric   // fixed buffer for computing the versions name (foo@ver) can save a
15200b57cec5SDimitry Andric   // lot of allocations.
15210b57cec5SDimitry Andric   SmallString<0> versionedNameBuffer;
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric   // Add symbols to the symbol table.
15240b57cec5SDimitry Andric   ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
15250b57cec5SDimitry Andric   for (size_t i = 0; i < syms.size(); ++i) {
15260b57cec5SDimitry Andric     const Elf_Sym &sym = syms[i];
15270b57cec5SDimitry Andric 
15280b57cec5SDimitry Andric     // ELF spec requires that all local symbols precede weak or global
15290b57cec5SDimitry Andric     // symbols in each symbol table, and the index of first non-local symbol
15300b57cec5SDimitry Andric     // is stored to sh_info. If a local symbol appears after some non-local
15310b57cec5SDimitry Andric     // symbol, that's a violation of the spec.
15320b57cec5SDimitry Andric     StringRef name = CHECK(sym.getName(this->stringTable), this);
15330b57cec5SDimitry Andric     if (sym.getBinding() == STB_LOCAL) {
15340b57cec5SDimitry Andric       warn("found local symbol '" + name +
15350b57cec5SDimitry Andric            "' in global part of symbol table in file " + toString(this));
15360b57cec5SDimitry Andric       continue;
15370b57cec5SDimitry Andric     }
15380b57cec5SDimitry Andric 
15395ffd83dbSDimitry Andric     uint16_t idx = versyms[i] & ~VERSYM_HIDDEN;
15400b57cec5SDimitry Andric     if (sym.isUndefined()) {
15415ffd83dbSDimitry Andric       // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but
15425ffd83dbSDimitry Andric       // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL.
15435ffd83dbSDimitry Andric       if (idx != VER_NDX_LOCAL && idx != VER_NDX_GLOBAL) {
15445ffd83dbSDimitry Andric         if (idx >= verneeds.size()) {
15455ffd83dbSDimitry Andric           error("corrupt input file: version need index " + Twine(idx) +
15465ffd83dbSDimitry Andric                 " for symbol " + name + " is out of bounds\n>>> defined in " +
15475ffd83dbSDimitry Andric                 toString(this));
15485ffd83dbSDimitry Andric           continue;
15495ffd83dbSDimitry Andric         }
15505ffd83dbSDimitry Andric         StringRef verName = this->stringTable.data() + verneeds[idx];
15515ffd83dbSDimitry Andric         versionedNameBuffer.clear();
15525ffd83dbSDimitry Andric         name =
15535ffd83dbSDimitry Andric             saver.save((name + "@" + verName).toStringRef(versionedNameBuffer));
15545ffd83dbSDimitry Andric       }
15550b57cec5SDimitry Andric       Symbol *s = symtab->addSymbol(
15560b57cec5SDimitry Andric           Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
15570b57cec5SDimitry Andric       s->exportDynamic = true;
15580b57cec5SDimitry Andric       continue;
15590b57cec5SDimitry Andric     }
15600b57cec5SDimitry Andric 
15610b57cec5SDimitry Andric     // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
15620b57cec5SDimitry Andric     // assigns VER_NDX_LOCAL to this section global symbol. Here is a
15630b57cec5SDimitry Andric     // workaround for this bug.
15640b57cec5SDimitry Andric     if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL &&
15650b57cec5SDimitry Andric         name == "_gp_disp")
15660b57cec5SDimitry Andric       continue;
15670b57cec5SDimitry Andric 
15680b57cec5SDimitry Andric     uint32_t alignment = getAlignment<ELFT>(sections, sym);
15690b57cec5SDimitry Andric     if (!(versyms[i] & VERSYM_HIDDEN)) {
15700b57cec5SDimitry Andric       symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(),
15710b57cec5SDimitry Andric                                      sym.st_other, sym.getType(), sym.st_value,
15720b57cec5SDimitry Andric                                      sym.st_size, alignment, idx});
15730b57cec5SDimitry Andric     }
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric     // Also add the symbol with the versioned name to handle undefined symbols
15760b57cec5SDimitry Andric     // with explicit versions.
15770b57cec5SDimitry Andric     if (idx == VER_NDX_GLOBAL)
15780b57cec5SDimitry Andric       continue;
15790b57cec5SDimitry Andric 
15800b57cec5SDimitry Andric     if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) {
15810b57cec5SDimitry Andric       error("corrupt input file: version definition index " + Twine(idx) +
15820b57cec5SDimitry Andric             " for symbol " + name + " is out of bounds\n>>> defined in " +
15830b57cec5SDimitry Andric             toString(this));
15840b57cec5SDimitry Andric       continue;
15850b57cec5SDimitry Andric     }
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric     StringRef verName =
15880b57cec5SDimitry Andric         this->stringTable.data() +
15890b57cec5SDimitry Andric         reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
15900b57cec5SDimitry Andric     versionedNameBuffer.clear();
15910b57cec5SDimitry Andric     name = (name + "@" + verName).toStringRef(versionedNameBuffer);
15920b57cec5SDimitry Andric     symtab->addSymbol(SharedSymbol{*this, saver.save(name), sym.getBinding(),
15930b57cec5SDimitry Andric                                    sym.st_other, sym.getType(), sym.st_value,
15940b57cec5SDimitry Andric                                    sym.st_size, alignment, idx});
15950b57cec5SDimitry Andric   }
15960b57cec5SDimitry Andric }
15970b57cec5SDimitry Andric 
15980b57cec5SDimitry Andric static ELFKind getBitcodeELFKind(const Triple &t) {
15990b57cec5SDimitry Andric   if (t.isLittleEndian())
16000b57cec5SDimitry Andric     return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
16010b57cec5SDimitry Andric   return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
16020b57cec5SDimitry Andric }
16030b57cec5SDimitry Andric 
1604*e8d8bef9SDimitry Andric static uint16_t getBitcodeMachineKind(StringRef path, const Triple &t) {
16050b57cec5SDimitry Andric   switch (t.getArch()) {
16060b57cec5SDimitry Andric   case Triple::aarch64:
16070b57cec5SDimitry Andric     return EM_AARCH64;
16080b57cec5SDimitry Andric   case Triple::amdgcn:
16090b57cec5SDimitry Andric   case Triple::r600:
16100b57cec5SDimitry Andric     return EM_AMDGPU;
16110b57cec5SDimitry Andric   case Triple::arm:
16120b57cec5SDimitry Andric   case Triple::thumb:
16130b57cec5SDimitry Andric     return EM_ARM;
16140b57cec5SDimitry Andric   case Triple::avr:
16150b57cec5SDimitry Andric     return EM_AVR;
16160b57cec5SDimitry Andric   case Triple::mips:
16170b57cec5SDimitry Andric   case Triple::mipsel:
16180b57cec5SDimitry Andric   case Triple::mips64:
16190b57cec5SDimitry Andric   case Triple::mips64el:
16200b57cec5SDimitry Andric     return EM_MIPS;
16210b57cec5SDimitry Andric   case Triple::msp430:
16220b57cec5SDimitry Andric     return EM_MSP430;
16230b57cec5SDimitry Andric   case Triple::ppc:
1624*e8d8bef9SDimitry Andric   case Triple::ppcle:
16250b57cec5SDimitry Andric     return EM_PPC;
16260b57cec5SDimitry Andric   case Triple::ppc64:
16270b57cec5SDimitry Andric   case Triple::ppc64le:
16280b57cec5SDimitry Andric     return EM_PPC64;
16290b57cec5SDimitry Andric   case Triple::riscv32:
16300b57cec5SDimitry Andric   case Triple::riscv64:
16310b57cec5SDimitry Andric     return EM_RISCV;
16320b57cec5SDimitry Andric   case Triple::x86:
16330b57cec5SDimitry Andric     return t.isOSIAMCU() ? EM_IAMCU : EM_386;
16340b57cec5SDimitry Andric   case Triple::x86_64:
16350b57cec5SDimitry Andric     return EM_X86_64;
16360b57cec5SDimitry Andric   default:
16370b57cec5SDimitry Andric     error(path + ": could not infer e_machine from bitcode target triple " +
16380b57cec5SDimitry Andric           t.str());
16390b57cec5SDimitry Andric     return EM_NONE;
16400b57cec5SDimitry Andric   }
16410b57cec5SDimitry Andric }
16420b57cec5SDimitry Andric 
1643*e8d8bef9SDimitry Andric static uint8_t getOsAbi(const Triple &t) {
1644*e8d8bef9SDimitry Andric   switch (t.getOS()) {
1645*e8d8bef9SDimitry Andric   case Triple::AMDHSA:
1646*e8d8bef9SDimitry Andric     return ELF::ELFOSABI_AMDGPU_HSA;
1647*e8d8bef9SDimitry Andric   case Triple::AMDPAL:
1648*e8d8bef9SDimitry Andric     return ELF::ELFOSABI_AMDGPU_PAL;
1649*e8d8bef9SDimitry Andric   case Triple::Mesa3D:
1650*e8d8bef9SDimitry Andric     return ELF::ELFOSABI_AMDGPU_MESA3D;
1651*e8d8bef9SDimitry Andric   default:
1652*e8d8bef9SDimitry Andric     return ELF::ELFOSABI_NONE;
1653*e8d8bef9SDimitry Andric   }
1654*e8d8bef9SDimitry Andric }
1655*e8d8bef9SDimitry Andric 
16560b57cec5SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
16570b57cec5SDimitry Andric                          uint64_t offsetInArchive)
16580b57cec5SDimitry Andric     : InputFile(BitcodeKind, mb) {
16595ffd83dbSDimitry Andric   this->archiveName = std::string(archiveName);
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric   std::string path = mb.getBufferIdentifier().str();
16620b57cec5SDimitry Andric   if (config->thinLTOIndexOnly)
16630b57cec5SDimitry Andric     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
16640b57cec5SDimitry Andric 
16650b57cec5SDimitry Andric   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
16660b57cec5SDimitry Andric   // name. If two archives define two members with the same name, this
16670b57cec5SDimitry Andric   // causes a collision which result in only one of the objects being taken
16680b57cec5SDimitry Andric   // into consideration at LTO time (which very likely causes undefined
16690b57cec5SDimitry Andric   // symbols later in the link stage). So we append file offset to make
16700b57cec5SDimitry Andric   // filename unique.
16715ffd83dbSDimitry Andric   StringRef name =
16725ffd83dbSDimitry Andric       archiveName.empty()
16730b57cec5SDimitry Andric           ? saver.save(path)
16745ffd83dbSDimitry Andric           : saver.save(archiveName + "(" + path::filename(path) + " at " +
16750b57cec5SDimitry Andric                        utostr(offsetInArchive) + ")");
16760b57cec5SDimitry Andric   MemoryBufferRef mbref(mb.getBuffer(), name);
16770b57cec5SDimitry Andric 
16780b57cec5SDimitry Andric   obj = CHECK(lto::InputFile::create(mbref), this);
16790b57cec5SDimitry Andric 
16800b57cec5SDimitry Andric   Triple t(obj->getTargetTriple());
16810b57cec5SDimitry Andric   ekind = getBitcodeELFKind(t);
16820b57cec5SDimitry Andric   emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t);
1683*e8d8bef9SDimitry Andric   osabi = getOsAbi(t);
16840b57cec5SDimitry Andric }
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
16870b57cec5SDimitry Andric   switch (gvVisibility) {
16880b57cec5SDimitry Andric   case GlobalValue::DefaultVisibility:
16890b57cec5SDimitry Andric     return STV_DEFAULT;
16900b57cec5SDimitry Andric   case GlobalValue::HiddenVisibility:
16910b57cec5SDimitry Andric     return STV_HIDDEN;
16920b57cec5SDimitry Andric   case GlobalValue::ProtectedVisibility:
16930b57cec5SDimitry Andric     return STV_PROTECTED;
16940b57cec5SDimitry Andric   }
16950b57cec5SDimitry Andric   llvm_unreachable("unknown visibility");
16960b57cec5SDimitry Andric }
16970b57cec5SDimitry Andric 
16980b57cec5SDimitry Andric template <class ELFT>
16990b57cec5SDimitry Andric static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
17000b57cec5SDimitry Andric                                    const lto::InputFile::Symbol &objSym,
17010b57cec5SDimitry Andric                                    BitcodeFile &f) {
17020b57cec5SDimitry Andric   StringRef name = saver.save(objSym.getName());
17030b57cec5SDimitry Andric   uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
17040b57cec5SDimitry Andric   uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
17050b57cec5SDimitry Andric   uint8_t visibility = mapVisibility(objSym.getVisibility());
17060b57cec5SDimitry Andric   bool canOmitFromDynSym = objSym.canBeOmittedFromSymbolTable();
17070b57cec5SDimitry Andric 
17080b57cec5SDimitry Andric   int c = objSym.getComdatIndex();
17090b57cec5SDimitry Andric   if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) {
171085868e8aSDimitry Andric     Undefined newSym(&f, name, binding, visibility, type);
17110b57cec5SDimitry Andric     if (canOmitFromDynSym)
171285868e8aSDimitry Andric       newSym.exportDynamic = false;
171385868e8aSDimitry Andric     Symbol *ret = symtab->addSymbol(newSym);
171485868e8aSDimitry Andric     ret->referenced = true;
171585868e8aSDimitry Andric     return ret;
17160b57cec5SDimitry Andric   }
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   if (objSym.isCommon())
17190b57cec5SDimitry Andric     return symtab->addSymbol(
17200b57cec5SDimitry Andric         CommonSymbol{&f, name, binding, visibility, STT_OBJECT,
17210b57cec5SDimitry Andric                      objSym.getCommonAlignment(), objSym.getCommonSize()});
17220b57cec5SDimitry Andric 
172385868e8aSDimitry Andric   Defined newSym(&f, name, binding, visibility, type, 0, 0, nullptr);
17240b57cec5SDimitry Andric   if (canOmitFromDynSym)
172585868e8aSDimitry Andric     newSym.exportDynamic = false;
172685868e8aSDimitry Andric   return symtab->addSymbol(newSym);
17270b57cec5SDimitry Andric }
17280b57cec5SDimitry Andric 
17290b57cec5SDimitry Andric template <class ELFT> void BitcodeFile::parse() {
17300b57cec5SDimitry Andric   std::vector<bool> keptComdats;
17310b57cec5SDimitry Andric   for (StringRef s : obj->getComdatTable())
17320b57cec5SDimitry Andric     keptComdats.push_back(
17330b57cec5SDimitry Andric         symtab->comdatGroups.try_emplace(CachedHashStringRef(s), this).second);
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric   for (const lto::InputFile::Symbol &objSym : obj->symbols())
17360b57cec5SDimitry Andric     symbols.push_back(createBitcodeSymbol<ELFT>(keptComdats, objSym, *this));
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric   for (auto l : obj->getDependentLibraries())
17390b57cec5SDimitry Andric     addDependentLibrary(l, this);
17400b57cec5SDimitry Andric }
17410b57cec5SDimitry Andric 
17420b57cec5SDimitry Andric void BinaryFile::parse() {
17430b57cec5SDimitry Andric   ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
17440b57cec5SDimitry Andric   auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
17450b57cec5SDimitry Andric                                      8, data, ".data");
17460b57cec5SDimitry Andric   sections.push_back(section);
17470b57cec5SDimitry Andric 
17480b57cec5SDimitry Andric   // For each input file foo that is embedded to a result as a binary
17490b57cec5SDimitry Andric   // blob, we define _binary_foo_{start,end,size} symbols, so that
17500b57cec5SDimitry Andric   // user programs can access blobs by name. Non-alphanumeric
17510b57cec5SDimitry Andric   // characters in a filename are replaced with underscore.
17520b57cec5SDimitry Andric   std::string s = "_binary_" + mb.getBufferIdentifier().str();
17530b57cec5SDimitry Andric   for (size_t i = 0; i < s.size(); ++i)
17540b57cec5SDimitry Andric     if (!isAlnum(s[i]))
17550b57cec5SDimitry Andric       s[i] = '_';
17560b57cec5SDimitry Andric 
17570b57cec5SDimitry Andric   symtab->addSymbol(Defined{nullptr, saver.save(s + "_start"), STB_GLOBAL,
17580b57cec5SDimitry Andric                             STV_DEFAULT, STT_OBJECT, 0, 0, section});
17590b57cec5SDimitry Andric   symtab->addSymbol(Defined{nullptr, saver.save(s + "_end"), STB_GLOBAL,
17600b57cec5SDimitry Andric                             STV_DEFAULT, STT_OBJECT, data.size(), 0, section});
17610b57cec5SDimitry Andric   symtab->addSymbol(Defined{nullptr, saver.save(s + "_size"), STB_GLOBAL,
17620b57cec5SDimitry Andric                             STV_DEFAULT, STT_OBJECT, data.size(), 0, nullptr});
17630b57cec5SDimitry Andric }
17640b57cec5SDimitry Andric 
17655ffd83dbSDimitry Andric InputFile *elf::createObjectFile(MemoryBufferRef mb, StringRef archiveName,
17660b57cec5SDimitry Andric                                  uint64_t offsetInArchive) {
17670b57cec5SDimitry Andric   if (isBitcode(mb))
17680b57cec5SDimitry Andric     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric   switch (getELFKind(mb, archiveName)) {
17710b57cec5SDimitry Andric   case ELF32LEKind:
17720b57cec5SDimitry Andric     return make<ObjFile<ELF32LE>>(mb, archiveName);
17730b57cec5SDimitry Andric   case ELF32BEKind:
17740b57cec5SDimitry Andric     return make<ObjFile<ELF32BE>>(mb, archiveName);
17750b57cec5SDimitry Andric   case ELF64LEKind:
17760b57cec5SDimitry Andric     return make<ObjFile<ELF64LE>>(mb, archiveName);
17770b57cec5SDimitry Andric   case ELF64BEKind:
17780b57cec5SDimitry Andric     return make<ObjFile<ELF64BE>>(mb, archiveName);
17790b57cec5SDimitry Andric   default:
17800b57cec5SDimitry Andric     llvm_unreachable("getELFKind");
17810b57cec5SDimitry Andric   }
17820b57cec5SDimitry Andric }
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric void LazyObjFile::fetch() {
17855ffd83dbSDimitry Andric   if (fetched)
17860b57cec5SDimitry Andric     return;
17875ffd83dbSDimitry Andric   fetched = true;
17880b57cec5SDimitry Andric 
17890b57cec5SDimitry Andric   InputFile *file = createObjectFile(mb, archiveName, offsetInArchive);
17900b57cec5SDimitry Andric   file->groupId = groupId;
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   // Copy symbol vector so that the new InputFile doesn't have to
17930b57cec5SDimitry Andric   // insert the same defined symbols to the symbol table again.
17940b57cec5SDimitry Andric   file->symbols = std::move(symbols);
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric   parseFile(file);
17970b57cec5SDimitry Andric }
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric template <class ELFT> void LazyObjFile::parse() {
18000b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
18010b57cec5SDimitry Andric 
18020b57cec5SDimitry Andric   // A lazy object file wraps either a bitcode file or an ELF file.
18030b57cec5SDimitry Andric   if (isBitcode(this->mb)) {
18040b57cec5SDimitry Andric     std::unique_ptr<lto::InputFile> obj =
18050b57cec5SDimitry Andric         CHECK(lto::InputFile::create(this->mb), this);
18060b57cec5SDimitry Andric     for (const lto::InputFile::Symbol &sym : obj->symbols()) {
18070b57cec5SDimitry Andric       if (sym.isUndefined())
18080b57cec5SDimitry Andric         continue;
18090b57cec5SDimitry Andric       symtab->addSymbol(LazyObject{*this, saver.save(sym.getName())});
18100b57cec5SDimitry Andric     }
18110b57cec5SDimitry Andric     return;
18120b57cec5SDimitry Andric   }
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   if (getELFKind(this->mb, archiveName) != config->ekind) {
18150b57cec5SDimitry Andric     error("incompatible file: " + this->mb.getBufferIdentifier());
18160b57cec5SDimitry Andric     return;
18170b57cec5SDimitry Andric   }
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   // Find a symbol table.
18200b57cec5SDimitry Andric   ELFFile<ELFT> obj = check(ELFFile<ELFT>::create(mb.getBuffer()));
18210b57cec5SDimitry Andric   ArrayRef<typename ELFT::Shdr> sections = CHECK(obj.sections(), this);
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric   for (const typename ELFT::Shdr &sec : sections) {
18240b57cec5SDimitry Andric     if (sec.sh_type != SHT_SYMTAB)
18250b57cec5SDimitry Andric       continue;
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric     // A symbol table is found.
18280b57cec5SDimitry Andric     ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(&sec), this);
18290b57cec5SDimitry Andric     uint32_t firstGlobal = sec.sh_info;
18300b57cec5SDimitry Andric     StringRef strtab = CHECK(obj.getStringTableForSymtab(sec, sections), this);
18310b57cec5SDimitry Andric     this->symbols.resize(eSyms.size());
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric     // Get existing symbols or insert placeholder symbols.
18340b57cec5SDimitry Andric     for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
18350b57cec5SDimitry Andric       if (eSyms[i].st_shndx != SHN_UNDEF)
18360b57cec5SDimitry Andric         this->symbols[i] = symtab->insert(CHECK(eSyms[i].getName(strtab), this));
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric     // Replace existing symbols with LazyObject symbols.
18390b57cec5SDimitry Andric     //
18400b57cec5SDimitry Andric     // resolve() may trigger this->fetch() if an existing symbol is an
18410b57cec5SDimitry Andric     // undefined symbol. If that happens, this LazyObjFile has served
18420b57cec5SDimitry Andric     // its purpose, and we can exit from the loop early.
18430b57cec5SDimitry Andric     for (Symbol *sym : this->symbols) {
18440b57cec5SDimitry Andric       if (!sym)
18450b57cec5SDimitry Andric         continue;
18460b57cec5SDimitry Andric       sym->resolve(LazyObject{*this, sym->getName()});
18470b57cec5SDimitry Andric 
18485ffd83dbSDimitry Andric       // If fetched, stop iterating because this->symbols has been transferred
18495ffd83dbSDimitry Andric       // to the instantiated ObjFile.
18505ffd83dbSDimitry Andric       if (fetched)
18510b57cec5SDimitry Andric         return;
18520b57cec5SDimitry Andric     }
18530b57cec5SDimitry Andric     return;
18540b57cec5SDimitry Andric   }
18550b57cec5SDimitry Andric }
18560b57cec5SDimitry Andric 
1857*e8d8bef9SDimitry Andric bool LazyObjFile::shouldFetchForCommon(const StringRef &name) {
1858*e8d8bef9SDimitry Andric   if (isBitcode(mb))
1859*e8d8bef9SDimitry Andric     return isBitcodeNonCommonDef(mb, name, archiveName);
1860*e8d8bef9SDimitry Andric 
1861*e8d8bef9SDimitry Andric   return isNonCommonDef(mb, name, archiveName);
1862*e8d8bef9SDimitry Andric }
1863*e8d8bef9SDimitry Andric 
18645ffd83dbSDimitry Andric std::string elf::replaceThinLTOSuffix(StringRef path) {
18650b57cec5SDimitry Andric   StringRef suffix = config->thinLTOObjectSuffixReplace.first;
18660b57cec5SDimitry Andric   StringRef repl = config->thinLTOObjectSuffixReplace.second;
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric   if (path.consume_back(suffix))
18690b57cec5SDimitry Andric     return (path + repl).str();
18705ffd83dbSDimitry Andric   return std::string(path);
18710b57cec5SDimitry Andric }
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32LE>();
18740b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32BE>();
18750b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64LE>();
18760b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64BE>();
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric template void LazyObjFile::parse<ELF32LE>();
18790b57cec5SDimitry Andric template void LazyObjFile::parse<ELF32BE>();
18800b57cec5SDimitry Andric template void LazyObjFile::parse<ELF64LE>();
18810b57cec5SDimitry Andric template void LazyObjFile::parse<ELF64BE>();
18820b57cec5SDimitry Andric 
18835ffd83dbSDimitry Andric template class elf::ObjFile<ELF32LE>;
18845ffd83dbSDimitry Andric template class elf::ObjFile<ELF32BE>;
18855ffd83dbSDimitry Andric template class elf::ObjFile<ELF64LE>;
18865ffd83dbSDimitry Andric template class elf::ObjFile<ELF64BE>;
18870b57cec5SDimitry Andric 
18880b57cec5SDimitry Andric template void SharedFile::parse<ELF32LE>();
18890b57cec5SDimitry Andric template void SharedFile::parse<ELF32BE>();
18900b57cec5SDimitry Andric template void SharedFile::parse<ELF64LE>();
18910b57cec5SDimitry Andric template void SharedFile::parse<ELF64BE>();
1892