xref: /freebsd/contrib/llvm-project/lld/ELF/InputFiles.cpp (revision d56accc7c3dcc897489b6a07834763a03b9f3d68)
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"
161fd87a68SDimitry Andric #include "Target.h"
1704eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h"
18480093f4SDimitry Andric #include "lld/Common/DWARF.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/Analysis.h"
210b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
220b57cec5SDimitry Andric #include "llvm/IR/Module.h"
230b57cec5SDimitry Andric #include "llvm/LTO/LTO.h"
240b57cec5SDimitry Andric #include "llvm/MC/StringTableBuilder.h"
250b57cec5SDimitry Andric #include "llvm/Object/ELFObjectFile.h"
260b57cec5SDimitry Andric #include "llvm/Support/ARMAttributeParser.h"
270b57cec5SDimitry Andric #include "llvm/Support/ARMBuildAttributes.h"
280b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
290b57cec5SDimitry Andric #include "llvm/Support/Path.h"
30e8d8bef9SDimitry Andric #include "llvm/Support/RISCVAttributeParser.h"
310b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h"
320b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric using namespace llvm;
350b57cec5SDimitry Andric using namespace llvm::ELF;
360b57cec5SDimitry Andric using namespace llvm::object;
370b57cec5SDimitry Andric using namespace llvm::sys;
380b57cec5SDimitry Andric using namespace llvm::sys::fs;
390b57cec5SDimitry Andric using namespace llvm::support::endian;
405ffd83dbSDimitry Andric using namespace lld;
415ffd83dbSDimitry Andric using namespace lld::elf;
420b57cec5SDimitry Andric 
435ffd83dbSDimitry Andric bool InputFile::isInGroup;
445ffd83dbSDimitry Andric uint32_t InputFile::nextGroupId;
455ffd83dbSDimitry Andric 
4604eeddc0SDimitry Andric SmallVector<std::unique_ptr<MemoryBuffer>> elf::memoryBuffers;
470eae32dcSDimitry Andric SmallVector<ArchiveFile *, 0> elf::archiveFiles;
480eae32dcSDimitry Andric SmallVector<BinaryFile *, 0> elf::binaryFiles;
490eae32dcSDimitry Andric SmallVector<BitcodeFile *, 0> elf::bitcodeFiles;
500eae32dcSDimitry Andric SmallVector<BitcodeFile *, 0> elf::lazyBitcodeFiles;
510eae32dcSDimitry Andric SmallVector<ELFFileBase *, 0> elf::objectFiles;
520eae32dcSDimitry Andric SmallVector<SharedFile *, 0> elf::sharedFiles;
535ffd83dbSDimitry Andric 
545ffd83dbSDimitry Andric std::unique_ptr<TarWriter> elf::tar;
555ffd83dbSDimitry Andric 
5685868e8aSDimitry Andric // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
575ffd83dbSDimitry Andric std::string lld::toString(const InputFile *f) {
5885868e8aSDimitry Andric   if (!f)
5985868e8aSDimitry Andric     return "<internal>";
600b57cec5SDimitry Andric 
6185868e8aSDimitry Andric   if (f->toStringCache.empty()) {
6285868e8aSDimitry Andric     if (f->archiveName.empty())
630eae32dcSDimitry Andric       f->toStringCache = f->getName();
6485868e8aSDimitry Andric     else
650eae32dcSDimitry Andric       (f->archiveName + "(" + f->getName() + ")").toVector(f->toStringCache);
6685868e8aSDimitry Andric   }
670eae32dcSDimitry Andric   return std::string(f->toStringCache);
6885868e8aSDimitry Andric }
6985868e8aSDimitry Andric 
700b57cec5SDimitry Andric static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) {
710b57cec5SDimitry Andric   unsigned char size;
720b57cec5SDimitry Andric   unsigned char endian;
730b57cec5SDimitry Andric   std::tie(size, endian) = getElfArchType(mb.getBuffer());
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric   auto report = [&](StringRef msg) {
760b57cec5SDimitry Andric     StringRef filename = mb.getBufferIdentifier();
770b57cec5SDimitry Andric     if (archiveName.empty())
780b57cec5SDimitry Andric       fatal(filename + ": " + msg);
790b57cec5SDimitry Andric     else
800b57cec5SDimitry Andric       fatal(archiveName + "(" + filename + "): " + msg);
810b57cec5SDimitry Andric   };
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric   if (!mb.getBuffer().startswith(ElfMagic))
840b57cec5SDimitry Andric     report("not an ELF file");
850b57cec5SDimitry Andric   if (endian != ELFDATA2LSB && endian != ELFDATA2MSB)
860b57cec5SDimitry Andric     report("corrupted ELF file: invalid data encoding");
870b57cec5SDimitry Andric   if (size != ELFCLASS32 && size != ELFCLASS64)
880b57cec5SDimitry Andric     report("corrupted ELF file: invalid file class");
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric   size_t bufSize = mb.getBuffer().size();
910b57cec5SDimitry Andric   if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) ||
920b57cec5SDimitry Andric       (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr)))
930b57cec5SDimitry Andric     report("corrupted ELF file: file is too short");
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric   if (size == ELFCLASS32)
960b57cec5SDimitry Andric     return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
970b57cec5SDimitry Andric   return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
980b57cec5SDimitry Andric }
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric InputFile::InputFile(Kind k, MemoryBufferRef m)
1010b57cec5SDimitry Andric     : mb(m), groupId(nextGroupId), fileKind(k) {
1020b57cec5SDimitry Andric   // All files within the same --{start,end}-group get the same group ID.
1030b57cec5SDimitry Andric   // Otherwise, a new file will get a new group ID.
1040b57cec5SDimitry Andric   if (!isInGroup)
1050b57cec5SDimitry Andric     ++nextGroupId;
1060b57cec5SDimitry Andric }
1070b57cec5SDimitry Andric 
1085ffd83dbSDimitry Andric Optional<MemoryBufferRef> elf::readFile(StringRef path) {
109e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Load input files", path);
110e8d8bef9SDimitry Andric 
1110b57cec5SDimitry Andric   // The --chroot option changes our virtual root directory.
1120b57cec5SDimitry Andric   // This is useful when you are dealing with files created by --reproduce.
1130b57cec5SDimitry Andric   if (!config->chroot.empty() && path.startswith("/"))
11404eeddc0SDimitry Andric     path = saver().save(config->chroot + path);
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric   log(path);
117e8d8bef9SDimitry Andric   config->dependencyFiles.insert(llvm::CachedHashString(path));
1180b57cec5SDimitry Andric 
119fe6060f1SDimitry Andric   auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
120fe6060f1SDimitry Andric                                        /*RequiresNullTerminator=*/false);
1210b57cec5SDimitry Andric   if (auto ec = mbOrErr.getError()) {
1220b57cec5SDimitry Andric     error("cannot open " + path + ": " + ec.message());
1230b57cec5SDimitry Andric     return None;
1240b57cec5SDimitry Andric   }
1250b57cec5SDimitry Andric 
12604eeddc0SDimitry Andric   MemoryBufferRef mbref = (*mbOrErr)->getMemBufferRef();
12704eeddc0SDimitry Andric   memoryBuffers.push_back(std::move(*mbOrErr)); // take MB ownership
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   if (tar)
1300b57cec5SDimitry Andric     tar->append(relativeToRoot(path), mbref.getBuffer());
1310b57cec5SDimitry Andric   return mbref;
1320b57cec5SDimitry Andric }
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric // All input object files must be for the same architecture
1350b57cec5SDimitry Andric // (e.g. it does not make sense to link x86 object files with
1360b57cec5SDimitry Andric // MIPS object files.) This function checks for that error.
1370b57cec5SDimitry Andric static bool isCompatible(InputFile *file) {
1380b57cec5SDimitry Andric   if (!file->isElf() && !isa<BitcodeFile>(file))
1390b57cec5SDimitry Andric     return true;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   if (file->ekind == config->ekind && file->emachine == config->emachine) {
1420b57cec5SDimitry Andric     if (config->emachine != EM_MIPS)
1430b57cec5SDimitry Andric       return true;
1440b57cec5SDimitry Andric     if (isMipsN32Abi(file) == config->mipsN32Abi)
1450b57cec5SDimitry Andric       return true;
1460b57cec5SDimitry Andric   }
1470b57cec5SDimitry Andric 
1485ffd83dbSDimitry Andric   StringRef target =
1495ffd83dbSDimitry Andric       !config->bfdname.empty() ? config->bfdname : config->emulation;
1505ffd83dbSDimitry Andric   if (!target.empty()) {
1515ffd83dbSDimitry Andric     error(toString(file) + " is incompatible with " + target);
15285868e8aSDimitry Andric     return false;
15385868e8aSDimitry Andric   }
15485868e8aSDimitry Andric 
155*d56accc7SDimitry Andric   InputFile *existing = nullptr;
1560b57cec5SDimitry Andric   if (!objectFiles.empty())
1570b57cec5SDimitry Andric     existing = objectFiles[0];
1580b57cec5SDimitry Andric   else if (!sharedFiles.empty())
1590b57cec5SDimitry Andric     existing = sharedFiles[0];
1605ffd83dbSDimitry Andric   else if (!bitcodeFiles.empty())
1610b57cec5SDimitry Andric     existing = bitcodeFiles[0];
162*d56accc7SDimitry Andric   std::string with;
163*d56accc7SDimitry Andric   if (existing)
164*d56accc7SDimitry Andric     with = " with " + toString(existing);
165*d56accc7SDimitry Andric   error(toString(file) + " is incompatible" + with);
1660b57cec5SDimitry Andric   return false;
1670b57cec5SDimitry Andric }
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric template <class ELFT> static void doParseFile(InputFile *file) {
1700b57cec5SDimitry Andric   if (!isCompatible(file))
1710b57cec5SDimitry Andric     return;
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   // Binary file
1740b57cec5SDimitry Andric   if (auto *f = dyn_cast<BinaryFile>(file)) {
1750b57cec5SDimitry Andric     binaryFiles.push_back(f);
1760b57cec5SDimitry Andric     f->parse();
1770b57cec5SDimitry Andric     return;
1780b57cec5SDimitry Andric   }
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   // .a file
1810b57cec5SDimitry Andric   if (auto *f = dyn_cast<ArchiveFile>(file)) {
1825ffd83dbSDimitry Andric     archiveFiles.push_back(f);
1830b57cec5SDimitry Andric     f->parse();
1840b57cec5SDimitry Andric     return;
1850b57cec5SDimitry Andric   }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   // Lazy object file
1880eae32dcSDimitry Andric   if (file->lazy) {
1890eae32dcSDimitry Andric     if (auto *f = dyn_cast<BitcodeFile>(file)) {
1900eae32dcSDimitry Andric       lazyBitcodeFiles.push_back(f);
1910eae32dcSDimitry Andric       f->parseLazy();
1920eae32dcSDimitry Andric     } else {
1930eae32dcSDimitry Andric       cast<ObjFile<ELFT>>(file)->parseLazy();
1940eae32dcSDimitry Andric     }
1950b57cec5SDimitry Andric     return;
1960b57cec5SDimitry Andric   }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric   if (config->trace)
1990b57cec5SDimitry Andric     message(toString(file));
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric   // .so file
2020b57cec5SDimitry Andric   if (auto *f = dyn_cast<SharedFile>(file)) {
2030b57cec5SDimitry Andric     f->parse<ELFT>();
2040b57cec5SDimitry Andric     return;
2050b57cec5SDimitry Andric   }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   // LLVM bitcode file
2080b57cec5SDimitry Andric   if (auto *f = dyn_cast<BitcodeFile>(file)) {
2090b57cec5SDimitry Andric     bitcodeFiles.push_back(f);
2100b57cec5SDimitry Andric     f->parse<ELFT>();
2110b57cec5SDimitry Andric     return;
2120b57cec5SDimitry Andric   }
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   // Regular object file
2150eae32dcSDimitry Andric   objectFiles.push_back(cast<ELFFileBase>(file));
2160b57cec5SDimitry Andric   cast<ObjFile<ELFT>>(file)->parse();
2170b57cec5SDimitry Andric }
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric // Add symbols in File to the symbol table.
2201fd87a68SDimitry Andric void elf::parseFile(InputFile *file) { invokeELFT(doParseFile, file); }
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric // Concatenates arguments to construct a string representing an error location.
2230b57cec5SDimitry Andric static std::string createFileLineMsg(StringRef path, unsigned line) {
2245ffd83dbSDimitry Andric   std::string filename = std::string(path::filename(path));
2250b57cec5SDimitry Andric   std::string lineno = ":" + std::to_string(line);
2260b57cec5SDimitry Andric   if (filename == path)
2270b57cec5SDimitry Andric     return filename + lineno;
2280b57cec5SDimitry Andric   return filename + lineno + " (" + path.str() + lineno + ")";
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric template <class ELFT>
2320b57cec5SDimitry Andric static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym,
2330b57cec5SDimitry Andric                                 InputSectionBase &sec, uint64_t offset) {
2340b57cec5SDimitry Andric   // In DWARF, functions and variables are stored to different places.
2350b57cec5SDimitry Andric   // First, lookup a function for a given offset.
2360b57cec5SDimitry Andric   if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
2370b57cec5SDimitry Andric     return createFileLineMsg(info->FileName, info->Line);
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   // If it failed, lookup again as a variable.
2400b57cec5SDimitry Andric   if (Optional<std::pair<std::string, unsigned>> fileLine =
2410b57cec5SDimitry Andric           file.getVariableLoc(sym.getName()))
2420b57cec5SDimitry Andric     return createFileLineMsg(fileLine->first, fileLine->second);
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   // File.sourceFile contains STT_FILE symbol, and that is a last resort.
2455ffd83dbSDimitry Andric   return std::string(file.sourceFile);
2460b57cec5SDimitry Andric }
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec,
2490b57cec5SDimitry Andric                                  uint64_t offset) {
2500b57cec5SDimitry Andric   if (kind() != ObjKind)
2510b57cec5SDimitry Andric     return "";
2520b57cec5SDimitry Andric   switch (config->ekind) {
2530b57cec5SDimitry Andric   default:
2540b57cec5SDimitry Andric     llvm_unreachable("Invalid kind");
2550b57cec5SDimitry Andric   case ELF32LEKind:
2560b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset);
2570b57cec5SDimitry Andric   case ELF32BEKind:
2580b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset);
2590b57cec5SDimitry Andric   case ELF64LEKind:
2600b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset);
2610b57cec5SDimitry Andric   case ELF64BEKind:
2620b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset);
2630b57cec5SDimitry Andric   }
2640b57cec5SDimitry Andric }
2650b57cec5SDimitry Andric 
266e8d8bef9SDimitry Andric StringRef InputFile::getNameForScript() const {
267e8d8bef9SDimitry Andric   if (archiveName.empty())
268e8d8bef9SDimitry Andric     return getName();
269e8d8bef9SDimitry Andric 
270e8d8bef9SDimitry Andric   if (nameForScriptCache.empty())
271e8d8bef9SDimitry Andric     nameForScriptCache = (archiveName + Twine(':') + getName()).str();
272e8d8bef9SDimitry Andric 
273e8d8bef9SDimitry Andric   return nameForScriptCache;
274e8d8bef9SDimitry Andric }
275e8d8bef9SDimitry Andric 
2765ffd83dbSDimitry Andric template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() {
2775ffd83dbSDimitry Andric   llvm::call_once(initDwarf, [this]() {
2785ffd83dbSDimitry Andric     dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
2795ffd83dbSDimitry Andric         std::make_unique<LLDDwarfObj<ELFT>>(this), "",
2805ffd83dbSDimitry Andric         [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
2815ffd83dbSDimitry Andric         [&](Error warning) {
2825ffd83dbSDimitry Andric           warn(getName() + ": " + toString(std::move(warning)));
2835ffd83dbSDimitry Andric         }));
2845ffd83dbSDimitry Andric   });
2855ffd83dbSDimitry Andric 
2865ffd83dbSDimitry Andric   return dwarf.get();
2870b57cec5SDimitry Andric }
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric // Returns the pair of file name and line number describing location of data
2900b57cec5SDimitry Andric // object (variable, array, etc) definition.
2910b57cec5SDimitry Andric template <class ELFT>
2920b57cec5SDimitry Andric Optional<std::pair<std::string, unsigned>>
2930b57cec5SDimitry Andric ObjFile<ELFT>::getVariableLoc(StringRef name) {
2945ffd83dbSDimitry Andric   return getDwarf()->getVariableLoc(name);
2950b57cec5SDimitry Andric }
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric // Returns source line information for a given offset
2980b57cec5SDimitry Andric // using DWARF debug info.
2990b57cec5SDimitry Andric template <class ELFT>
3000b57cec5SDimitry Andric Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s,
3010b57cec5SDimitry Andric                                                   uint64_t offset) {
3020b57cec5SDimitry Andric   // Detect SectionIndex for specified section.
3030b57cec5SDimitry Andric   uint64_t sectionIndex = object::SectionedAddress::UndefSection;
3040b57cec5SDimitry Andric   ArrayRef<InputSectionBase *> sections = s->file->getSections();
3050b57cec5SDimitry Andric   for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) {
3060b57cec5SDimitry Andric     if (s == sections[curIndex]) {
3070b57cec5SDimitry Andric       sectionIndex = curIndex;
3080b57cec5SDimitry Andric       break;
3090b57cec5SDimitry Andric     }
3100b57cec5SDimitry Andric   }
3110b57cec5SDimitry Andric 
3125ffd83dbSDimitry Andric   return getDwarf()->getDILineInfo(offset, sectionIndex);
3130b57cec5SDimitry Andric }
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) {
3160b57cec5SDimitry Andric   ekind = getELFKind(mb, "");
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   switch (ekind) {
3190b57cec5SDimitry Andric   case ELF32LEKind:
3200b57cec5SDimitry Andric     init<ELF32LE>();
3210b57cec5SDimitry Andric     break;
3220b57cec5SDimitry Andric   case ELF32BEKind:
3230b57cec5SDimitry Andric     init<ELF32BE>();
3240b57cec5SDimitry Andric     break;
3250b57cec5SDimitry Andric   case ELF64LEKind:
3260b57cec5SDimitry Andric     init<ELF64LE>();
3270b57cec5SDimitry Andric     break;
3280b57cec5SDimitry Andric   case ELF64BEKind:
3290b57cec5SDimitry Andric     init<ELF64BE>();
3300b57cec5SDimitry Andric     break;
3310b57cec5SDimitry Andric   default:
3320b57cec5SDimitry Andric     llvm_unreachable("getELFKind");
3330b57cec5SDimitry Andric   }
3340b57cec5SDimitry Andric }
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric template <typename Elf_Shdr>
3370b57cec5SDimitry Andric static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
3380b57cec5SDimitry Andric   for (const Elf_Shdr &sec : sections)
3390b57cec5SDimitry Andric     if (sec.sh_type == type)
3400b57cec5SDimitry Andric       return &sec;
3410b57cec5SDimitry Andric   return nullptr;
3420b57cec5SDimitry Andric }
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric template <class ELFT> void ELFFileBase::init() {
3450b57cec5SDimitry Andric   using Elf_Shdr = typename ELFT::Shdr;
3460b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric   // Initialize trivial attributes.
3490b57cec5SDimitry Andric   const ELFFile<ELFT> &obj = getObj<ELFT>();
350e8d8bef9SDimitry Andric   emachine = obj.getHeader().e_machine;
351e8d8bef9SDimitry Andric   osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI];
352e8d8bef9SDimitry Andric   abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION];
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
3550eae32dcSDimitry Andric   elfShdrs = sections.data();
3560eae32dcSDimitry Andric   numELFShdrs = sections.size();
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric   // Find a symbol table.
3590b57cec5SDimitry Andric   bool isDSO =
3600b57cec5SDimitry Andric       (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
3610b57cec5SDimitry Andric   const Elf_Shdr *symtabSec =
3620b57cec5SDimitry Andric       findSection(sections, isDSO ? SHT_DYNSYM : SHT_SYMTAB);
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   if (!symtabSec)
3650b57cec5SDimitry Andric     return;
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   // Initialize members corresponding to a symbol table.
3680b57cec5SDimitry Andric   firstGlobal = symtabSec->sh_info;
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric   ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
3710b57cec5SDimitry Andric   if (firstGlobal == 0 || firstGlobal > eSyms.size())
3720b57cec5SDimitry Andric     fatal(toString(this) + ": invalid sh_info in symbol table");
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   elfSyms = reinterpret_cast<const void *>(eSyms.data());
3750eae32dcSDimitry Andric   numELFSyms = uint32_t(eSyms.size());
3760b57cec5SDimitry Andric   stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
3770b57cec5SDimitry Andric }
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric template <class ELFT>
3800b57cec5SDimitry Andric uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
3810b57cec5SDimitry Andric   return CHECK(
382e8d8bef9SDimitry Andric       this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable),
3830b57cec5SDimitry Andric       this);
3840b57cec5SDimitry Andric }
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
3871fd87a68SDimitry Andric   object::ELFFile<ELFT> obj = this->getObj();
3880b57cec5SDimitry Andric   // Read a section table. justSymbols is usually false.
3890b57cec5SDimitry Andric   if (this->justSymbols)
3900b57cec5SDimitry Andric     initializeJustSymbols();
3910b57cec5SDimitry Andric   else
3921fd87a68SDimitry Andric     initializeSections(ignoreComdats, obj);
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   // Read a symbol table.
3951fd87a68SDimitry Andric   initializeSymbols(obj);
3960b57cec5SDimitry Andric }
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric // Sections with SHT_GROUP and comdat bits define comdat section groups.
3990b57cec5SDimitry Andric // They are identified and deduplicated by group name. This function
4000b57cec5SDimitry Andric // returns a group name.
4010b57cec5SDimitry Andric template <class ELFT>
4020b57cec5SDimitry Andric StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
4030b57cec5SDimitry Andric                                               const Elf_Shdr &sec) {
4040b57cec5SDimitry Andric   typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
4050b57cec5SDimitry Andric   if (sec.sh_info >= symbols.size())
4060b57cec5SDimitry Andric     fatal(toString(this) + ": invalid symbol index");
4070b57cec5SDimitry Andric   const typename ELFT::Sym &sym = symbols[sec.sh_info];
408349cc55cSDimitry Andric   return CHECK(sym.getName(this->stringTable), this);
4090b57cec5SDimitry Andric }
4100b57cec5SDimitry Andric 
41185868e8aSDimitry Andric template <class ELFT>
41285868e8aSDimitry Andric bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
4130b57cec5SDimitry Andric   // On a regular link we don't merge sections if -O0 (default is -O1). This
4140b57cec5SDimitry Andric   // sometimes makes the linker significantly faster, although the output will
4150b57cec5SDimitry Andric   // be bigger.
4160b57cec5SDimitry Andric   //
4170b57cec5SDimitry Andric   // Doing the same for -r would create a problem as it would combine sections
4180b57cec5SDimitry Andric   // with different sh_entsize. One option would be to just copy every SHF_MERGE
4190b57cec5SDimitry Andric   // section as is to the output. While this would produce a valid ELF file with
4200b57cec5SDimitry Andric   // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
4210b57cec5SDimitry Andric   // they see two .debug_str. We could have separate logic for combining
4220b57cec5SDimitry Andric   // SHF_MERGE sections based both on their name and sh_entsize, but that seems
4230b57cec5SDimitry Andric   // to be more trouble than it is worth. Instead, we just use the regular (-O1)
4240b57cec5SDimitry Andric   // logic for -r.
4250b57cec5SDimitry Andric   if (config->optimize == 0 && !config->relocatable)
4260b57cec5SDimitry Andric     return false;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   // A mergeable section with size 0 is useless because they don't have
4290b57cec5SDimitry Andric   // any data to merge. A mergeable string section with size 0 can be
4300b57cec5SDimitry Andric   // argued as invalid because it doesn't end with a null character.
4310b57cec5SDimitry Andric   // We'll avoid a mess by handling them as if they were non-mergeable.
4320b57cec5SDimitry Andric   if (sec.sh_size == 0)
4330b57cec5SDimitry Andric     return false;
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   // Check for sh_entsize. The ELF spec is not clear about the zero
4360b57cec5SDimitry Andric   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
4370b57cec5SDimitry Andric   // the section does not hold a table of fixed-size entries". We know
4380b57cec5SDimitry Andric   // that Rust 1.13 produces a string mergeable section with a zero
4390b57cec5SDimitry Andric   // sh_entsize. Here we just accept it rather than being picky about it.
4400b57cec5SDimitry Andric   uint64_t entSize = sec.sh_entsize;
4410b57cec5SDimitry Andric   if (entSize == 0)
4420b57cec5SDimitry Andric     return false;
4430b57cec5SDimitry Andric   if (sec.sh_size % entSize)
44485868e8aSDimitry Andric     fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" +
44585868e8aSDimitry Andric           Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" +
44685868e8aSDimitry Andric           Twine(entSize) + ")");
4470b57cec5SDimitry Andric 
4485ffd83dbSDimitry Andric   if (sec.sh_flags & SHF_WRITE)
44985868e8aSDimitry Andric     fatal(toString(this) + ":(" + name +
45085868e8aSDimitry Andric           "): writable SHF_MERGE section is not supported");
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   return true;
4530b57cec5SDimitry Andric }
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric // This is for --just-symbols.
4560b57cec5SDimitry Andric //
4570b57cec5SDimitry Andric // --just-symbols is a very minor feature that allows you to link your
4580b57cec5SDimitry Andric // output against other existing program, so that if you load both your
4590b57cec5SDimitry Andric // program and the other program into memory, your output can refer the
4600b57cec5SDimitry Andric // other program's symbols.
4610b57cec5SDimitry Andric //
4620b57cec5SDimitry Andric // When the option is given, we link "just symbols". The section table is
4630b57cec5SDimitry Andric // initialized with null pointers.
4640b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
4650eae32dcSDimitry Andric   sections.resize(numELFShdrs);
4660b57cec5SDimitry Andric }
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric // An ELF object file may contain a `.deplibs` section. If it exists, the
4690b57cec5SDimitry Andric // section contains a list of library specifiers such as `m` for libm. This
4700b57cec5SDimitry Andric // function resolves a given name by finding the first matching library checking
4710b57cec5SDimitry Andric // the various ways that a library can be specified to LLD. This ELF extension
4720b57cec5SDimitry Andric // is a form of autolinking and is called `dependent libraries`. It is currently
4730b57cec5SDimitry Andric // unique to LLVM and lld.
4740b57cec5SDimitry Andric static void addDependentLibrary(StringRef specifier, const InputFile *f) {
4750b57cec5SDimitry Andric   if (!config->dependentLibraries)
4760b57cec5SDimitry Andric     return;
4771fd87a68SDimitry Andric   if (Optional<std::string> s = searchLibraryBaseName(specifier))
4781fd87a68SDimitry Andric     driver->addFile(*s, /*withLOption=*/true);
4790b57cec5SDimitry Andric   else if (Optional<std::string> s = findFromSearchPaths(specifier))
4800b57cec5SDimitry Andric     driver->addFile(*s, /*withLOption=*/true);
4811fd87a68SDimitry Andric   else if (fs::exists(specifier))
4821fd87a68SDimitry Andric     driver->addFile(specifier, /*withLOption=*/false);
4830b57cec5SDimitry Andric   else
4840b57cec5SDimitry Andric     error(toString(f) +
4850b57cec5SDimitry Andric           ": unable to find library from dependent library specifier: " +
4860b57cec5SDimitry Andric           specifier);
4870b57cec5SDimitry Andric }
4880b57cec5SDimitry Andric 
489480093f4SDimitry Andric // Record the membership of a section group so that in the garbage collection
490480093f4SDimitry Andric // pass, section group members are kept or discarded as a unit.
491480093f4SDimitry Andric template <class ELFT>
492480093f4SDimitry Andric static void handleSectionGroup(ArrayRef<InputSectionBase *> sections,
493480093f4SDimitry Andric                                ArrayRef<typename ELFT::Word> entries) {
494480093f4SDimitry Andric   bool hasAlloc = false;
495480093f4SDimitry Andric   for (uint32_t index : entries.slice(1)) {
496480093f4SDimitry Andric     if (index >= sections.size())
497480093f4SDimitry Andric       return;
498480093f4SDimitry Andric     if (InputSectionBase *s = sections[index])
499480093f4SDimitry Andric       if (s != &InputSection::discarded && s->flags & SHF_ALLOC)
500480093f4SDimitry Andric         hasAlloc = true;
501480093f4SDimitry Andric   }
502480093f4SDimitry Andric 
503480093f4SDimitry Andric   // If any member has the SHF_ALLOC flag, the whole group is subject to garbage
504480093f4SDimitry Andric   // collection. See the comment in markLive(). This rule retains .debug_types
505480093f4SDimitry Andric   // and .rela.debug_types.
506480093f4SDimitry Andric   if (!hasAlloc)
507480093f4SDimitry Andric     return;
508480093f4SDimitry Andric 
509480093f4SDimitry Andric   // Connect the members in a circular doubly-linked list via
510480093f4SDimitry Andric   // nextInSectionGroup.
511480093f4SDimitry Andric   InputSectionBase *head;
512480093f4SDimitry Andric   InputSectionBase *prev = nullptr;
513480093f4SDimitry Andric   for (uint32_t index : entries.slice(1)) {
514480093f4SDimitry Andric     InputSectionBase *s = sections[index];
515480093f4SDimitry Andric     if (!s || s == &InputSection::discarded)
516480093f4SDimitry Andric       continue;
517480093f4SDimitry Andric     if (prev)
518480093f4SDimitry Andric       prev->nextInSectionGroup = s;
519480093f4SDimitry Andric     else
520480093f4SDimitry Andric       head = s;
521480093f4SDimitry Andric     prev = s;
522480093f4SDimitry Andric   }
523480093f4SDimitry Andric   if (prev)
524480093f4SDimitry Andric     prev->nextInSectionGroup = head;
525480093f4SDimitry Andric }
526480093f4SDimitry Andric 
5270b57cec5SDimitry Andric template <class ELFT>
5281fd87a68SDimitry Andric void ObjFile<ELFT>::initializeSections(bool ignoreComdats,
5291fd87a68SDimitry Andric                                        const llvm::object::ELFFile<ELFT> &obj) {
5300eae32dcSDimitry Andric   ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
531349cc55cSDimitry Andric   StringRef shstrtab = CHECK(obj.getSectionStringTable(objSections), this);
5320b57cec5SDimitry Andric   uint64_t size = objSections.size();
5330b57cec5SDimitry Andric   this->sections.resize(size);
5340b57cec5SDimitry Andric 
535480093f4SDimitry Andric   std::vector<ArrayRef<Elf_Word>> selectedGroups;
536480093f4SDimitry Andric 
53704eeddc0SDimitry Andric   for (size_t i = 0; i != size; ++i) {
5380b57cec5SDimitry Andric     if (this->sections[i] == &InputSection::discarded)
5390b57cec5SDimitry Andric       continue;
5400b57cec5SDimitry Andric     const Elf_Shdr &sec = objSections[i];
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
5430b57cec5SDimitry Andric     // if -r is given, we'll let the final link discard such sections.
5440b57cec5SDimitry Andric     // This is compatible with GNU.
5450b57cec5SDimitry Andric     if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) {
5460eae32dcSDimitry Andric       if (sec.sh_type == SHT_LLVM_CALL_GRAPH_PROFILE)
5470eae32dcSDimitry Andric         cgProfileSectionIndex = i;
5480b57cec5SDimitry Andric       if (sec.sh_type == SHT_LLVM_ADDRSIG) {
5490b57cec5SDimitry Andric         // We ignore the address-significance table if we know that the object
5500b57cec5SDimitry Andric         // file was created by objcopy or ld -r. This is because these tools
5510b57cec5SDimitry Andric         // will reorder the symbols in the symbol table, invalidating the data
5520b57cec5SDimitry Andric         // in the address-significance table, which refers to symbols by index.
5530b57cec5SDimitry Andric         if (sec.sh_link != 0)
5540b57cec5SDimitry Andric           this->addrsigSec = &sec;
5550b57cec5SDimitry Andric         else if (config->icf == ICFLevel::Safe)
556fe6060f1SDimitry Andric           warn(toString(this) +
557fe6060f1SDimitry Andric                ": --icf=safe conservatively ignores "
558fe6060f1SDimitry Andric                "SHT_LLVM_ADDRSIG [index " +
559fe6060f1SDimitry Andric                Twine(i) +
560fe6060f1SDimitry Andric                "] with sh_link=0 "
561fe6060f1SDimitry Andric                "(likely created using objcopy or ld -r)");
5620b57cec5SDimitry Andric       }
5630b57cec5SDimitry Andric       this->sections[i] = &InputSection::discarded;
5640b57cec5SDimitry Andric       continue;
5650b57cec5SDimitry Andric     }
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric     switch (sec.sh_type) {
5680b57cec5SDimitry Andric     case SHT_GROUP: {
5690b57cec5SDimitry Andric       // De-duplicate section groups by their signatures.
5700b57cec5SDimitry Andric       StringRef signature = getShtGroupSignature(objSections, sec);
5710b57cec5SDimitry Andric       this->sections[i] = &InputSection::discarded;
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric       ArrayRef<Elf_Word> entries =
574e8d8bef9SDimitry Andric           CHECK(obj.template getSectionContentsAsArray<Elf_Word>(sec), this);
5750b57cec5SDimitry Andric       if (entries.empty())
5760b57cec5SDimitry Andric         fatal(toString(this) + ": empty SHT_GROUP");
5770b57cec5SDimitry Andric 
578fe6060f1SDimitry Andric       Elf_Word flag = entries[0];
579fe6060f1SDimitry Andric       if (flag && flag != GRP_COMDAT)
5800b57cec5SDimitry Andric         fatal(toString(this) + ": unsupported SHT_GROUP format");
5810b57cec5SDimitry Andric 
582fe6060f1SDimitry Andric       bool keepGroup =
583fe6060f1SDimitry Andric           (flag & GRP_COMDAT) == 0 || ignoreComdats ||
5840b57cec5SDimitry Andric           symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
5850b57cec5SDimitry Andric               .second;
586fe6060f1SDimitry Andric       if (keepGroup) {
5870b57cec5SDimitry Andric         if (config->relocatable)
5881fd87a68SDimitry Andric           this->sections[i] = createInputSection(
5891fd87a68SDimitry Andric               i, sec, check(obj.getSectionName(sec, shstrtab)));
590480093f4SDimitry Andric         selectedGroups.push_back(entries);
5910b57cec5SDimitry Andric         continue;
5920b57cec5SDimitry Andric       }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric       // Otherwise, discard group members.
5950b57cec5SDimitry Andric       for (uint32_t secIndex : entries.slice(1)) {
5960b57cec5SDimitry Andric         if (secIndex >= size)
5970b57cec5SDimitry Andric           fatal(toString(this) +
5980b57cec5SDimitry Andric                 ": invalid section index in group: " + Twine(secIndex));
5990b57cec5SDimitry Andric         this->sections[secIndex] = &InputSection::discarded;
6000b57cec5SDimitry Andric       }
6010b57cec5SDimitry Andric       break;
6020b57cec5SDimitry Andric     }
6030b57cec5SDimitry Andric     case SHT_SYMTAB_SHNDX:
6040b57cec5SDimitry Andric       shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
6050b57cec5SDimitry Andric       break;
6060b57cec5SDimitry Andric     case SHT_SYMTAB:
6070b57cec5SDimitry Andric     case SHT_STRTAB:
6085ffd83dbSDimitry Andric     case SHT_REL:
6095ffd83dbSDimitry Andric     case SHT_RELA:
6100b57cec5SDimitry Andric     case SHT_NULL:
6110b57cec5SDimitry Andric       break;
6120b57cec5SDimitry Andric     default:
6131fd87a68SDimitry Andric       this->sections[i] =
6141fd87a68SDimitry Andric           createInputSection(i, sec, check(obj.getSectionName(sec, shstrtab)));
6150b57cec5SDimitry Andric     }
61685868e8aSDimitry Andric   }
61785868e8aSDimitry Andric 
6185ffd83dbSDimitry Andric   // We have a second loop. It is used to:
6195ffd83dbSDimitry Andric   // 1) handle SHF_LINK_ORDER sections.
6205ffd83dbSDimitry Andric   // 2) create SHT_REL[A] sections. In some cases the section header index of a
6215ffd83dbSDimitry Andric   //    relocation section may be smaller than that of the relocated section. In
6225ffd83dbSDimitry Andric   //    such cases, the relocation section would attempt to reference a target
6235ffd83dbSDimitry Andric   //    section that has not yet been created. For simplicity, delay creation of
6245ffd83dbSDimitry Andric   //    relocation sections until now.
62504eeddc0SDimitry Andric   for (size_t i = 0; i != size; ++i) {
62685868e8aSDimitry Andric     if (this->sections[i] == &InputSection::discarded)
62785868e8aSDimitry Andric       continue;
62885868e8aSDimitry Andric     const Elf_Shdr &sec = objSections[i];
6295ffd83dbSDimitry Andric 
63004eeddc0SDimitry Andric     if (sec.sh_type == SHT_REL || sec.sh_type == SHT_RELA) {
63104eeddc0SDimitry Andric       // Find a relocation target section and associate this section with that.
63204eeddc0SDimitry Andric       // Target may have been discarded if it is in a different section group
63304eeddc0SDimitry Andric       // and the group is discarded, even though it's a violation of the spec.
63404eeddc0SDimitry Andric       // We handle that situation gracefully by discarding dangling relocation
63504eeddc0SDimitry Andric       // sections.
63604eeddc0SDimitry Andric       const uint32_t info = sec.sh_info;
63704eeddc0SDimitry Andric       InputSectionBase *s = getRelocTarget(i, sec, info);
63804eeddc0SDimitry Andric       if (!s)
63904eeddc0SDimitry Andric         continue;
64004eeddc0SDimitry Andric 
64104eeddc0SDimitry Andric       // ELF spec allows mergeable sections with relocations, but they are rare,
64204eeddc0SDimitry Andric       // and it is in practice hard to merge such sections by contents, because
64304eeddc0SDimitry Andric       // applying relocations at end of linking changes section contents. So, we
64404eeddc0SDimitry Andric       // simply handle such sections as non-mergeable ones. Degrading like this
64504eeddc0SDimitry Andric       // is acceptable because section merging is optional.
64604eeddc0SDimitry Andric       if (auto *ms = dyn_cast<MergeInputSection>(s)) {
64704eeddc0SDimitry Andric         s = make<InputSection>(ms->file, ms->flags, ms->type, ms->alignment,
64804eeddc0SDimitry Andric                                ms->data(), ms->name);
64904eeddc0SDimitry Andric         sections[info] = s;
65004eeddc0SDimitry Andric       }
65104eeddc0SDimitry Andric 
65204eeddc0SDimitry Andric       if (s->relSecIdx != 0)
65304eeddc0SDimitry Andric         error(
65404eeddc0SDimitry Andric             toString(s) +
65504eeddc0SDimitry Andric             ": multiple relocation sections to one section are not supported");
65604eeddc0SDimitry Andric       s->relSecIdx = i;
65704eeddc0SDimitry Andric 
65804eeddc0SDimitry Andric       // Relocation sections are usually removed from the output, so return
65904eeddc0SDimitry Andric       // `nullptr` for the normal case. However, if -r or --emit-relocs is
66004eeddc0SDimitry Andric       // specified, we need to copy them to the output. (Some post link analysis
66104eeddc0SDimitry Andric       // tools specify --emit-relocs to obtain the information.)
66204eeddc0SDimitry Andric       if (config->copyRelocs) {
66304eeddc0SDimitry Andric         auto *isec = make<InputSection>(
66404eeddc0SDimitry Andric             *this, sec, check(obj.getSectionName(sec, shstrtab)));
66504eeddc0SDimitry Andric         // If the relocated section is discarded (due to /DISCARD/ or
66604eeddc0SDimitry Andric         // --gc-sections), the relocation section should be discarded as well.
66704eeddc0SDimitry Andric         s->dependentSections.push_back(isec);
66804eeddc0SDimitry Andric         sections[i] = isec;
66904eeddc0SDimitry Andric       }
67004eeddc0SDimitry Andric       continue;
67104eeddc0SDimitry Andric     }
6725ffd83dbSDimitry Andric 
673e8d8bef9SDimitry Andric     // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have
674e8d8bef9SDimitry Andric     // the flag.
67504eeddc0SDimitry Andric     if (!sec.sh_link || !(sec.sh_flags & SHF_LINK_ORDER))
67685868e8aSDimitry Andric       continue;
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric     InputSectionBase *linkSec = nullptr;
67904eeddc0SDimitry Andric     if (sec.sh_link < 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 
684e8d8bef9SDimitry Andric     // A SHF_LINK_ORDER section is discarded if its linked-to section is
685e8d8bef9SDimitry 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.
796e8d8bef9SDimitry 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;
801e8d8bef9SDimitry Andric   ArrayRef<uint8_t> data = sec.data();
802e8d8bef9SDimitry Andric   auto reportFatal = [&](const uint8_t *place, const char *msg) {
803e8d8bef9SDimitry Andric     fatal(toString(sec.file) + ":(" + sec.name + "+0x" +
804e8d8bef9SDimitry Andric           Twine::utohexstr(place - sec.data().data()) + "): " + msg);
805e8d8bef9SDimitry Andric   };
8060b57cec5SDimitry Andric   while (!data.empty()) {
8070b57cec5SDimitry Andric     // Read one NOTE record.
8080b57cec5SDimitry Andric     auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
809e8d8bef9SDimitry Andric     if (data.size() < sizeof(Elf_Nhdr) || data.size() < nhdr->getSize())
810e8d8bef9SDimitry 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()) {
825e8d8bef9SDimitry Andric       const uint8_t *place = desc.data();
8260b57cec5SDimitry Andric       if (desc.size() < 8)
827e8d8bef9SDimitry Andric         reportFatal(place, "program property is too short");
828e8d8bef9SDimitry Andric       uint32_t type = read32<ELFT::TargetEndianness>(desc.data());
829e8d8bef9SDimitry Andric       uint32_t size = read32<ELFT::TargetEndianness>(desc.data() + 4);
830e8d8bef9SDimitry Andric       desc = desc.slice(8);
831e8d8bef9SDimitry Andric       if (desc.size() < size)
832e8d8bef9SDimitry 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.
838e8d8bef9SDimitry Andric         if (size < 4)
839e8d8bef9SDimitry Andric           reportFatal(place, "FEATURE_1_AND entry is too short");
840e8d8bef9SDimitry Andric         featuresSet |= read32<ELFT::TargetEndianness>(desc.data());
8410b57cec5SDimitry Andric       }
8420b57cec5SDimitry Andric 
843e8d8bef9SDimitry Andric       // Padding is present in the note descriptor, if necessary.
844e8d8bef9SDimitry 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>
85504eeddc0SDimitry Andric InputSectionBase *ObjFile<ELFT>::getRelocTarget(uint32_t idx,
85604eeddc0SDimitry Andric                                                 const Elf_Shdr &sec,
85704eeddc0SDimitry Andric                                                 uint32_t info) {
858349cc55cSDimitry Andric   if (info < this->sections.size()) {
859349cc55cSDimitry Andric     InputSectionBase *target = this->sections[info];
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 
867349cc55cSDimitry Andric     if (target != nullptr)
8680b57cec5SDimitry Andric       return target;
8690b57cec5SDimitry Andric   }
8700b57cec5SDimitry Andric 
87104eeddc0SDimitry Andric   error(toString(this) + Twine(": relocation section (index ") + Twine(idx) +
87204eeddc0SDimitry Andric         ") has invalid sh_info (" + Twine(info) + ")");
873349cc55cSDimitry Andric   return nullptr;
874349cc55cSDimitry Andric }
875349cc55cSDimitry Andric 
8760b57cec5SDimitry Andric template <class ELFT>
877349cc55cSDimitry Andric InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx,
878349cc55cSDimitry Andric                                                     const Elf_Shdr &sec,
8791fd87a68SDimitry Andric                                                     StringRef name) {
8801fd87a68SDimitry Andric   if (sec.sh_type == SHT_ARM_ATTRIBUTES && config->emachine == EM_ARM) {
8810b57cec5SDimitry Andric     ARMAttributeParser attributes;
882e8d8bef9SDimitry Andric     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec));
8835ffd83dbSDimitry Andric     if (Error e = attributes.parse(contents, config->ekind == ELF32LEKind
8845ffd83dbSDimitry Andric                                                  ? support::little
8855ffd83dbSDimitry Andric                                                  : support::big)) {
8865ffd83dbSDimitry Andric       auto *isec = make<InputSection>(*this, sec, name);
8875ffd83dbSDimitry Andric       warn(toString(isec) + ": " + llvm::toString(std::move(e)));
888e8d8bef9SDimitry Andric     } else {
8890b57cec5SDimitry Andric       updateSupportedARMFeatures(attributes);
8900b57cec5SDimitry Andric       updateARMVFPArgs(attributes, this);
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric       // FIXME: Retain the first attribute section we see. The eglibc ARM
8930b57cec5SDimitry Andric       // dynamic loaders require the presence of an attribute section for dlopen
894e8d8bef9SDimitry Andric       // to work. In a full implementation we would merge all attribute
895e8d8bef9SDimitry Andric       // sections.
896e8d8bef9SDimitry Andric       if (in.attributes == nullptr) {
89704eeddc0SDimitry Andric         in.attributes = std::make_unique<InputSection>(*this, sec, name);
89804eeddc0SDimitry Andric         return in.attributes.get();
8990b57cec5SDimitry Andric       }
9000b57cec5SDimitry Andric       return &InputSection::discarded;
9010b57cec5SDimitry Andric     }
902e8d8bef9SDimitry Andric   }
903e8d8bef9SDimitry Andric 
9041fd87a68SDimitry Andric   if (sec.sh_type == SHT_RISCV_ATTRIBUTES && config->emachine == EM_RISCV) {
905e8d8bef9SDimitry Andric     RISCVAttributeParser attributes;
906e8d8bef9SDimitry Andric     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(sec));
907e8d8bef9SDimitry Andric     if (Error e = attributes.parse(contents, support::little)) {
908e8d8bef9SDimitry Andric       auto *isec = make<InputSection>(*this, sec, name);
909e8d8bef9SDimitry Andric       warn(toString(isec) + ": " + llvm::toString(std::move(e)));
910e8d8bef9SDimitry Andric     } else {
911e8d8bef9SDimitry Andric       // FIXME: Validate arch tag contains C if and only if EF_RISCV_RVC is
912e8d8bef9SDimitry Andric       // present.
913e8d8bef9SDimitry Andric 
914e8d8bef9SDimitry Andric       // FIXME: Retain the first attribute section we see. Tools such as
915e8d8bef9SDimitry Andric       // llvm-objdump make use of the attribute section to determine which
916e8d8bef9SDimitry Andric       // standard extensions to enable. In a full implementation we would merge
917e8d8bef9SDimitry Andric       // all attribute sections.
918e8d8bef9SDimitry Andric       if (in.attributes == nullptr) {
91904eeddc0SDimitry Andric         in.attributes = std::make_unique<InputSection>(*this, sec, name);
92004eeddc0SDimitry Andric         return in.attributes.get();
921e8d8bef9SDimitry Andric       }
922e8d8bef9SDimitry Andric       return &InputSection::discarded;
923e8d8bef9SDimitry Andric     }
924e8d8bef9SDimitry Andric   }
925e8d8bef9SDimitry Andric 
92604eeddc0SDimitry Andric   if (sec.sh_type == SHT_LLVM_DEPENDENT_LIBRARIES && !config->relocatable) {
9270b57cec5SDimitry Andric     ArrayRef<char> data =
928e8d8bef9SDimitry Andric         CHECK(this->getObj().template getSectionContentsAsArray<char>(sec), this);
9290b57cec5SDimitry Andric     if (!data.empty() && data.back() != '\0') {
9300b57cec5SDimitry Andric       error(toString(this) +
9310b57cec5SDimitry Andric             ": corrupted dependent libraries section (unterminated string): " +
9320b57cec5SDimitry Andric             name);
9330b57cec5SDimitry Andric       return &InputSection::discarded;
9340b57cec5SDimitry Andric     }
9350b57cec5SDimitry Andric     for (const char *d = data.begin(), *e = data.end(); d < e;) {
9360b57cec5SDimitry Andric       StringRef s(d);
9370b57cec5SDimitry Andric       addDependentLibrary(s, this);
9380b57cec5SDimitry Andric       d += s.size() + 1;
9390b57cec5SDimitry Andric     }
9400b57cec5SDimitry Andric     return &InputSection::discarded;
9410b57cec5SDimitry Andric   }
9420b57cec5SDimitry Andric 
9430eae32dcSDimitry Andric   if (name.startswith(".n")) {
9440b57cec5SDimitry Andric     // The GNU linker uses .note.GNU-stack section as a marker indicating
9450b57cec5SDimitry Andric     // that the code in the object file does not expect that the stack is
9460b57cec5SDimitry Andric     // executable (in terms of NX bit). If all input files have the marker,
9470b57cec5SDimitry Andric     // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
9480b57cec5SDimitry Andric     // make the stack non-executable. Most object files have this section as
9490b57cec5SDimitry Andric     // of 2017.
9500b57cec5SDimitry Andric     //
9510b57cec5SDimitry Andric     // But making the stack non-executable is a norm today for security
9520b57cec5SDimitry Andric     // reasons. Failure to do so may result in a serious security issue.
9530b57cec5SDimitry Andric     // Therefore, we make LLD always add PT_GNU_STACK unless it is
9540b57cec5SDimitry Andric     // explicitly told to do otherwise (by -z execstack). Because the stack
9550b57cec5SDimitry Andric     // executable-ness is controlled solely by command line options,
9560b57cec5SDimitry Andric     // .note.GNU-stack sections are simply ignored.
9570b57cec5SDimitry Andric     if (name == ".note.GNU-stack")
9580b57cec5SDimitry Andric       return &InputSection::discarded;
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric     // Object files that use processor features such as Intel Control-Flow
9610b57cec5SDimitry Andric     // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
9620b57cec5SDimitry Andric     // .note.gnu.property section containing a bitfield of feature bits like the
9630b57cec5SDimitry Andric     // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
9640b57cec5SDimitry Andric     //
9650b57cec5SDimitry Andric     // Since we merge bitmaps from multiple object files to create a new
9660b57cec5SDimitry Andric     // .note.gnu.property containing a single AND'ed bitmap, we discard an input
9670b57cec5SDimitry Andric     // file's .note.gnu.property section.
9680b57cec5SDimitry Andric     if (name == ".note.gnu.property") {
969e8d8bef9SDimitry Andric       this->andFeatures = readAndFeatures<ELFT>(InputSection(*this, sec, name));
9700b57cec5SDimitry Andric       return &InputSection::discarded;
9710b57cec5SDimitry Andric     }
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric     // Split stacks is a feature to support a discontiguous stack,
9740b57cec5SDimitry Andric     // commonly used in the programming language Go. For the details,
9750b57cec5SDimitry Andric     // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
9760b57cec5SDimitry Andric     // for split stack will include a .note.GNU-split-stack section.
9770b57cec5SDimitry Andric     if (name == ".note.GNU-split-stack") {
9780b57cec5SDimitry Andric       if (config->relocatable) {
9790eae32dcSDimitry Andric         error(
9800eae32dcSDimitry Andric             "cannot mix split-stack and non-split-stack in a relocatable link");
9810b57cec5SDimitry Andric         return &InputSection::discarded;
9820b57cec5SDimitry Andric       }
9830b57cec5SDimitry Andric       this->splitStack = true;
9840b57cec5SDimitry Andric       return &InputSection::discarded;
9850b57cec5SDimitry Andric     }
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric     // An object file cmpiled for split stack, but where some of the
9880b57cec5SDimitry Andric     // functions were compiled with the no_split_stack_attribute will
9890b57cec5SDimitry Andric     // include a .note.GNU-no-split-stack section.
9900b57cec5SDimitry Andric     if (name == ".note.GNU-no-split-stack") {
9910b57cec5SDimitry Andric       this->someNoSplitStack = true;
9920b57cec5SDimitry Andric       return &InputSection::discarded;
9930b57cec5SDimitry Andric     }
9940b57cec5SDimitry Andric 
9950eae32dcSDimitry Andric     // Strip existing .note.gnu.build-id sections so that the output won't have
9960eae32dcSDimitry Andric     // more than one build-id. This is not usually a problem because input
9970eae32dcSDimitry Andric     // object files normally don't have .build-id sections, but you can create
9980eae32dcSDimitry Andric     // such files by "ld.{bfd,gold,lld} -r --build-id", and we want to guard
9990eae32dcSDimitry Andric     // against it.
10000eae32dcSDimitry Andric     if (name == ".note.gnu.build-id")
10010eae32dcSDimitry Andric       return &InputSection::discarded;
10020eae32dcSDimitry Andric   }
10030eae32dcSDimitry Andric 
10040b57cec5SDimitry Andric   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
10050b57cec5SDimitry Andric   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
10060b57cec5SDimitry Andric   // sections. Drop those sections to avoid duplicate symbol errors.
10070b57cec5SDimitry Andric   // FIXME: This is glibc PR20543, we should remove this hack once that has been
10080b57cec5SDimitry Andric   // fixed for a while.
10090b57cec5SDimitry Andric   if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
10100b57cec5SDimitry Andric       name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
10110b57cec5SDimitry Andric     return &InputSection::discarded;
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric   // The linker merges EH (exception handling) frames and creates a
10140b57cec5SDimitry Andric   // .eh_frame_hdr section for runtime. So we handle them with a special
10150b57cec5SDimitry Andric   // class. For relocatable outputs, they are just passed through.
10160b57cec5SDimitry Andric   if (name == ".eh_frame" && !config->relocatable)
10170b57cec5SDimitry Andric     return make<EhInputSection>(*this, sec, name);
10180b57cec5SDimitry Andric 
10190eae32dcSDimitry Andric   if ((sec.sh_flags & SHF_MERGE) && shouldMerge(sec, name))
10200b57cec5SDimitry Andric     return make<MergeInputSection>(*this, sec, name);
10210b57cec5SDimitry Andric   return make<InputSection>(*this, sec, name);
10220b57cec5SDimitry Andric }
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric // Initialize this->Symbols. this->Symbols is a parallel array as
10250b57cec5SDimitry Andric // its corresponding ELF symbol table.
10261fd87a68SDimitry Andric template <class ELFT>
10271fd87a68SDimitry Andric void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) {
10280eae32dcSDimitry Andric   ArrayRef<InputSectionBase *> sections(this->sections);
10290eae32dcSDimitry Andric   SymbolTable &symtab = *elf::symtab;
10300b57cec5SDimitry Andric 
10310eae32dcSDimitry Andric   ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
10320eae32dcSDimitry Andric   symbols.resize(eSyms.size());
10330eae32dcSDimitry Andric   SymbolUnion *locals =
10340eae32dcSDimitry Andric       firstGlobal == 0
10350eae32dcSDimitry Andric           ? nullptr
10360eae32dcSDimitry Andric           : getSpecificAllocSingleton<SymbolUnion>().Allocate(firstGlobal);
10370eae32dcSDimitry Andric 
10380eae32dcSDimitry Andric   for (size_t i = 0, end = firstGlobal; i != end; ++i) {
10390b57cec5SDimitry Andric     const Elf_Sym &eSym = eSyms[i];
10401fd87a68SDimitry Andric     uint32_t secIdx = eSym.st_shndx;
10411fd87a68SDimitry Andric     if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
10421fd87a68SDimitry Andric       secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
10431fd87a68SDimitry Andric     else if (secIdx >= SHN_LORESERVE)
10441fd87a68SDimitry Andric       secIdx = 0;
10450eae32dcSDimitry Andric     if (LLVM_UNLIKELY(secIdx >= sections.size()))
10460b57cec5SDimitry Andric       fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
10470eae32dcSDimitry Andric     if (LLVM_UNLIKELY(eSym.getBinding() != STB_LOCAL))
10485ffd83dbSDimitry Andric       error(toString(this) + ": non-local symbol (" + Twine(i) +
10490eae32dcSDimitry Andric             ") found at index < .symtab's sh_info (" + Twine(end) + ")");
10505ffd83dbSDimitry Andric 
10510eae32dcSDimitry Andric     InputSectionBase *sec = sections[secIdx];
10525ffd83dbSDimitry Andric     uint8_t type = eSym.getType();
10535ffd83dbSDimitry Andric     if (type == STT_FILE)
10540eae32dcSDimitry Andric       sourceFile = CHECK(eSym.getName(stringTable), this);
10550eae32dcSDimitry Andric     if (LLVM_UNLIKELY(stringTable.size() <= eSym.st_name))
10565ffd83dbSDimitry Andric       fatal(toString(this) + ": invalid symbol name offset");
105704eeddc0SDimitry Andric     StringRef name(stringTable.data() + eSym.st_name);
10585ffd83dbSDimitry Andric 
10590eae32dcSDimitry Andric     symbols[i] = reinterpret_cast<Symbol *>(locals + i);
10600eae32dcSDimitry Andric     if (eSym.st_shndx == SHN_UNDEF || sec == &InputSection::discarded)
10610eae32dcSDimitry Andric       new (symbols[i]) Undefined(this, name, STB_LOCAL, eSym.st_other, type,
10625ffd83dbSDimitry Andric                                  /*discardedSecIdx=*/secIdx);
10635ffd83dbSDimitry Andric     else
10640eae32dcSDimitry Andric       new (symbols[i]) Defined(this, name, STB_LOCAL, eSym.st_other, type,
10650eae32dcSDimitry Andric                                eSym.st_value, eSym.st_size, sec);
10665ffd83dbSDimitry Andric   }
10675ffd83dbSDimitry Andric 
10680eae32dcSDimitry Andric   // Some entries have been filled by LazyObjFile.
10690eae32dcSDimitry Andric   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
10700eae32dcSDimitry Andric     if (!symbols[i])
10710eae32dcSDimitry Andric       symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this));
10720eae32dcSDimitry Andric 
10730eae32dcSDimitry Andric   // Perform symbol resolution on non-local symbols.
1074fe6060f1SDimitry Andric   SmallVector<unsigned, 32> undefineds;
10755ffd83dbSDimitry Andric   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
10765ffd83dbSDimitry Andric     const Elf_Sym &eSym = eSyms[i];
10770b57cec5SDimitry Andric     uint8_t binding = eSym.getBinding();
10780eae32dcSDimitry Andric     if (LLVM_UNLIKELY(binding == STB_LOCAL)) {
10790eae32dcSDimitry Andric       errorOrWarn(toString(this) + ": STB_LOCAL symbol (" + Twine(i) +
10800eae32dcSDimitry Andric                   ") found at index >= .symtab's sh_info (" +
10810eae32dcSDimitry Andric                   Twine(firstGlobal) + ")");
10820eae32dcSDimitry Andric       continue;
10830eae32dcSDimitry Andric     }
10841fd87a68SDimitry Andric     uint32_t secIdx = eSym.st_shndx;
10851fd87a68SDimitry Andric     if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
10861fd87a68SDimitry Andric       secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
10871fd87a68SDimitry Andric     else if (secIdx >= SHN_LORESERVE)
10881fd87a68SDimitry Andric       secIdx = 0;
10890eae32dcSDimitry Andric     if (LLVM_UNLIKELY(secIdx >= sections.size()))
10900eae32dcSDimitry Andric       fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
10910eae32dcSDimitry Andric     InputSectionBase *sec = sections[secIdx];
10920b57cec5SDimitry Andric     uint8_t stOther = eSym.st_other;
10930b57cec5SDimitry Andric     uint8_t type = eSym.getType();
10940b57cec5SDimitry Andric     uint64_t value = eSym.st_value;
10950b57cec5SDimitry Andric     uint64_t size = eSym.st_size;
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric     if (eSym.st_shndx == SHN_UNDEF) {
1098fe6060f1SDimitry Andric       undefineds.push_back(i);
10990b57cec5SDimitry Andric       continue;
11000b57cec5SDimitry Andric     }
11010b57cec5SDimitry Andric 
11020eae32dcSDimitry Andric     Symbol *sym = symbols[i];
11030eae32dcSDimitry Andric     const StringRef name = sym->getName();
11040eae32dcSDimitry Andric     if (LLVM_UNLIKELY(eSym.st_shndx == SHN_COMMON)) {
11050b57cec5SDimitry Andric       if (value == 0 || value >= UINT32_MAX)
11060eae32dcSDimitry Andric         fatal(toString(this) + ": common symbol '" + name +
11070b57cec5SDimitry Andric               "' has invalid alignment: " + Twine(value));
11080eae32dcSDimitry Andric       hasCommonSyms = true;
11090eae32dcSDimitry Andric       sym->resolve(
11100b57cec5SDimitry Andric           CommonSymbol{this, name, binding, stOther, type, value, size});
11110b57cec5SDimitry Andric       continue;
11120b57cec5SDimitry Andric     }
11130b57cec5SDimitry Andric 
11140b57cec5SDimitry Andric     // If a defined symbol is in a discarded section, handle it as if it
11150b57cec5SDimitry Andric     // were an undefined symbol. Such symbol doesn't comply with the
11160b57cec5SDimitry Andric     // standard, but in practice, a .eh_frame often directly refer
11170b57cec5SDimitry Andric     // COMDAT member sections, and if a comdat group is discarded, some
11180b57cec5SDimitry Andric     // defined symbol in a .eh_frame becomes dangling symbols.
11190b57cec5SDimitry Andric     if (sec == &InputSection::discarded) {
11205ffd83dbSDimitry Andric       Undefined und{this, name, binding, stOther, type, secIdx};
11210eae32dcSDimitry Andric       // !ArchiveFile::parsed or !LazyObjFile::lazy means that the file
11225ffd83dbSDimitry Andric       // containing this object has not finished processing, i.e. this symbol is
11234824e7fdSDimitry Andric       // a result of a lazy symbol extract. We should demote the lazy symbol to
11244824e7fdSDimitry Andric       // an Undefined so that any relocations outside of the group to it will
11255ffd83dbSDimitry Andric       // trigger a discarded section error.
11265ffd83dbSDimitry Andric       if ((sym->symbolKind == Symbol::LazyArchiveKind &&
11275ffd83dbSDimitry Andric            !cast<ArchiveFile>(sym->file)->parsed) ||
11280eae32dcSDimitry Andric           (sym->symbolKind == Symbol::LazyObjectKind && !sym->file->lazy)) {
11295ffd83dbSDimitry Andric         sym->replace(und);
11304824e7fdSDimitry Andric         // Prevent LTO from internalizing the symbol in case there is a
11314824e7fdSDimitry Andric         // reference to this symbol from this file.
11324824e7fdSDimitry Andric         sym->isUsedInRegularObj = true;
11334824e7fdSDimitry Andric       } else
11345ffd83dbSDimitry Andric         sym->resolve(und);
11350b57cec5SDimitry Andric       continue;
11360b57cec5SDimitry Andric     }
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric     // Handle global defined symbols.
11390b57cec5SDimitry Andric     if (binding == STB_GLOBAL || binding == STB_WEAK ||
11400b57cec5SDimitry Andric         binding == STB_GNU_UNIQUE) {
11410eae32dcSDimitry Andric       sym->resolve(
11420b57cec5SDimitry Andric           Defined{this, name, binding, stOther, type, value, size, sec});
11430b57cec5SDimitry Andric       continue;
11440b57cec5SDimitry Andric     }
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric     fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
11470b57cec5SDimitry Andric   }
1148fe6060f1SDimitry Andric 
1149fe6060f1SDimitry Andric   // Undefined symbols (excluding those defined relative to non-prevailing
11504824e7fdSDimitry Andric   // sections) can trigger recursive extract. Process defined symbols first so
1151fe6060f1SDimitry Andric   // that the relative order between a defined symbol and an undefined symbol
1152fe6060f1SDimitry Andric   // does not change the symbol resolution behavior. In addition, a set of
1153fe6060f1SDimitry Andric   // interconnected symbols will all be resolved to the same file, instead of
1154fe6060f1SDimitry Andric   // being resolved to different files.
1155fe6060f1SDimitry Andric   for (unsigned i : undefineds) {
1156fe6060f1SDimitry Andric     const Elf_Sym &eSym = eSyms[i];
11570eae32dcSDimitry Andric     Symbol *sym = symbols[i];
11580eae32dcSDimitry Andric     sym->resolve(Undefined{this, sym->getName(), eSym.getBinding(),
1159fe6060f1SDimitry Andric                            eSym.st_other, eSym.getType()});
11600eae32dcSDimitry Andric     sym->referenced = true;
1161fe6060f1SDimitry Andric   }
11620b57cec5SDimitry Andric }
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&file)
11650b57cec5SDimitry Andric     : InputFile(ArchiveKind, file->getMemoryBufferRef()),
11660b57cec5SDimitry Andric       file(std::move(file)) {}
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric void ArchiveFile::parse() {
11690eae32dcSDimitry Andric   SymbolTable &symtab = *elf::symtab;
11700b57cec5SDimitry Andric   for (const Archive::Symbol &sym : file->symbols())
11710eae32dcSDimitry Andric     symtab.addSymbol(LazyArchive{*this, sym});
11725ffd83dbSDimitry Andric 
11735ffd83dbSDimitry Andric   // Inform a future invocation of ObjFile<ELFT>::initializeSymbols() that this
11745ffd83dbSDimitry Andric   // archive has been processed.
11755ffd83dbSDimitry Andric   parsed = true;
11760b57cec5SDimitry Andric }
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric // Returns a buffer pointing to a member file containing a given symbol.
11794824e7fdSDimitry Andric void ArchiveFile::extract(const Archive::Symbol &sym) {
11800b57cec5SDimitry Andric   Archive::Child c =
11810b57cec5SDimitry Andric       CHECK(sym.getMember(), toString(this) +
11820b57cec5SDimitry Andric                                  ": could not get the member for symbol " +
11830b57cec5SDimitry Andric                                  toELFString(sym));
11840b57cec5SDimitry Andric 
11850b57cec5SDimitry Andric   if (!seen.insert(c.getChildOffset()).second)
11860b57cec5SDimitry Andric     return;
11870b57cec5SDimitry Andric 
11880b57cec5SDimitry Andric   MemoryBufferRef mb =
11890b57cec5SDimitry Andric       CHECK(c.getMemoryBufferRef(),
11900b57cec5SDimitry Andric             toString(this) +
11910b57cec5SDimitry Andric                 ": could not get the buffer for the member defining symbol " +
11920b57cec5SDimitry Andric                 toELFString(sym));
11930b57cec5SDimitry Andric 
11940b57cec5SDimitry Andric   if (tar && c.getParent()->isThin())
11950b57cec5SDimitry Andric     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
11960b57cec5SDimitry Andric 
11975ffd83dbSDimitry Andric   InputFile *file = createObjectFile(mb, getName(), c.getChildOffset());
11980b57cec5SDimitry Andric   file->groupId = groupId;
11990b57cec5SDimitry Andric   parseFile(file);
12000b57cec5SDimitry Andric }
12010b57cec5SDimitry Andric 
1202e8d8bef9SDimitry Andric // The handling of tentative definitions (COMMON symbols) in archives is murky.
1203fe6060f1SDimitry Andric // A tentative definition will be promoted to a global definition if there are
1204fe6060f1SDimitry Andric // no non-tentative definitions to dominate it. When we hold a tentative
1205fe6060f1SDimitry Andric // definition to a symbol and are inspecting archive members for inclusion
1206fe6060f1SDimitry Andric // there are 2 ways we can proceed:
1207e8d8bef9SDimitry Andric //
1208e8d8bef9SDimitry Andric // 1) Consider the tentative definition a 'real' definition (ie promotion from
1209e8d8bef9SDimitry Andric //    tentative to real definition has already happened) and not inspect
1210e8d8bef9SDimitry Andric //    archive members for Global/Weak definitions to replace the tentative
1211e8d8bef9SDimitry Andric //    definition. An archive member would only be included if it satisfies some
1212e8d8bef9SDimitry Andric //    other undefined symbol. This is the behavior Gold uses.
1213e8d8bef9SDimitry Andric //
1214e8d8bef9SDimitry Andric // 2) Consider the tentative definition as still undefined (ie the promotion to
1215fe6060f1SDimitry Andric //    a real definition happens only after all symbol resolution is done).
1216fe6060f1SDimitry Andric //    The linker searches archive members for STB_GLOBAL definitions to
1217e8d8bef9SDimitry Andric //    replace the tentative definition with. This is the behavior used by
1218e8d8bef9SDimitry Andric //    GNU ld.
1219e8d8bef9SDimitry Andric //
1220e8d8bef9SDimitry Andric //  The second behavior is inherited from SysVR4, which based it on the FORTRAN
1221fe6060f1SDimitry Andric //  COMMON BLOCK model. This behavior is needed for proper initialization in old
1222e8d8bef9SDimitry Andric //  (pre F90) FORTRAN code that is packaged into an archive.
1223e8d8bef9SDimitry Andric //
1224fe6060f1SDimitry Andric //  The following functions search archive members for definitions to replace
1225fe6060f1SDimitry Andric //  tentative definitions (implementing behavior 2).
1226e8d8bef9SDimitry Andric static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName,
1227e8d8bef9SDimitry Andric                                   StringRef archiveName) {
1228e8d8bef9SDimitry Andric   IRSymtabFile symtabFile = check(readIRSymtab(mb));
1229e8d8bef9SDimitry Andric   for (const irsymtab::Reader::SymbolRef &sym :
1230e8d8bef9SDimitry Andric        symtabFile.TheReader.symbols()) {
1231e8d8bef9SDimitry Andric     if (sym.isGlobal() && sym.getName() == symName)
1232fe6060f1SDimitry Andric       return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon();
1233e8d8bef9SDimitry Andric   }
1234e8d8bef9SDimitry Andric   return false;
1235e8d8bef9SDimitry Andric }
1236e8d8bef9SDimitry Andric 
1237e8d8bef9SDimitry Andric template <class ELFT>
1238e8d8bef9SDimitry Andric static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName,
1239e8d8bef9SDimitry Andric                            StringRef archiveName) {
1240e8d8bef9SDimitry Andric   ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(mb, archiveName);
1241e8d8bef9SDimitry Andric   StringRef stringtable = obj->getStringTable();
1242e8d8bef9SDimitry Andric 
1243e8d8bef9SDimitry Andric   for (auto sym : obj->template getGlobalELFSyms<ELFT>()) {
1244e8d8bef9SDimitry Andric     Expected<StringRef> name = sym.getName(stringtable);
1245e8d8bef9SDimitry Andric     if (name && name.get() == symName)
1246fe6060f1SDimitry Andric       return sym.isDefined() && sym.getBinding() == STB_GLOBAL &&
1247fe6060f1SDimitry Andric              !sym.isCommon();
1248e8d8bef9SDimitry Andric   }
1249e8d8bef9SDimitry Andric   return false;
1250e8d8bef9SDimitry Andric }
1251e8d8bef9SDimitry Andric 
1252e8d8bef9SDimitry Andric static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName,
1253e8d8bef9SDimitry Andric                            StringRef archiveName) {
1254e8d8bef9SDimitry Andric   switch (getELFKind(mb, archiveName)) {
1255e8d8bef9SDimitry Andric   case ELF32LEKind:
1256e8d8bef9SDimitry Andric     return isNonCommonDef<ELF32LE>(mb, symName, archiveName);
1257e8d8bef9SDimitry Andric   case ELF32BEKind:
1258e8d8bef9SDimitry Andric     return isNonCommonDef<ELF32BE>(mb, symName, archiveName);
1259e8d8bef9SDimitry Andric   case ELF64LEKind:
1260e8d8bef9SDimitry Andric     return isNonCommonDef<ELF64LE>(mb, symName, archiveName);
1261e8d8bef9SDimitry Andric   case ELF64BEKind:
1262e8d8bef9SDimitry Andric     return isNonCommonDef<ELF64BE>(mb, symName, archiveName);
1263e8d8bef9SDimitry Andric   default:
1264e8d8bef9SDimitry Andric     llvm_unreachable("getELFKind");
1265e8d8bef9SDimitry Andric   }
1266e8d8bef9SDimitry Andric }
1267e8d8bef9SDimitry Andric 
12684824e7fdSDimitry Andric bool ArchiveFile::shouldExtractForCommon(const Archive::Symbol &sym) {
1269e8d8bef9SDimitry Andric   Archive::Child c =
1270e8d8bef9SDimitry Andric       CHECK(sym.getMember(), toString(this) +
1271e8d8bef9SDimitry Andric                                  ": could not get the member for symbol " +
1272e8d8bef9SDimitry Andric                                  toELFString(sym));
1273e8d8bef9SDimitry Andric   MemoryBufferRef mb =
1274e8d8bef9SDimitry Andric       CHECK(c.getMemoryBufferRef(),
1275e8d8bef9SDimitry Andric             toString(this) +
1276e8d8bef9SDimitry Andric                 ": could not get the buffer for the member defining symbol " +
1277e8d8bef9SDimitry Andric                 toELFString(sym));
1278e8d8bef9SDimitry Andric 
1279e8d8bef9SDimitry Andric   if (isBitcode(mb))
1280e8d8bef9SDimitry Andric     return isBitcodeNonCommonDef(mb, sym.getName(), getName());
1281e8d8bef9SDimitry Andric 
1282e8d8bef9SDimitry Andric   return isNonCommonDef(mb, sym.getName(), getName());
1283e8d8bef9SDimitry Andric }
1284e8d8bef9SDimitry Andric 
12855ffd83dbSDimitry Andric size_t ArchiveFile::getMemberCount() const {
12865ffd83dbSDimitry Andric   size_t count = 0;
12875ffd83dbSDimitry Andric   Error err = Error::success();
12885ffd83dbSDimitry Andric   for (const Archive::Child &c : file->children(err)) {
12895ffd83dbSDimitry Andric     (void)c;
12905ffd83dbSDimitry Andric     ++count;
12915ffd83dbSDimitry Andric   }
12925ffd83dbSDimitry Andric   // This function is used by --print-archive-stats=, where an error does not
12935ffd83dbSDimitry Andric   // really matter.
12945ffd83dbSDimitry Andric   consumeError(std::move(err));
12955ffd83dbSDimitry Andric   return count;
12965ffd83dbSDimitry Andric }
12975ffd83dbSDimitry Andric 
12980b57cec5SDimitry Andric unsigned SharedFile::vernauxNum;
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric // Parse the version definitions in the object file if present, and return a
13010b57cec5SDimitry Andric // vector whose nth element contains a pointer to the Elf_Verdef for version
13020b57cec5SDimitry Andric // identifier n. Version identifiers that are not definitions map to nullptr.
13030b57cec5SDimitry Andric template <typename ELFT>
13040eae32dcSDimitry Andric static SmallVector<const void *, 0>
13050eae32dcSDimitry Andric parseVerdefs(const uint8_t *base, const typename ELFT::Shdr *sec) {
13060b57cec5SDimitry Andric   if (!sec)
13070b57cec5SDimitry Andric     return {};
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric   // Build the Verdefs array by following the chain of Elf_Verdef objects
13100b57cec5SDimitry Andric   // from the start of the .gnu.version_d section.
13110eae32dcSDimitry Andric   SmallVector<const void *, 0> verdefs;
13120b57cec5SDimitry Andric   const uint8_t *verdef = base + sec->sh_offset;
13130eae32dcSDimitry Andric   for (unsigned i = 0, e = sec->sh_info; i != e; ++i) {
13140b57cec5SDimitry Andric     auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
13150b57cec5SDimitry Andric     verdef += curVerdef->vd_next;
13160b57cec5SDimitry Andric     unsigned verdefIndex = curVerdef->vd_ndx;
13170eae32dcSDimitry Andric     if (verdefIndex >= verdefs.size())
13180b57cec5SDimitry Andric       verdefs.resize(verdefIndex + 1);
13190b57cec5SDimitry Andric     verdefs[verdefIndex] = curVerdef;
13200b57cec5SDimitry Andric   }
13210b57cec5SDimitry Andric   return verdefs;
13220b57cec5SDimitry Andric }
13230b57cec5SDimitry Andric 
13245ffd83dbSDimitry Andric // Parse SHT_GNU_verneed to properly set the name of a versioned undefined
13255ffd83dbSDimitry Andric // symbol. We detect fatal issues which would cause vulnerabilities, but do not
13265ffd83dbSDimitry Andric // implement sophisticated error checking like in llvm-readobj because the value
13275ffd83dbSDimitry Andric // of such diagnostics is low.
13285ffd83dbSDimitry Andric template <typename ELFT>
13295ffd83dbSDimitry Andric std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
13305ffd83dbSDimitry Andric                                                const typename ELFT::Shdr *sec) {
13315ffd83dbSDimitry Andric   if (!sec)
13325ffd83dbSDimitry Andric     return {};
13335ffd83dbSDimitry Andric   std::vector<uint32_t> verneeds;
1334e8d8bef9SDimitry Andric   ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(*sec), this);
13355ffd83dbSDimitry Andric   const uint8_t *verneedBuf = data.begin();
13365ffd83dbSDimitry Andric   for (unsigned i = 0; i != sec->sh_info; ++i) {
13375ffd83dbSDimitry Andric     if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end())
13385ffd83dbSDimitry Andric       fatal(toString(this) + " has an invalid Verneed");
13395ffd83dbSDimitry Andric     auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
13405ffd83dbSDimitry Andric     const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
13415ffd83dbSDimitry Andric     for (unsigned j = 0; j != vn->vn_cnt; ++j) {
13425ffd83dbSDimitry Andric       if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end())
13435ffd83dbSDimitry Andric         fatal(toString(this) + " has an invalid Vernaux");
13445ffd83dbSDimitry Andric       auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
13455ffd83dbSDimitry Andric       if (aux->vna_name >= this->stringTable.size())
13465ffd83dbSDimitry Andric         fatal(toString(this) + " has a Vernaux with an invalid vna_name");
13475ffd83dbSDimitry Andric       uint16_t version = aux->vna_other & VERSYM_VERSION;
13485ffd83dbSDimitry Andric       if (version >= verneeds.size())
13495ffd83dbSDimitry Andric         verneeds.resize(version + 1);
13505ffd83dbSDimitry Andric       verneeds[version] = aux->vna_name;
13515ffd83dbSDimitry Andric       vernauxBuf += aux->vna_next;
13525ffd83dbSDimitry Andric     }
13535ffd83dbSDimitry Andric     verneedBuf += vn->vn_next;
13545ffd83dbSDimitry Andric   }
13555ffd83dbSDimitry Andric   return verneeds;
13565ffd83dbSDimitry Andric }
13575ffd83dbSDimitry Andric 
13580b57cec5SDimitry Andric // We do not usually care about alignments of data in shared object
13590b57cec5SDimitry Andric // files because the loader takes care of it. However, if we promote a
13600b57cec5SDimitry Andric // DSO symbol to point to .bss due to copy relocation, we need to keep
13610b57cec5SDimitry Andric // the original alignment requirements. We infer it in this function.
13620b57cec5SDimitry Andric template <typename ELFT>
13630b57cec5SDimitry Andric static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
13640b57cec5SDimitry Andric                              const typename ELFT::Sym &sym) {
13650b57cec5SDimitry Andric   uint64_t ret = UINT64_MAX;
13660b57cec5SDimitry Andric   if (sym.st_value)
13670b57cec5SDimitry Andric     ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
13680b57cec5SDimitry Andric   if (0 < sym.st_shndx && sym.st_shndx < sections.size())
13690b57cec5SDimitry Andric     ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
13700b57cec5SDimitry Andric   return (ret > UINT32_MAX) ? 0 : ret;
13710b57cec5SDimitry Andric }
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric // Fully parse the shared object file.
13740b57cec5SDimitry Andric //
13750b57cec5SDimitry Andric // This function parses symbol versions. If a DSO has version information,
13760b57cec5SDimitry Andric // the file has a ".gnu.version_d" section which contains symbol version
13770b57cec5SDimitry Andric // definitions. Each symbol is associated to one version through a table in
13780b57cec5SDimitry Andric // ".gnu.version" section. That table is a parallel array for the symbol
13790b57cec5SDimitry Andric // table, and each table entry contains an index in ".gnu.version_d".
13800b57cec5SDimitry Andric //
13810b57cec5SDimitry Andric // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
13820b57cec5SDimitry Andric // VER_NDX_GLOBAL. There's no table entry for these special versions in
13830b57cec5SDimitry Andric // ".gnu.version_d".
13840b57cec5SDimitry Andric //
13850b57cec5SDimitry Andric // The file format for symbol versioning is perhaps a bit more complicated
13860b57cec5SDimitry Andric // than necessary, but you can easily understand the code if you wrap your
13870b57cec5SDimitry Andric // head around the data structure described above.
13880b57cec5SDimitry Andric template <class ELFT> void SharedFile::parse() {
13890b57cec5SDimitry Andric   using Elf_Dyn = typename ELFT::Dyn;
13900b57cec5SDimitry Andric   using Elf_Shdr = typename ELFT::Shdr;
13910b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
13920b57cec5SDimitry Andric   using Elf_Verdef = typename ELFT::Verdef;
13930b57cec5SDimitry Andric   using Elf_Versym = typename ELFT::Versym;
13940b57cec5SDimitry Andric 
13950b57cec5SDimitry Andric   ArrayRef<Elf_Dyn> dynamicTags;
13960b57cec5SDimitry Andric   const ELFFile<ELFT> obj = this->getObj<ELFT>();
13970eae32dcSDimitry Andric   ArrayRef<Elf_Shdr> sections = getELFShdrs<ELFT>();
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric   const Elf_Shdr *versymSec = nullptr;
14000b57cec5SDimitry Andric   const Elf_Shdr *verdefSec = nullptr;
14015ffd83dbSDimitry Andric   const Elf_Shdr *verneedSec = nullptr;
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
14040b57cec5SDimitry Andric   for (const Elf_Shdr &sec : sections) {
14050b57cec5SDimitry Andric     switch (sec.sh_type) {
14060b57cec5SDimitry Andric     default:
14070b57cec5SDimitry Andric       continue;
14080b57cec5SDimitry Andric     case SHT_DYNAMIC:
14090b57cec5SDimitry Andric       dynamicTags =
1410e8d8bef9SDimitry Andric           CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this);
14110b57cec5SDimitry Andric       break;
14120b57cec5SDimitry Andric     case SHT_GNU_versym:
14130b57cec5SDimitry Andric       versymSec = &sec;
14140b57cec5SDimitry Andric       break;
14150b57cec5SDimitry Andric     case SHT_GNU_verdef:
14160b57cec5SDimitry Andric       verdefSec = &sec;
14170b57cec5SDimitry Andric       break;
14185ffd83dbSDimitry Andric     case SHT_GNU_verneed:
14195ffd83dbSDimitry Andric       verneedSec = &sec;
14205ffd83dbSDimitry Andric       break;
14210b57cec5SDimitry Andric     }
14220b57cec5SDimitry Andric   }
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric   if (versymSec && numELFSyms == 0) {
14250b57cec5SDimitry Andric     error("SHT_GNU_versym should be associated with symbol table");
14260b57cec5SDimitry Andric     return;
14270b57cec5SDimitry Andric   }
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric   // Search for a DT_SONAME tag to initialize this->soName.
14300b57cec5SDimitry Andric   for (const Elf_Dyn &dyn : dynamicTags) {
14310b57cec5SDimitry Andric     if (dyn.d_tag == DT_NEEDED) {
14320b57cec5SDimitry Andric       uint64_t val = dyn.getVal();
14330b57cec5SDimitry Andric       if (val >= this->stringTable.size())
14340b57cec5SDimitry Andric         fatal(toString(this) + ": invalid DT_NEEDED entry");
14350b57cec5SDimitry Andric       dtNeeded.push_back(this->stringTable.data() + val);
14360b57cec5SDimitry Andric     } else if (dyn.d_tag == DT_SONAME) {
14370b57cec5SDimitry Andric       uint64_t val = dyn.getVal();
14380b57cec5SDimitry Andric       if (val >= this->stringTable.size())
14390b57cec5SDimitry Andric         fatal(toString(this) + ": invalid DT_SONAME entry");
14400b57cec5SDimitry Andric       soName = this->stringTable.data() + val;
14410b57cec5SDimitry Andric     }
14420b57cec5SDimitry Andric   }
14430b57cec5SDimitry Andric 
14440b57cec5SDimitry Andric   // DSOs are uniquified not by filename but by soname.
144504eeddc0SDimitry Andric   DenseMap<CachedHashStringRef, SharedFile *>::iterator it;
14460b57cec5SDimitry Andric   bool wasInserted;
144704eeddc0SDimitry Andric   std::tie(it, wasInserted) =
144804eeddc0SDimitry Andric       symtab->soNames.try_emplace(CachedHashStringRef(soName), this);
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric   // If a DSO appears more than once on the command line with and without
14510b57cec5SDimitry Andric   // --as-needed, --no-as-needed takes precedence over --as-needed because a
14520b57cec5SDimitry Andric   // user can add an extra DSO with --no-as-needed to force it to be added to
14530b57cec5SDimitry Andric   // the dependency list.
14540b57cec5SDimitry Andric   it->second->isNeeded |= isNeeded;
14550b57cec5SDimitry Andric   if (!wasInserted)
14560b57cec5SDimitry Andric     return;
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric   sharedFiles.push_back(this);
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
14615ffd83dbSDimitry Andric   std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric   // Parse ".gnu.version" section which is a parallel array for the symbol
14640b57cec5SDimitry Andric   // table. If a given file doesn't have a ".gnu.version" section, we use
14650b57cec5SDimitry Andric   // VER_NDX_GLOBAL.
14660b57cec5SDimitry Andric   size_t size = numELFSyms - firstGlobal;
14675ffd83dbSDimitry Andric   std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
14680b57cec5SDimitry Andric   if (versymSec) {
14690b57cec5SDimitry Andric     ArrayRef<Elf_Versym> versym =
1470e8d8bef9SDimitry Andric         CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec),
14710b57cec5SDimitry Andric               this)
14720b57cec5SDimitry Andric             .slice(firstGlobal);
14730b57cec5SDimitry Andric     for (size_t i = 0; i < size; ++i)
14740b57cec5SDimitry Andric       versyms[i] = versym[i].vs_index;
14750b57cec5SDimitry Andric   }
14760b57cec5SDimitry Andric 
14770b57cec5SDimitry Andric   // System libraries can have a lot of symbols with versions. Using a
14780b57cec5SDimitry Andric   // fixed buffer for computing the versions name (foo@ver) can save a
14790b57cec5SDimitry Andric   // lot of allocations.
14800b57cec5SDimitry Andric   SmallString<0> versionedNameBuffer;
14810b57cec5SDimitry Andric 
14820b57cec5SDimitry Andric   // Add symbols to the symbol table.
14830eae32dcSDimitry Andric   SymbolTable &symtab = *elf::symtab;
14840b57cec5SDimitry Andric   ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
14850eae32dcSDimitry Andric   for (size_t i = 0, e = syms.size(); i != e; ++i) {
14860b57cec5SDimitry Andric     const Elf_Sym &sym = syms[i];
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric     // ELF spec requires that all local symbols precede weak or global
14890b57cec5SDimitry Andric     // symbols in each symbol table, and the index of first non-local symbol
14900b57cec5SDimitry Andric     // is stored to sh_info. If a local symbol appears after some non-local
14910b57cec5SDimitry Andric     // symbol, that's a violation of the spec.
14920eae32dcSDimitry Andric     StringRef name = CHECK(sym.getName(stringTable), this);
14930b57cec5SDimitry Andric     if (sym.getBinding() == STB_LOCAL) {
14940b57cec5SDimitry Andric       warn("found local symbol '" + name +
14950b57cec5SDimitry Andric            "' in global part of symbol table in file " + toString(this));
14960b57cec5SDimitry Andric       continue;
14970b57cec5SDimitry Andric     }
14980b57cec5SDimitry Andric 
14995ffd83dbSDimitry Andric     uint16_t idx = versyms[i] & ~VERSYM_HIDDEN;
15000b57cec5SDimitry Andric     if (sym.isUndefined()) {
15015ffd83dbSDimitry Andric       // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but
15025ffd83dbSDimitry Andric       // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL.
15035ffd83dbSDimitry Andric       if (idx != VER_NDX_LOCAL && idx != VER_NDX_GLOBAL) {
15045ffd83dbSDimitry Andric         if (idx >= verneeds.size()) {
15055ffd83dbSDimitry Andric           error("corrupt input file: version need index " + Twine(idx) +
15065ffd83dbSDimitry Andric                 " for symbol " + name + " is out of bounds\n>>> defined in " +
15075ffd83dbSDimitry Andric                 toString(this));
15085ffd83dbSDimitry Andric           continue;
15095ffd83dbSDimitry Andric         }
15100eae32dcSDimitry Andric         StringRef verName = stringTable.data() + verneeds[idx];
15115ffd83dbSDimitry Andric         versionedNameBuffer.clear();
151204eeddc0SDimitry Andric         name = saver().save(
151304eeddc0SDimitry Andric             (name + "@" + verName).toStringRef(versionedNameBuffer));
15145ffd83dbSDimitry Andric       }
15150eae32dcSDimitry Andric       Symbol *s = symtab.addSymbol(
15160b57cec5SDimitry Andric           Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
15170b57cec5SDimitry Andric       s->exportDynamic = true;
15180eae32dcSDimitry Andric       if (s->isUndefined() && sym.getBinding() != STB_WEAK &&
1519fe6060f1SDimitry Andric           config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore)
1520fe6060f1SDimitry Andric         requiredSymbols.push_back(s);
15210b57cec5SDimitry Andric       continue;
15220b57cec5SDimitry Andric     }
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric     // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
15250b57cec5SDimitry Andric     // assigns VER_NDX_LOCAL to this section global symbol. Here is a
15260b57cec5SDimitry Andric     // workaround for this bug.
15270b57cec5SDimitry Andric     if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL &&
15280b57cec5SDimitry Andric         name == "_gp_disp")
15290b57cec5SDimitry Andric       continue;
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric     uint32_t alignment = getAlignment<ELFT>(sections, sym);
15320b57cec5SDimitry Andric     if (!(versyms[i] & VERSYM_HIDDEN)) {
15330eae32dcSDimitry Andric       symtab.addSymbol(SharedSymbol{*this, name, sym.getBinding(), sym.st_other,
15340eae32dcSDimitry Andric                                     sym.getType(), sym.st_value, sym.st_size,
15350eae32dcSDimitry Andric                                     alignment, idx});
15360b57cec5SDimitry Andric     }
15370b57cec5SDimitry Andric 
15380b57cec5SDimitry Andric     // Also add the symbol with the versioned name to handle undefined symbols
15390b57cec5SDimitry Andric     // with explicit versions.
15400b57cec5SDimitry Andric     if (idx == VER_NDX_GLOBAL)
15410b57cec5SDimitry Andric       continue;
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric     if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) {
15440b57cec5SDimitry Andric       error("corrupt input file: version definition index " + Twine(idx) +
15450b57cec5SDimitry Andric             " for symbol " + name + " is out of bounds\n>>> defined in " +
15460b57cec5SDimitry Andric             toString(this));
15470b57cec5SDimitry Andric       continue;
15480b57cec5SDimitry Andric     }
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric     StringRef verName =
15510eae32dcSDimitry Andric         stringTable.data() +
15520b57cec5SDimitry Andric         reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
15530b57cec5SDimitry Andric     versionedNameBuffer.clear();
15540b57cec5SDimitry Andric     name = (name + "@" + verName).toStringRef(versionedNameBuffer);
155504eeddc0SDimitry Andric     symtab.addSymbol(SharedSymbol{*this, saver().save(name), sym.getBinding(),
15560b57cec5SDimitry Andric                                   sym.st_other, sym.getType(), sym.st_value,
15570b57cec5SDimitry Andric                                   sym.st_size, alignment, idx});
15580b57cec5SDimitry Andric   }
15590b57cec5SDimitry Andric }
15600b57cec5SDimitry Andric 
15610b57cec5SDimitry Andric static ELFKind getBitcodeELFKind(const Triple &t) {
15620b57cec5SDimitry Andric   if (t.isLittleEndian())
15630b57cec5SDimitry Andric     return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
15640b57cec5SDimitry Andric   return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
15650b57cec5SDimitry Andric }
15660b57cec5SDimitry Andric 
1567e8d8bef9SDimitry Andric static uint16_t getBitcodeMachineKind(StringRef path, const Triple &t) {
15680b57cec5SDimitry Andric   switch (t.getArch()) {
15690b57cec5SDimitry Andric   case Triple::aarch64:
1570fe6060f1SDimitry Andric   case Triple::aarch64_be:
15710b57cec5SDimitry Andric     return EM_AARCH64;
15720b57cec5SDimitry Andric   case Triple::amdgcn:
15730b57cec5SDimitry Andric   case Triple::r600:
15740b57cec5SDimitry Andric     return EM_AMDGPU;
15750b57cec5SDimitry Andric   case Triple::arm:
15760b57cec5SDimitry Andric   case Triple::thumb:
15770b57cec5SDimitry Andric     return EM_ARM;
15780b57cec5SDimitry Andric   case Triple::avr:
15790b57cec5SDimitry Andric     return EM_AVR;
1580349cc55cSDimitry Andric   case Triple::hexagon:
1581349cc55cSDimitry Andric     return EM_HEXAGON;
15820b57cec5SDimitry Andric   case Triple::mips:
15830b57cec5SDimitry Andric   case Triple::mipsel:
15840b57cec5SDimitry Andric   case Triple::mips64:
15850b57cec5SDimitry Andric   case Triple::mips64el:
15860b57cec5SDimitry Andric     return EM_MIPS;
15870b57cec5SDimitry Andric   case Triple::msp430:
15880b57cec5SDimitry Andric     return EM_MSP430;
15890b57cec5SDimitry Andric   case Triple::ppc:
1590e8d8bef9SDimitry Andric   case Triple::ppcle:
15910b57cec5SDimitry Andric     return EM_PPC;
15920b57cec5SDimitry Andric   case Triple::ppc64:
15930b57cec5SDimitry Andric   case Triple::ppc64le:
15940b57cec5SDimitry Andric     return EM_PPC64;
15950b57cec5SDimitry Andric   case Triple::riscv32:
15960b57cec5SDimitry Andric   case Triple::riscv64:
15970b57cec5SDimitry Andric     return EM_RISCV;
15980b57cec5SDimitry Andric   case Triple::x86:
15990b57cec5SDimitry Andric     return t.isOSIAMCU() ? EM_IAMCU : EM_386;
16000b57cec5SDimitry Andric   case Triple::x86_64:
16010b57cec5SDimitry Andric     return EM_X86_64;
16020b57cec5SDimitry Andric   default:
16030b57cec5SDimitry Andric     error(path + ": could not infer e_machine from bitcode target triple " +
16040b57cec5SDimitry Andric           t.str());
16050b57cec5SDimitry Andric     return EM_NONE;
16060b57cec5SDimitry Andric   }
16070b57cec5SDimitry Andric }
16080b57cec5SDimitry Andric 
1609e8d8bef9SDimitry Andric static uint8_t getOsAbi(const Triple &t) {
1610e8d8bef9SDimitry Andric   switch (t.getOS()) {
1611e8d8bef9SDimitry Andric   case Triple::AMDHSA:
1612e8d8bef9SDimitry Andric     return ELF::ELFOSABI_AMDGPU_HSA;
1613e8d8bef9SDimitry Andric   case Triple::AMDPAL:
1614e8d8bef9SDimitry Andric     return ELF::ELFOSABI_AMDGPU_PAL;
1615e8d8bef9SDimitry Andric   case Triple::Mesa3D:
1616e8d8bef9SDimitry Andric     return ELF::ELFOSABI_AMDGPU_MESA3D;
1617e8d8bef9SDimitry Andric   default:
1618e8d8bef9SDimitry Andric     return ELF::ELFOSABI_NONE;
1619e8d8bef9SDimitry Andric   }
1620e8d8bef9SDimitry Andric }
1621e8d8bef9SDimitry Andric 
16220b57cec5SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
16230eae32dcSDimitry Andric                          uint64_t offsetInArchive, bool lazy)
16240b57cec5SDimitry Andric     : InputFile(BitcodeKind, mb) {
16250eae32dcSDimitry Andric   this->archiveName = archiveName;
16260eae32dcSDimitry Andric   this->lazy = lazy;
16270b57cec5SDimitry Andric 
16280b57cec5SDimitry Andric   std::string path = mb.getBufferIdentifier().str();
16290b57cec5SDimitry Andric   if (config->thinLTOIndexOnly)
16300b57cec5SDimitry Andric     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
16310b57cec5SDimitry Andric 
16320b57cec5SDimitry Andric   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
16330b57cec5SDimitry Andric   // name. If two archives define two members with the same name, this
16340b57cec5SDimitry Andric   // causes a collision which result in only one of the objects being taken
16350b57cec5SDimitry Andric   // into consideration at LTO time (which very likely causes undefined
16360b57cec5SDimitry Andric   // symbols later in the link stage). So we append file offset to make
16370b57cec5SDimitry Andric   // filename unique.
163804eeddc0SDimitry Andric   StringRef name = archiveName.empty()
163904eeddc0SDimitry Andric                        ? saver().save(path)
164004eeddc0SDimitry Andric                        : saver().save(archiveName + "(" + path::filename(path) +
164104eeddc0SDimitry Andric                                       " at " + utostr(offsetInArchive) + ")");
16420b57cec5SDimitry Andric   MemoryBufferRef mbref(mb.getBuffer(), name);
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric   obj = CHECK(lto::InputFile::create(mbref), this);
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric   Triple t(obj->getTargetTriple());
16470b57cec5SDimitry Andric   ekind = getBitcodeELFKind(t);
16480b57cec5SDimitry Andric   emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t);
1649e8d8bef9SDimitry Andric   osabi = getOsAbi(t);
16500b57cec5SDimitry Andric }
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
16530b57cec5SDimitry Andric   switch (gvVisibility) {
16540b57cec5SDimitry Andric   case GlobalValue::DefaultVisibility:
16550b57cec5SDimitry Andric     return STV_DEFAULT;
16560b57cec5SDimitry Andric   case GlobalValue::HiddenVisibility:
16570b57cec5SDimitry Andric     return STV_HIDDEN;
16580b57cec5SDimitry Andric   case GlobalValue::ProtectedVisibility:
16590b57cec5SDimitry Andric     return STV_PROTECTED;
16600b57cec5SDimitry Andric   }
16610b57cec5SDimitry Andric   llvm_unreachable("unknown visibility");
16620b57cec5SDimitry Andric }
16630b57cec5SDimitry Andric 
16640b57cec5SDimitry Andric template <class ELFT>
166504eeddc0SDimitry Andric static void
166604eeddc0SDimitry Andric createBitcodeSymbol(Symbol *&sym, const std::vector<bool> &keptComdats,
166704eeddc0SDimitry Andric                     const lto::InputFile::Symbol &objSym, BitcodeFile &f) {
16680b57cec5SDimitry Andric   uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
16690b57cec5SDimitry Andric   uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
16700b57cec5SDimitry Andric   uint8_t visibility = mapVisibility(objSym.getVisibility());
16710b57cec5SDimitry Andric   bool canOmitFromDynSym = objSym.canBeOmittedFromSymbolTable();
16720b57cec5SDimitry Andric 
167304eeddc0SDimitry Andric   StringRef name;
167404eeddc0SDimitry Andric   if (sym) {
167504eeddc0SDimitry Andric     name = sym->getName();
167604eeddc0SDimitry Andric   } else {
167704eeddc0SDimitry Andric     name = saver().save(objSym.getName());
167804eeddc0SDimitry Andric     sym = symtab->insert(name);
167904eeddc0SDimitry Andric   }
168004eeddc0SDimitry Andric 
16810b57cec5SDimitry Andric   int c = objSym.getComdatIndex();
16820b57cec5SDimitry Andric   if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) {
168385868e8aSDimitry Andric     Undefined newSym(&f, name, binding, visibility, type);
16840b57cec5SDimitry Andric     if (canOmitFromDynSym)
168585868e8aSDimitry Andric       newSym.exportDynamic = false;
168604eeddc0SDimitry Andric     sym->resolve(newSym);
168704eeddc0SDimitry Andric     sym->referenced = true;
168804eeddc0SDimitry Andric     return;
16890b57cec5SDimitry Andric   }
16900b57cec5SDimitry Andric 
169104eeddc0SDimitry Andric   if (objSym.isCommon()) {
169204eeddc0SDimitry Andric     sym->resolve(CommonSymbol{&f, name, binding, visibility, STT_OBJECT,
169304eeddc0SDimitry Andric                               objSym.getCommonAlignment(),
169404eeddc0SDimitry Andric                               objSym.getCommonSize()});
169504eeddc0SDimitry Andric   } else {
169685868e8aSDimitry Andric     Defined newSym(&f, name, binding, visibility, type, 0, 0, nullptr);
16970b57cec5SDimitry Andric     if (canOmitFromDynSym)
169885868e8aSDimitry Andric       newSym.exportDynamic = false;
169904eeddc0SDimitry Andric     sym->resolve(newSym);
170004eeddc0SDimitry Andric   }
17010b57cec5SDimitry Andric }
17020b57cec5SDimitry Andric 
17030b57cec5SDimitry Andric template <class ELFT> void BitcodeFile::parse() {
17040b57cec5SDimitry Andric   std::vector<bool> keptComdats;
1705fe6060f1SDimitry Andric   for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) {
17060b57cec5SDimitry Andric     keptComdats.push_back(
1707fe6060f1SDimitry Andric         s.second == Comdat::NoDeduplicate ||
1708fe6060f1SDimitry Andric         symtab->comdatGroups.try_emplace(CachedHashStringRef(s.first), this)
1709fe6060f1SDimitry Andric             .second);
1710fe6060f1SDimitry Andric   }
17110b57cec5SDimitry Andric 
171204eeddc0SDimitry Andric   symbols.resize(obj->symbols().size());
171304eeddc0SDimitry Andric   for (auto it : llvm::enumerate(obj->symbols())) {
171404eeddc0SDimitry Andric     Symbol *&sym = symbols[it.index()];
171504eeddc0SDimitry Andric     createBitcodeSymbol<ELFT>(sym, keptComdats, it.value(), *this);
171604eeddc0SDimitry Andric   }
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   for (auto l : obj->getDependentLibraries())
17190b57cec5SDimitry Andric     addDependentLibrary(l, this);
17200b57cec5SDimitry Andric }
17210b57cec5SDimitry Andric 
17220eae32dcSDimitry Andric void BitcodeFile::parseLazy() {
17230eae32dcSDimitry Andric   SymbolTable &symtab = *elf::symtab;
172404eeddc0SDimitry Andric   symbols.resize(obj->symbols().size());
172504eeddc0SDimitry Andric   for (auto it : llvm::enumerate(obj->symbols()))
172604eeddc0SDimitry Andric     if (!it.value().isUndefined())
172704eeddc0SDimitry Andric       symbols[it.index()] = symtab.addSymbol(
172804eeddc0SDimitry Andric           LazyObject{*this, saver().save(it.value().getName())});
17290eae32dcSDimitry Andric }
17300eae32dcSDimitry Andric 
17310b57cec5SDimitry Andric void BinaryFile::parse() {
17320b57cec5SDimitry Andric   ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
17330b57cec5SDimitry Andric   auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
17340b57cec5SDimitry Andric                                      8, data, ".data");
17350b57cec5SDimitry Andric   sections.push_back(section);
17360b57cec5SDimitry Andric 
17370b57cec5SDimitry Andric   // For each input file foo that is embedded to a result as a binary
17380b57cec5SDimitry Andric   // blob, we define _binary_foo_{start,end,size} symbols, so that
17390b57cec5SDimitry Andric   // user programs can access blobs by name. Non-alphanumeric
17400b57cec5SDimitry Andric   // characters in a filename are replaced with underscore.
17410b57cec5SDimitry Andric   std::string s = "_binary_" + mb.getBufferIdentifier().str();
17420b57cec5SDimitry Andric   for (size_t i = 0; i < s.size(); ++i)
17430b57cec5SDimitry Andric     if (!isAlnum(s[i]))
17440b57cec5SDimitry Andric       s[i] = '_';
17450b57cec5SDimitry Andric 
174604eeddc0SDimitry Andric   llvm::StringSaver &saver = lld::saver();
174704eeddc0SDimitry Andric 
17480b57cec5SDimitry Andric   symtab->addSymbol(Defined{nullptr, saver.save(s + "_start"), STB_GLOBAL,
17490b57cec5SDimitry Andric                             STV_DEFAULT, STT_OBJECT, 0, 0, section});
17500b57cec5SDimitry Andric   symtab->addSymbol(Defined{nullptr, saver.save(s + "_end"), STB_GLOBAL,
17510b57cec5SDimitry Andric                             STV_DEFAULT, STT_OBJECT, data.size(), 0, section});
17520b57cec5SDimitry Andric   symtab->addSymbol(Defined{nullptr, saver.save(s + "_size"), STB_GLOBAL,
17530b57cec5SDimitry Andric                             STV_DEFAULT, STT_OBJECT, data.size(), 0, nullptr});
17540b57cec5SDimitry Andric }
17550b57cec5SDimitry Andric 
17565ffd83dbSDimitry Andric InputFile *elf::createObjectFile(MemoryBufferRef mb, StringRef archiveName,
17570b57cec5SDimitry Andric                                  uint64_t offsetInArchive) {
17580b57cec5SDimitry Andric   if (isBitcode(mb))
17590eae32dcSDimitry Andric     return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/false);
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric   switch (getELFKind(mb, archiveName)) {
17620b57cec5SDimitry Andric   case ELF32LEKind:
17630b57cec5SDimitry Andric     return make<ObjFile<ELF32LE>>(mb, archiveName);
17640b57cec5SDimitry Andric   case ELF32BEKind:
17650b57cec5SDimitry Andric     return make<ObjFile<ELF32BE>>(mb, archiveName);
17660b57cec5SDimitry Andric   case ELF64LEKind:
17670b57cec5SDimitry Andric     return make<ObjFile<ELF64LE>>(mb, archiveName);
17680b57cec5SDimitry Andric   case ELF64BEKind:
17690b57cec5SDimitry Andric     return make<ObjFile<ELF64BE>>(mb, archiveName);
17700b57cec5SDimitry Andric   default:
17710b57cec5SDimitry Andric     llvm_unreachable("getELFKind");
17720b57cec5SDimitry Andric   }
17730b57cec5SDimitry Andric }
17740b57cec5SDimitry Andric 
17750eae32dcSDimitry Andric InputFile *elf::createLazyFile(MemoryBufferRef mb, StringRef archiveName,
17760eae32dcSDimitry Andric                                uint64_t offsetInArchive) {
17770eae32dcSDimitry Andric   if (isBitcode(mb))
17780eae32dcSDimitry Andric     return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/true);
17790b57cec5SDimitry Andric 
17800eae32dcSDimitry Andric   auto *file =
17810eae32dcSDimitry Andric       cast<ELFFileBase>(createObjectFile(mb, archiveName, offsetInArchive));
17820eae32dcSDimitry Andric   file->lazy = true;
17830eae32dcSDimitry Andric   return file;
17840b57cec5SDimitry Andric }
17850b57cec5SDimitry Andric 
17860eae32dcSDimitry Andric template <class ELFT> void ObjFile<ELFT>::parseLazy() {
17870eae32dcSDimitry Andric   const ArrayRef<typename ELFT::Sym> eSyms = this->getELFSyms<ELFT>();
17880eae32dcSDimitry Andric   SymbolTable &symtab = *elf::symtab;
17890b57cec5SDimitry Andric 
17900eae32dcSDimitry Andric   symbols.resize(eSyms.size());
17910b57cec5SDimitry Andric   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
17920b57cec5SDimitry Andric     if (eSyms[i].st_shndx != SHN_UNDEF)
17930eae32dcSDimitry Andric       symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this));
17940b57cec5SDimitry Andric 
17950b57cec5SDimitry Andric   // Replace existing symbols with LazyObject symbols.
17960b57cec5SDimitry Andric   //
17970eae32dcSDimitry Andric   // resolve() may trigger this->extract() if an existing symbol is an undefined
17980eae32dcSDimitry Andric   // symbol. If that happens, this function has served its purpose, and we can
17990eae32dcSDimitry Andric   // exit from the loop early.
18000eae32dcSDimitry Andric   for (Symbol *sym : makeArrayRef(symbols).slice(firstGlobal))
18010eae32dcSDimitry Andric     if (sym) {
18020b57cec5SDimitry Andric       sym->resolve(LazyObject{*this, sym->getName()});
18030eae32dcSDimitry Andric       if (!lazy)
18040b57cec5SDimitry Andric         return;
18050b57cec5SDimitry Andric     }
18060b57cec5SDimitry Andric }
18070b57cec5SDimitry Andric 
18080eae32dcSDimitry Andric bool InputFile::shouldExtractForCommon(StringRef name) {
1809e8d8bef9SDimitry Andric   if (isBitcode(mb))
1810e8d8bef9SDimitry Andric     return isBitcodeNonCommonDef(mb, name, archiveName);
1811e8d8bef9SDimitry Andric 
1812e8d8bef9SDimitry Andric   return isNonCommonDef(mb, name, archiveName);
1813e8d8bef9SDimitry Andric }
1814e8d8bef9SDimitry Andric 
18155ffd83dbSDimitry Andric std::string elf::replaceThinLTOSuffix(StringRef path) {
18160b57cec5SDimitry Andric   StringRef suffix = config->thinLTOObjectSuffixReplace.first;
18170b57cec5SDimitry Andric   StringRef repl = config->thinLTOObjectSuffixReplace.second;
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   if (path.consume_back(suffix))
18200b57cec5SDimitry Andric     return (path + repl).str();
18215ffd83dbSDimitry Andric   return std::string(path);
18220b57cec5SDimitry Andric }
18230b57cec5SDimitry Andric 
18240b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32LE>();
18250b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32BE>();
18260b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64LE>();
18270b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64BE>();
18280b57cec5SDimitry Andric 
18295ffd83dbSDimitry Andric template class elf::ObjFile<ELF32LE>;
18305ffd83dbSDimitry Andric template class elf::ObjFile<ELF32BE>;
18315ffd83dbSDimitry Andric template class elf::ObjFile<ELF64LE>;
18325ffd83dbSDimitry Andric template class elf::ObjFile<ELF64BE>;
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric template void SharedFile::parse<ELF32LE>();
18350b57cec5SDimitry Andric template void SharedFile::parse<ELF32BE>();
18360b57cec5SDimitry Andric template void SharedFile::parse<ELF64LE>();
18370b57cec5SDimitry Andric template void SharedFile::parse<ELF64BE>();
1838