xref: /freebsd/contrib/llvm-project/lld/ELF/InputFiles.cpp (revision 85868e8a1daeaae7a0e48effb2ea2310ae3b02c6)
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"
160b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h"
170b57cec5SDimitry Andric #include "lld/Common/Memory.h"
180b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/Analysis.h"
200b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
210b57cec5SDimitry Andric #include "llvm/IR/Module.h"
220b57cec5SDimitry Andric #include "llvm/LTO/LTO.h"
230b57cec5SDimitry Andric #include "llvm/MC/StringTableBuilder.h"
240b57cec5SDimitry Andric #include "llvm/Object/ELFObjectFile.h"
250b57cec5SDimitry Andric #include "llvm/Support/ARMAttributeParser.h"
260b57cec5SDimitry Andric #include "llvm/Support/ARMBuildAttributes.h"
270b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
280b57cec5SDimitry Andric #include "llvm/Support/Path.h"
290b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h"
300b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
310b57cec5SDimitry Andric 
320b57cec5SDimitry Andric using namespace llvm;
330b57cec5SDimitry Andric using namespace llvm::ELF;
340b57cec5SDimitry Andric using namespace llvm::object;
350b57cec5SDimitry Andric using namespace llvm::sys;
360b57cec5SDimitry Andric using namespace llvm::sys::fs;
370b57cec5SDimitry Andric using namespace llvm::support::endian;
380b57cec5SDimitry Andric 
39*85868e8aSDimitry Andric namespace lld {
40*85868e8aSDimitry Andric // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
41*85868e8aSDimitry Andric std::string toString(const elf::InputFile *f) {
42*85868e8aSDimitry Andric   if (!f)
43*85868e8aSDimitry Andric     return "<internal>";
440b57cec5SDimitry Andric 
45*85868e8aSDimitry Andric   if (f->toStringCache.empty()) {
46*85868e8aSDimitry Andric     if (f->archiveName.empty())
47*85868e8aSDimitry Andric       f->toStringCache = f->getName();
48*85868e8aSDimitry Andric     else
49*85868e8aSDimitry Andric       f->toStringCache = (f->archiveName + "(" + f->getName() + ")").str();
50*85868e8aSDimitry Andric   }
51*85868e8aSDimitry Andric   return f->toStringCache;
52*85868e8aSDimitry Andric }
53*85868e8aSDimitry Andric 
54*85868e8aSDimitry Andric namespace elf {
550b57cec5SDimitry Andric bool InputFile::isInGroup;
560b57cec5SDimitry Andric uint32_t InputFile::nextGroupId;
57*85868e8aSDimitry Andric std::vector<BinaryFile *> binaryFiles;
58*85868e8aSDimitry Andric std::vector<BitcodeFile *> bitcodeFiles;
59*85868e8aSDimitry Andric std::vector<LazyObjFile *> lazyObjFiles;
60*85868e8aSDimitry Andric std::vector<InputFile *> objectFiles;
61*85868e8aSDimitry Andric std::vector<SharedFile *> sharedFiles;
620b57cec5SDimitry Andric 
63*85868e8aSDimitry Andric std::unique_ptr<TarWriter> tar;
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) {
660b57cec5SDimitry Andric   unsigned char size;
670b57cec5SDimitry Andric   unsigned char endian;
680b57cec5SDimitry Andric   std::tie(size, endian) = getElfArchType(mb.getBuffer());
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric   auto report = [&](StringRef msg) {
710b57cec5SDimitry Andric     StringRef filename = mb.getBufferIdentifier();
720b57cec5SDimitry Andric     if (archiveName.empty())
730b57cec5SDimitry Andric       fatal(filename + ": " + msg);
740b57cec5SDimitry Andric     else
750b57cec5SDimitry Andric       fatal(archiveName + "(" + filename + "): " + msg);
760b57cec5SDimitry Andric   };
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric   if (!mb.getBuffer().startswith(ElfMagic))
790b57cec5SDimitry Andric     report("not an ELF file");
800b57cec5SDimitry Andric   if (endian != ELFDATA2LSB && endian != ELFDATA2MSB)
810b57cec5SDimitry Andric     report("corrupted ELF file: invalid data encoding");
820b57cec5SDimitry Andric   if (size != ELFCLASS32 && size != ELFCLASS64)
830b57cec5SDimitry Andric     report("corrupted ELF file: invalid file class");
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric   size_t bufSize = mb.getBuffer().size();
860b57cec5SDimitry Andric   if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) ||
870b57cec5SDimitry Andric       (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr)))
880b57cec5SDimitry Andric     report("corrupted ELF file: file is too short");
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric   if (size == ELFCLASS32)
910b57cec5SDimitry Andric     return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
920b57cec5SDimitry Andric   return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
930b57cec5SDimitry Andric }
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric InputFile::InputFile(Kind k, MemoryBufferRef m)
960b57cec5SDimitry Andric     : mb(m), groupId(nextGroupId), fileKind(k) {
970b57cec5SDimitry Andric   // All files within the same --{start,end}-group get the same group ID.
980b57cec5SDimitry Andric   // Otherwise, a new file will get a new group ID.
990b57cec5SDimitry Andric   if (!isInGroup)
1000b57cec5SDimitry Andric     ++nextGroupId;
1010b57cec5SDimitry Andric }
1020b57cec5SDimitry Andric 
103*85868e8aSDimitry Andric Optional<MemoryBufferRef> readFile(StringRef path) {
1040b57cec5SDimitry Andric   // The --chroot option changes our virtual root directory.
1050b57cec5SDimitry Andric   // This is useful when you are dealing with files created by --reproduce.
1060b57cec5SDimitry Andric   if (!config->chroot.empty() && path.startswith("/"))
1070b57cec5SDimitry Andric     path = saver.save(config->chroot + path);
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric   log(path);
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric   auto mbOrErr = MemoryBuffer::getFile(path, -1, false);
1120b57cec5SDimitry Andric   if (auto ec = mbOrErr.getError()) {
1130b57cec5SDimitry Andric     error("cannot open " + path + ": " + ec.message());
1140b57cec5SDimitry Andric     return None;
1150b57cec5SDimitry Andric   }
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
1180b57cec5SDimitry Andric   MemoryBufferRef mbref = mb->getMemBufferRef();
1190b57cec5SDimitry Andric   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   if (tar)
1220b57cec5SDimitry Andric     tar->append(relativeToRoot(path), mbref.getBuffer());
1230b57cec5SDimitry Andric   return mbref;
1240b57cec5SDimitry Andric }
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric // All input object files must be for the same architecture
1270b57cec5SDimitry Andric // (e.g. it does not make sense to link x86 object files with
1280b57cec5SDimitry Andric // MIPS object files.) This function checks for that error.
1290b57cec5SDimitry Andric static bool isCompatible(InputFile *file) {
1300b57cec5SDimitry Andric   if (!file->isElf() && !isa<BitcodeFile>(file))
1310b57cec5SDimitry Andric     return true;
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   if (file->ekind == config->ekind && file->emachine == config->emachine) {
1340b57cec5SDimitry Andric     if (config->emachine != EM_MIPS)
1350b57cec5SDimitry Andric       return true;
1360b57cec5SDimitry Andric     if (isMipsN32Abi(file) == config->mipsN32Abi)
1370b57cec5SDimitry Andric       return true;
1380b57cec5SDimitry Andric   }
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric   if (!config->emulation.empty()) {
1410b57cec5SDimitry Andric     error(toString(file) + " is incompatible with " + config->emulation);
142*85868e8aSDimitry Andric     return false;
143*85868e8aSDimitry Andric   }
144*85868e8aSDimitry Andric 
1450b57cec5SDimitry Andric   InputFile *existing;
1460b57cec5SDimitry Andric   if (!objectFiles.empty())
1470b57cec5SDimitry Andric     existing = objectFiles[0];
1480b57cec5SDimitry Andric   else if (!sharedFiles.empty())
1490b57cec5SDimitry Andric     existing = sharedFiles[0];
1500b57cec5SDimitry Andric   else
1510b57cec5SDimitry Andric     existing = bitcodeFiles[0];
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   error(toString(file) + " is incompatible with " + toString(existing));
1540b57cec5SDimitry Andric   return false;
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric template <class ELFT> static void doParseFile(InputFile *file) {
1580b57cec5SDimitry Andric   if (!isCompatible(file))
1590b57cec5SDimitry Andric     return;
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   // Binary file
1620b57cec5SDimitry Andric   if (auto *f = dyn_cast<BinaryFile>(file)) {
1630b57cec5SDimitry Andric     binaryFiles.push_back(f);
1640b57cec5SDimitry Andric     f->parse();
1650b57cec5SDimitry Andric     return;
1660b57cec5SDimitry Andric   }
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   // .a file
1690b57cec5SDimitry Andric   if (auto *f = dyn_cast<ArchiveFile>(file)) {
1700b57cec5SDimitry Andric     f->parse();
1710b57cec5SDimitry Andric     return;
1720b57cec5SDimitry Andric   }
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   // Lazy object file
1750b57cec5SDimitry Andric   if (auto *f = dyn_cast<LazyObjFile>(file)) {
1760b57cec5SDimitry Andric     lazyObjFiles.push_back(f);
1770b57cec5SDimitry Andric     f->parse<ELFT>();
1780b57cec5SDimitry Andric     return;
1790b57cec5SDimitry Andric   }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   if (config->trace)
1820b57cec5SDimitry Andric     message(toString(file));
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   // .so file
1850b57cec5SDimitry Andric   if (auto *f = dyn_cast<SharedFile>(file)) {
1860b57cec5SDimitry Andric     f->parse<ELFT>();
1870b57cec5SDimitry Andric     return;
1880b57cec5SDimitry Andric   }
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   // LLVM bitcode file
1910b57cec5SDimitry Andric   if (auto *f = dyn_cast<BitcodeFile>(file)) {
1920b57cec5SDimitry Andric     bitcodeFiles.push_back(f);
1930b57cec5SDimitry Andric     f->parse<ELFT>();
1940b57cec5SDimitry Andric     return;
1950b57cec5SDimitry Andric   }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   // Regular object file
1980b57cec5SDimitry Andric   objectFiles.push_back(file);
1990b57cec5SDimitry Andric   cast<ObjFile<ELFT>>(file)->parse();
2000b57cec5SDimitry Andric }
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric // Add symbols in File to the symbol table.
203*85868e8aSDimitry Andric void parseFile(InputFile *file) {
2040b57cec5SDimitry Andric   switch (config->ekind) {
2050b57cec5SDimitry Andric   case ELF32LEKind:
2060b57cec5SDimitry Andric     doParseFile<ELF32LE>(file);
2070b57cec5SDimitry Andric     return;
2080b57cec5SDimitry Andric   case ELF32BEKind:
2090b57cec5SDimitry Andric     doParseFile<ELF32BE>(file);
2100b57cec5SDimitry Andric     return;
2110b57cec5SDimitry Andric   case ELF64LEKind:
2120b57cec5SDimitry Andric     doParseFile<ELF64LE>(file);
2130b57cec5SDimitry Andric     return;
2140b57cec5SDimitry Andric   case ELF64BEKind:
2150b57cec5SDimitry Andric     doParseFile<ELF64BE>(file);
2160b57cec5SDimitry Andric     return;
2170b57cec5SDimitry Andric   default:
2180b57cec5SDimitry Andric     llvm_unreachable("unknown ELFT");
2190b57cec5SDimitry Andric   }
2200b57cec5SDimitry Andric }
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric // Concatenates arguments to construct a string representing an error location.
2230b57cec5SDimitry Andric static std::string createFileLineMsg(StringRef path, unsigned line) {
2240b57cec5SDimitry Andric   std::string filename = 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.
2450b57cec5SDimitry Andric   return 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 
2660b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
267*85868e8aSDimitry Andric   dwarf = make<DWARFCache>(std::make_unique<DWARFContext>(
268*85868e8aSDimitry Andric       std::make_unique<LLDDwarfObj<ELFT>>(this)));
2690b57cec5SDimitry Andric }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric // Returns the pair of file name and line number describing location of data
2720b57cec5SDimitry Andric // object (variable, array, etc) definition.
2730b57cec5SDimitry Andric template <class ELFT>
2740b57cec5SDimitry Andric Optional<std::pair<std::string, unsigned>>
2750b57cec5SDimitry Andric ObjFile<ELFT>::getVariableLoc(StringRef name) {
2760b57cec5SDimitry Andric   llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
2770b57cec5SDimitry Andric 
278*85868e8aSDimitry Andric   return dwarf->getVariableLoc(name);
2790b57cec5SDimitry Andric }
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric // Returns source line information for a given offset
2820b57cec5SDimitry Andric // using DWARF debug info.
2830b57cec5SDimitry Andric template <class ELFT>
2840b57cec5SDimitry Andric Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s,
2850b57cec5SDimitry Andric                                                   uint64_t offset) {
2860b57cec5SDimitry Andric   llvm::call_once(initDwarfLine, [this]() { initializeDwarf(); });
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   // Detect SectionIndex for specified section.
2890b57cec5SDimitry Andric   uint64_t sectionIndex = object::SectionedAddress::UndefSection;
2900b57cec5SDimitry Andric   ArrayRef<InputSectionBase *> sections = s->file->getSections();
2910b57cec5SDimitry Andric   for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) {
2920b57cec5SDimitry Andric     if (s == sections[curIndex]) {
2930b57cec5SDimitry Andric       sectionIndex = curIndex;
2940b57cec5SDimitry Andric       break;
2950b57cec5SDimitry Andric     }
2960b57cec5SDimitry Andric   }
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric   // Use fake address calcuated by adding section file offset and offset in
2990b57cec5SDimitry Andric   // section. See comments for ObjectInfo class.
300*85868e8aSDimitry Andric   return dwarf->getDILineInfo(s->getOffsetInFile() + offset, sectionIndex);
3010b57cec5SDimitry Andric }
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) {
3040b57cec5SDimitry Andric   ekind = getELFKind(mb, "");
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric   switch (ekind) {
3070b57cec5SDimitry Andric   case ELF32LEKind:
3080b57cec5SDimitry Andric     init<ELF32LE>();
3090b57cec5SDimitry Andric     break;
3100b57cec5SDimitry Andric   case ELF32BEKind:
3110b57cec5SDimitry Andric     init<ELF32BE>();
3120b57cec5SDimitry Andric     break;
3130b57cec5SDimitry Andric   case ELF64LEKind:
3140b57cec5SDimitry Andric     init<ELF64LE>();
3150b57cec5SDimitry Andric     break;
3160b57cec5SDimitry Andric   case ELF64BEKind:
3170b57cec5SDimitry Andric     init<ELF64BE>();
3180b57cec5SDimitry Andric     break;
3190b57cec5SDimitry Andric   default:
3200b57cec5SDimitry Andric     llvm_unreachable("getELFKind");
3210b57cec5SDimitry Andric   }
3220b57cec5SDimitry Andric }
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric template <typename Elf_Shdr>
3250b57cec5SDimitry Andric static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
3260b57cec5SDimitry Andric   for (const Elf_Shdr &sec : sections)
3270b57cec5SDimitry Andric     if (sec.sh_type == type)
3280b57cec5SDimitry Andric       return &sec;
3290b57cec5SDimitry Andric   return nullptr;
3300b57cec5SDimitry Andric }
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric template <class ELFT> void ELFFileBase::init() {
3330b57cec5SDimitry Andric   using Elf_Shdr = typename ELFT::Shdr;
3340b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric   // Initialize trivial attributes.
3370b57cec5SDimitry Andric   const ELFFile<ELFT> &obj = getObj<ELFT>();
3380b57cec5SDimitry Andric   emachine = obj.getHeader()->e_machine;
3390b57cec5SDimitry Andric   osabi = obj.getHeader()->e_ident[llvm::ELF::EI_OSABI];
3400b57cec5SDimitry Andric   abiVersion = obj.getHeader()->e_ident[llvm::ELF::EI_ABIVERSION];
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   // Find a symbol table.
3450b57cec5SDimitry Andric   bool isDSO =
3460b57cec5SDimitry Andric       (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
3470b57cec5SDimitry Andric   const Elf_Shdr *symtabSec =
3480b57cec5SDimitry Andric       findSection(sections, isDSO ? SHT_DYNSYM : SHT_SYMTAB);
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric   if (!symtabSec)
3510b57cec5SDimitry Andric     return;
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric   // Initialize members corresponding to a symbol table.
3540b57cec5SDimitry Andric   firstGlobal = symtabSec->sh_info;
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
3570b57cec5SDimitry Andric   if (firstGlobal == 0 || firstGlobal > eSyms.size())
3580b57cec5SDimitry Andric     fatal(toString(this) + ": invalid sh_info in symbol table");
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   elfSyms = reinterpret_cast<const void *>(eSyms.data());
3610b57cec5SDimitry Andric   numELFSyms = eSyms.size();
3620b57cec5SDimitry Andric   stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
3630b57cec5SDimitry Andric }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric template <class ELFT>
3660b57cec5SDimitry Andric uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
3670b57cec5SDimitry Andric   return CHECK(
3680b57cec5SDimitry Andric       this->getObj().getSectionIndex(&sym, getELFSyms<ELFT>(), shndxTable),
3690b57cec5SDimitry Andric       this);
3700b57cec5SDimitry Andric }
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
3730b57cec5SDimitry Andric   if (this->symbols.empty())
3740b57cec5SDimitry Andric     return {};
3750b57cec5SDimitry Andric   return makeArrayRef(this->symbols).slice(1, this->firstGlobal - 1);
3760b57cec5SDimitry Andric }
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
3790b57cec5SDimitry Andric   return makeArrayRef(this->symbols).slice(this->firstGlobal);
3800b57cec5SDimitry Andric }
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
3830b57cec5SDimitry Andric   // Read a section table. justSymbols is usually false.
3840b57cec5SDimitry Andric   if (this->justSymbols)
3850b57cec5SDimitry Andric     initializeJustSymbols();
3860b57cec5SDimitry Andric   else
3870b57cec5SDimitry Andric     initializeSections(ignoreComdats);
3880b57cec5SDimitry Andric 
3890b57cec5SDimitry Andric   // Read a symbol table.
3900b57cec5SDimitry Andric   initializeSymbols();
3910b57cec5SDimitry Andric }
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric // Sections with SHT_GROUP and comdat bits define comdat section groups.
3940b57cec5SDimitry Andric // They are identified and deduplicated by group name. This function
3950b57cec5SDimitry Andric // returns a group name.
3960b57cec5SDimitry Andric template <class ELFT>
3970b57cec5SDimitry Andric StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
3980b57cec5SDimitry Andric                                               const Elf_Shdr &sec) {
3990b57cec5SDimitry Andric   typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
4000b57cec5SDimitry Andric   if (sec.sh_info >= symbols.size())
4010b57cec5SDimitry Andric     fatal(toString(this) + ": invalid symbol index");
4020b57cec5SDimitry Andric   const typename ELFT::Sym &sym = symbols[sec.sh_info];
4030b57cec5SDimitry Andric   StringRef signature = CHECK(sym.getName(this->stringTable), this);
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   // As a special case, if a symbol is a section symbol and has no name,
4060b57cec5SDimitry Andric   // we use a section name as a signature.
4070b57cec5SDimitry Andric   //
4080b57cec5SDimitry Andric   // Such SHT_GROUP sections are invalid from the perspective of the ELF
4090b57cec5SDimitry Andric   // standard, but GNU gold 1.14 (the newest version as of July 2017) or
4100b57cec5SDimitry Andric   // older produce such sections as outputs for the -r option, so we need
4110b57cec5SDimitry Andric   // a bug-compatibility.
4120b57cec5SDimitry Andric   if (signature.empty() && sym.getType() == STT_SECTION)
4130b57cec5SDimitry Andric     return getSectionName(sec);
4140b57cec5SDimitry Andric   return signature;
4150b57cec5SDimitry Andric }
4160b57cec5SDimitry Andric 
417*85868e8aSDimitry Andric template <class ELFT>
418*85868e8aSDimitry Andric bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
4190b57cec5SDimitry Andric   // On a regular link we don't merge sections if -O0 (default is -O1). This
4200b57cec5SDimitry Andric   // sometimes makes the linker significantly faster, although the output will
4210b57cec5SDimitry Andric   // be bigger.
4220b57cec5SDimitry Andric   //
4230b57cec5SDimitry Andric   // Doing the same for -r would create a problem as it would combine sections
4240b57cec5SDimitry Andric   // with different sh_entsize. One option would be to just copy every SHF_MERGE
4250b57cec5SDimitry Andric   // section as is to the output. While this would produce a valid ELF file with
4260b57cec5SDimitry Andric   // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
4270b57cec5SDimitry Andric   // they see two .debug_str. We could have separate logic for combining
4280b57cec5SDimitry Andric   // SHF_MERGE sections based both on their name and sh_entsize, but that seems
4290b57cec5SDimitry Andric   // to be more trouble than it is worth. Instead, we just use the regular (-O1)
4300b57cec5SDimitry Andric   // logic for -r.
4310b57cec5SDimitry Andric   if (config->optimize == 0 && !config->relocatable)
4320b57cec5SDimitry Andric     return false;
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   // A mergeable section with size 0 is useless because they don't have
4350b57cec5SDimitry Andric   // any data to merge. A mergeable string section with size 0 can be
4360b57cec5SDimitry Andric   // argued as invalid because it doesn't end with a null character.
4370b57cec5SDimitry Andric   // We'll avoid a mess by handling them as if they were non-mergeable.
4380b57cec5SDimitry Andric   if (sec.sh_size == 0)
4390b57cec5SDimitry Andric     return false;
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   // Check for sh_entsize. The ELF spec is not clear about the zero
4420b57cec5SDimitry Andric   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
4430b57cec5SDimitry Andric   // the section does not hold a table of fixed-size entries". We know
4440b57cec5SDimitry Andric   // that Rust 1.13 produces a string mergeable section with a zero
4450b57cec5SDimitry Andric   // sh_entsize. Here we just accept it rather than being picky about it.
4460b57cec5SDimitry Andric   uint64_t entSize = sec.sh_entsize;
4470b57cec5SDimitry Andric   if (entSize == 0)
4480b57cec5SDimitry Andric     return false;
4490b57cec5SDimitry Andric   if (sec.sh_size % entSize)
450*85868e8aSDimitry Andric     fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" +
451*85868e8aSDimitry Andric           Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" +
452*85868e8aSDimitry Andric           Twine(entSize) + ")");
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric   uint64_t flags = sec.sh_flags;
4550b57cec5SDimitry Andric   if (!(flags & SHF_MERGE))
4560b57cec5SDimitry Andric     return false;
4570b57cec5SDimitry Andric   if (flags & SHF_WRITE)
458*85868e8aSDimitry Andric     fatal(toString(this) + ":(" + name +
459*85868e8aSDimitry Andric           "): writable SHF_MERGE section is not supported");
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric   return true;
4620b57cec5SDimitry Andric }
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric // This is for --just-symbols.
4650b57cec5SDimitry Andric //
4660b57cec5SDimitry Andric // --just-symbols is a very minor feature that allows you to link your
4670b57cec5SDimitry Andric // output against other existing program, so that if you load both your
4680b57cec5SDimitry Andric // program and the other program into memory, your output can refer the
4690b57cec5SDimitry Andric // other program's symbols.
4700b57cec5SDimitry Andric //
4710b57cec5SDimitry Andric // When the option is given, we link "just symbols". The section table is
4720b57cec5SDimitry Andric // initialized with null pointers.
4730b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
4740b57cec5SDimitry Andric   ArrayRef<Elf_Shdr> sections = CHECK(this->getObj().sections(), this);
4750b57cec5SDimitry Andric   this->sections.resize(sections.size());
4760b57cec5SDimitry Andric }
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric // An ELF object file may contain a `.deplibs` section. If it exists, the
4790b57cec5SDimitry Andric // section contains a list of library specifiers such as `m` for libm. This
4800b57cec5SDimitry Andric // function resolves a given name by finding the first matching library checking
4810b57cec5SDimitry Andric // the various ways that a library can be specified to LLD. This ELF extension
4820b57cec5SDimitry Andric // is a form of autolinking and is called `dependent libraries`. It is currently
4830b57cec5SDimitry Andric // unique to LLVM and lld.
4840b57cec5SDimitry Andric static void addDependentLibrary(StringRef specifier, const InputFile *f) {
4850b57cec5SDimitry Andric   if (!config->dependentLibraries)
4860b57cec5SDimitry Andric     return;
4870b57cec5SDimitry Andric   if (fs::exists(specifier))
4880b57cec5SDimitry Andric     driver->addFile(specifier, /*withLOption=*/false);
4890b57cec5SDimitry Andric   else if (Optional<std::string> s = findFromSearchPaths(specifier))
4900b57cec5SDimitry Andric     driver->addFile(*s, /*withLOption=*/true);
4910b57cec5SDimitry Andric   else if (Optional<std::string> s = searchLibraryBaseName(specifier))
4920b57cec5SDimitry Andric     driver->addFile(*s, /*withLOption=*/true);
4930b57cec5SDimitry Andric   else
4940b57cec5SDimitry Andric     error(toString(f) +
4950b57cec5SDimitry Andric           ": unable to find library from dependent library specifier: " +
4960b57cec5SDimitry Andric           specifier);
4970b57cec5SDimitry Andric }
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric template <class ELFT>
5000b57cec5SDimitry Andric void ObjFile<ELFT>::initializeSections(bool ignoreComdats) {
5010b57cec5SDimitry Andric   const ELFFile<ELFT> &obj = this->getObj();
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric   ArrayRef<Elf_Shdr> objSections = CHECK(obj.sections(), this);
5040b57cec5SDimitry Andric   uint64_t size = objSections.size();
5050b57cec5SDimitry Andric   this->sections.resize(size);
5060b57cec5SDimitry Andric   this->sectionStringTable =
5070b57cec5SDimitry Andric       CHECK(obj.getSectionStringTable(objSections), this);
5080b57cec5SDimitry Andric 
509*85868e8aSDimitry Andric   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
5100b57cec5SDimitry Andric     if (this->sections[i] == &InputSection::discarded)
5110b57cec5SDimitry Andric       continue;
5120b57cec5SDimitry Andric     const Elf_Shdr &sec = objSections[i];
5130b57cec5SDimitry Andric 
5140b57cec5SDimitry Andric     if (sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
5150b57cec5SDimitry Andric       cgProfile =
5160b57cec5SDimitry Andric           check(obj.template getSectionContentsAsArray<Elf_CGProfile>(&sec));
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
5190b57cec5SDimitry Andric     // if -r is given, we'll let the final link discard such sections.
5200b57cec5SDimitry Andric     // This is compatible with GNU.
5210b57cec5SDimitry Andric     if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) {
5220b57cec5SDimitry Andric       if (sec.sh_type == SHT_LLVM_ADDRSIG) {
5230b57cec5SDimitry Andric         // We ignore the address-significance table if we know that the object
5240b57cec5SDimitry Andric         // file was created by objcopy or ld -r. This is because these tools
5250b57cec5SDimitry Andric         // will reorder the symbols in the symbol table, invalidating the data
5260b57cec5SDimitry Andric         // in the address-significance table, which refers to symbols by index.
5270b57cec5SDimitry Andric         if (sec.sh_link != 0)
5280b57cec5SDimitry Andric           this->addrsigSec = &sec;
5290b57cec5SDimitry Andric         else if (config->icf == ICFLevel::Safe)
5300b57cec5SDimitry Andric           warn(toString(this) + ": --icf=safe is incompatible with object "
5310b57cec5SDimitry Andric                                 "files created using objcopy or ld -r");
5320b57cec5SDimitry Andric       }
5330b57cec5SDimitry Andric       this->sections[i] = &InputSection::discarded;
5340b57cec5SDimitry Andric       continue;
5350b57cec5SDimitry Andric     }
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric     switch (sec.sh_type) {
5380b57cec5SDimitry Andric     case SHT_GROUP: {
5390b57cec5SDimitry Andric       // De-duplicate section groups by their signatures.
5400b57cec5SDimitry Andric       StringRef signature = getShtGroupSignature(objSections, sec);
5410b57cec5SDimitry Andric       this->sections[i] = &InputSection::discarded;
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric       ArrayRef<Elf_Word> entries =
5450b57cec5SDimitry Andric           CHECK(obj.template getSectionContentsAsArray<Elf_Word>(&sec), this);
5460b57cec5SDimitry Andric       if (entries.empty())
5470b57cec5SDimitry Andric         fatal(toString(this) + ": empty SHT_GROUP");
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric       // The first word of a SHT_GROUP section contains flags. Currently,
5500b57cec5SDimitry Andric       // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
5510b57cec5SDimitry Andric       // An group with the empty flag doesn't define anything; such sections
5520b57cec5SDimitry Andric       // are just skipped.
5530b57cec5SDimitry Andric       if (entries[0] == 0)
5540b57cec5SDimitry Andric         continue;
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric       if (entries[0] != GRP_COMDAT)
5570b57cec5SDimitry Andric         fatal(toString(this) + ": unsupported SHT_GROUP format");
5580b57cec5SDimitry Andric 
5590b57cec5SDimitry Andric       bool isNew =
5600b57cec5SDimitry Andric           ignoreComdats ||
5610b57cec5SDimitry Andric           symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
5620b57cec5SDimitry Andric               .second;
5630b57cec5SDimitry Andric       if (isNew) {
5640b57cec5SDimitry Andric         if (config->relocatable)
5650b57cec5SDimitry Andric           this->sections[i] = createInputSection(sec);
5660b57cec5SDimitry Andric         continue;
5670b57cec5SDimitry Andric       }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric       // Otherwise, discard group members.
5700b57cec5SDimitry Andric       for (uint32_t secIndex : entries.slice(1)) {
5710b57cec5SDimitry Andric         if (secIndex >= size)
5720b57cec5SDimitry Andric           fatal(toString(this) +
5730b57cec5SDimitry Andric                 ": invalid section index in group: " + Twine(secIndex));
5740b57cec5SDimitry Andric         this->sections[secIndex] = &InputSection::discarded;
5750b57cec5SDimitry Andric       }
5760b57cec5SDimitry Andric       break;
5770b57cec5SDimitry Andric     }
5780b57cec5SDimitry Andric     case SHT_SYMTAB_SHNDX:
5790b57cec5SDimitry Andric       shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
5800b57cec5SDimitry Andric       break;
5810b57cec5SDimitry Andric     case SHT_SYMTAB:
5820b57cec5SDimitry Andric     case SHT_STRTAB:
5830b57cec5SDimitry Andric     case SHT_NULL:
5840b57cec5SDimitry Andric       break;
5850b57cec5SDimitry Andric     default:
5860b57cec5SDimitry Andric       this->sections[i] = createInputSection(sec);
5870b57cec5SDimitry Andric     }
588*85868e8aSDimitry Andric   }
589*85868e8aSDimitry Andric 
590*85868e8aSDimitry Andric   for (size_t i = 0, e = objSections.size(); i < e; ++i) {
591*85868e8aSDimitry Andric     if (this->sections[i] == &InputSection::discarded)
592*85868e8aSDimitry Andric       continue;
593*85868e8aSDimitry Andric     const Elf_Shdr &sec = objSections[i];
594*85868e8aSDimitry Andric     if (!(sec.sh_flags & SHF_LINK_ORDER))
595*85868e8aSDimitry Andric       continue;
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric     // .ARM.exidx sections have a reverse dependency on the InputSection they
5980b57cec5SDimitry Andric     // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
5990b57cec5SDimitry Andric     InputSectionBase *linkSec = nullptr;
6000b57cec5SDimitry Andric     if (sec.sh_link < this->sections.size())
6010b57cec5SDimitry Andric       linkSec = this->sections[sec.sh_link];
6020b57cec5SDimitry Andric     if (!linkSec)
603*85868e8aSDimitry Andric       fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric     InputSection *isec = cast<InputSection>(this->sections[i]);
6060b57cec5SDimitry Andric     linkSec->dependentSections.push_back(isec);
6070b57cec5SDimitry Andric     if (!isa<InputSection>(linkSec))
6080b57cec5SDimitry Andric       error("a section " + isec->name +
609*85868e8aSDimitry Andric             " with SHF_LINK_ORDER should not refer a non-regular section: " +
6100b57cec5SDimitry Andric             toString(linkSec));
6110b57cec5SDimitry Andric   }
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
6150b57cec5SDimitry Andric // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
6160b57cec5SDimitry Andric // the input objects have been compiled.
6170b57cec5SDimitry Andric static void updateARMVFPArgs(const ARMAttributeParser &attributes,
6180b57cec5SDimitry Andric                              const InputFile *f) {
6190b57cec5SDimitry Andric   if (!attributes.hasAttribute(ARMBuildAttrs::ABI_VFP_args))
6200b57cec5SDimitry Andric     // If an ABI tag isn't present then it is implicitly given the value of 0
6210b57cec5SDimitry Andric     // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
6220b57cec5SDimitry Andric     // including some in glibc that don't use FP args (and should have value 3)
6230b57cec5SDimitry Andric     // don't have the attribute so we do not consider an implicit value of 0
6240b57cec5SDimitry Andric     // as a clash.
6250b57cec5SDimitry Andric     return;
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   unsigned vfpArgs = attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
6280b57cec5SDimitry Andric   ARMVFPArgKind arg;
6290b57cec5SDimitry Andric   switch (vfpArgs) {
6300b57cec5SDimitry Andric   case ARMBuildAttrs::BaseAAPCS:
6310b57cec5SDimitry Andric     arg = ARMVFPArgKind::Base;
6320b57cec5SDimitry Andric     break;
6330b57cec5SDimitry Andric   case ARMBuildAttrs::HardFPAAPCS:
6340b57cec5SDimitry Andric     arg = ARMVFPArgKind::VFP;
6350b57cec5SDimitry Andric     break;
6360b57cec5SDimitry Andric   case ARMBuildAttrs::ToolChainFPPCS:
6370b57cec5SDimitry Andric     // Tool chain specific convention that conforms to neither AAPCS variant.
6380b57cec5SDimitry Andric     arg = ARMVFPArgKind::ToolChain;
6390b57cec5SDimitry Andric     break;
6400b57cec5SDimitry Andric   case ARMBuildAttrs::CompatibleFPAAPCS:
6410b57cec5SDimitry Andric     // Object compatible with all conventions.
6420b57cec5SDimitry Andric     return;
6430b57cec5SDimitry Andric   default:
6440b57cec5SDimitry Andric     error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs));
6450b57cec5SDimitry Andric     return;
6460b57cec5SDimitry Andric   }
6470b57cec5SDimitry Andric   // Follow ld.bfd and error if there is a mix of calling conventions.
6480b57cec5SDimitry Andric   if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default)
6490b57cec5SDimitry Andric     error(toString(f) + ": incompatible Tag_ABI_VFP_args");
6500b57cec5SDimitry Andric   else
6510b57cec5SDimitry Andric     config->armVFPArgs = arg;
6520b57cec5SDimitry Andric }
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric // The ARM support in lld makes some use of instructions that are not available
6550b57cec5SDimitry Andric // on all ARM architectures. Namely:
6560b57cec5SDimitry Andric // - Use of BLX instruction for interworking between ARM and Thumb state.
6570b57cec5SDimitry Andric // - Use of the extended Thumb branch encoding in relocation.
6580b57cec5SDimitry Andric // - Use of the MOVT/MOVW instructions in Thumb Thunks.
6590b57cec5SDimitry Andric // The ARM Attributes section contains information about the architecture chosen
6600b57cec5SDimitry Andric // at compile time. We follow the convention that if at least one input object
6610b57cec5SDimitry Andric // is compiled with an architecture that supports these features then lld is
6620b57cec5SDimitry Andric // permitted to use them.
6630b57cec5SDimitry Andric static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
6640b57cec5SDimitry Andric   if (!attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
6650b57cec5SDimitry Andric     return;
6660b57cec5SDimitry Andric   auto arch = attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
6670b57cec5SDimitry Andric   switch (arch) {
6680b57cec5SDimitry Andric   case ARMBuildAttrs::Pre_v4:
6690b57cec5SDimitry Andric   case ARMBuildAttrs::v4:
6700b57cec5SDimitry Andric   case ARMBuildAttrs::v4T:
6710b57cec5SDimitry Andric     // Architectures prior to v5 do not support BLX instruction
6720b57cec5SDimitry Andric     break;
6730b57cec5SDimitry Andric   case ARMBuildAttrs::v5T:
6740b57cec5SDimitry Andric   case ARMBuildAttrs::v5TE:
6750b57cec5SDimitry Andric   case ARMBuildAttrs::v5TEJ:
6760b57cec5SDimitry Andric   case ARMBuildAttrs::v6:
6770b57cec5SDimitry Andric   case ARMBuildAttrs::v6KZ:
6780b57cec5SDimitry Andric   case ARMBuildAttrs::v6K:
6790b57cec5SDimitry Andric     config->armHasBlx = true;
6800b57cec5SDimitry Andric     // Architectures used in pre-Cortex processors do not support
6810b57cec5SDimitry Andric     // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
6820b57cec5SDimitry Andric     // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
6830b57cec5SDimitry Andric     break;
6840b57cec5SDimitry Andric   default:
6850b57cec5SDimitry Andric     // All other Architectures have BLX and extended branch encoding
6860b57cec5SDimitry Andric     config->armHasBlx = true;
6870b57cec5SDimitry Andric     config->armJ1J2BranchEncoding = true;
6880b57cec5SDimitry Andric     if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
6890b57cec5SDimitry Andric       // All Architectures used in Cortex processors with the exception
6900b57cec5SDimitry Andric       // of v6-M and v6S-M have the MOVT and MOVW instructions.
6910b57cec5SDimitry Andric       config->armHasMovtMovw = true;
6920b57cec5SDimitry Andric     break;
6930b57cec5SDimitry Andric   }
6940b57cec5SDimitry Andric }
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric // If a source file is compiled with x86 hardware-assisted call flow control
6970b57cec5SDimitry Andric // enabled, the generated object file contains feature flags indicating that
6980b57cec5SDimitry Andric // fact. This function reads the feature flags and returns it.
6990b57cec5SDimitry Andric //
7000b57cec5SDimitry Andric // Essentially we want to read a single 32-bit value in this function, but this
7010b57cec5SDimitry Andric // function is rather complicated because the value is buried deep inside a
7020b57cec5SDimitry Andric // .note.gnu.property section.
7030b57cec5SDimitry Andric //
7040b57cec5SDimitry Andric // The section consists of one or more NOTE records. Each NOTE record consists
7050b57cec5SDimitry Andric // of zero or more type-length-value fields. We want to find a field of a
7060b57cec5SDimitry Andric // certain type. It seems a bit too much to just store a 32-bit value, perhaps
7070b57cec5SDimitry Andric // the ABI is unnecessarily complicated.
7080b57cec5SDimitry Andric template <class ELFT>
7090b57cec5SDimitry Andric static uint32_t readAndFeatures(ObjFile<ELFT> *obj, ArrayRef<uint8_t> data) {
7100b57cec5SDimitry Andric   using Elf_Nhdr = typename ELFT::Nhdr;
7110b57cec5SDimitry Andric   using Elf_Note = typename ELFT::Note;
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric   uint32_t featuresSet = 0;
7140b57cec5SDimitry Andric   while (!data.empty()) {
7150b57cec5SDimitry Andric     // Read one NOTE record.
7160b57cec5SDimitry Andric     if (data.size() < sizeof(Elf_Nhdr))
7170b57cec5SDimitry Andric       fatal(toString(obj) + ": .note.gnu.property: section too short");
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric     auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
7200b57cec5SDimitry Andric     if (data.size() < nhdr->getSize())
7210b57cec5SDimitry Andric       fatal(toString(obj) + ": .note.gnu.property: section too short");
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric     Elf_Note note(*nhdr);
7240b57cec5SDimitry Andric     if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
7250b57cec5SDimitry Andric       data = data.slice(nhdr->getSize());
7260b57cec5SDimitry Andric       continue;
7270b57cec5SDimitry Andric     }
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric     uint32_t featureAndType = config->emachine == EM_AARCH64
7300b57cec5SDimitry Andric                                   ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
7310b57cec5SDimitry Andric                                   : GNU_PROPERTY_X86_FEATURE_1_AND;
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric     // Read a body of a NOTE record, which consists of type-length-value fields.
7340b57cec5SDimitry Andric     ArrayRef<uint8_t> desc = note.getDesc();
7350b57cec5SDimitry Andric     while (!desc.empty()) {
7360b57cec5SDimitry Andric       if (desc.size() < 8)
7370b57cec5SDimitry Andric         fatal(toString(obj) + ": .note.gnu.property: section too short");
7380b57cec5SDimitry Andric 
7390b57cec5SDimitry Andric       uint32_t type = read32le(desc.data());
7400b57cec5SDimitry Andric       uint32_t size = read32le(desc.data() + 4);
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric       if (type == featureAndType) {
7430b57cec5SDimitry Andric         // We found a FEATURE_1_AND field. There may be more than one of these
7440b57cec5SDimitry Andric         // in a .note.gnu.propery section, for a relocatable object we
7450b57cec5SDimitry Andric         // accumulate the bits set.
7460b57cec5SDimitry Andric         featuresSet |= read32le(desc.data() + 8);
7470b57cec5SDimitry Andric       }
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric       // On 64-bit, a payload may be followed by a 4-byte padding to make its
7500b57cec5SDimitry Andric       // size a multiple of 8.
7510b57cec5SDimitry Andric       if (ELFT::Is64Bits)
7520b57cec5SDimitry Andric         size = alignTo(size, 8);
7530b57cec5SDimitry Andric 
7540b57cec5SDimitry Andric       desc = desc.slice(size + 8); // +8 for Type and Size
7550b57cec5SDimitry Andric     }
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric     // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
7580b57cec5SDimitry Andric     data = data.slice(nhdr->getSize());
7590b57cec5SDimitry Andric   }
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   return featuresSet;
7620b57cec5SDimitry Andric }
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric template <class ELFT>
7650b57cec5SDimitry Andric InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &sec) {
7660b57cec5SDimitry Andric   uint32_t idx = sec.sh_info;
7670b57cec5SDimitry Andric   if (idx >= this->sections.size())
7680b57cec5SDimitry Andric     fatal(toString(this) + ": invalid relocated section index: " + Twine(idx));
7690b57cec5SDimitry Andric   InputSectionBase *target = this->sections[idx];
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric   // Strictly speaking, a relocation section must be included in the
7720b57cec5SDimitry Andric   // group of the section it relocates. However, LLVM 3.3 and earlier
7730b57cec5SDimitry Andric   // would fail to do so, so we gracefully handle that case.
7740b57cec5SDimitry Andric   if (target == &InputSection::discarded)
7750b57cec5SDimitry Andric     return nullptr;
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric   if (!target)
7780b57cec5SDimitry Andric     fatal(toString(this) + ": unsupported relocation reference");
7790b57cec5SDimitry Andric   return target;
7800b57cec5SDimitry Andric }
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric // Create a regular InputSection class that has the same contents
7830b57cec5SDimitry Andric // as a given section.
7840b57cec5SDimitry Andric static InputSection *toRegularSection(MergeInputSection *sec) {
7850b57cec5SDimitry Andric   return make<InputSection>(sec->file, sec->flags, sec->type, sec->alignment,
7860b57cec5SDimitry Andric                             sec->data(), sec->name);
7870b57cec5SDimitry Andric }
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric template <class ELFT>
7900b57cec5SDimitry Andric InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &sec) {
7910b57cec5SDimitry Andric   StringRef name = getSectionName(sec);
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric   switch (sec.sh_type) {
7940b57cec5SDimitry Andric   case SHT_ARM_ATTRIBUTES: {
7950b57cec5SDimitry Andric     if (config->emachine != EM_ARM)
7960b57cec5SDimitry Andric       break;
7970b57cec5SDimitry Andric     ARMAttributeParser attributes;
7980b57cec5SDimitry Andric     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
7990b57cec5SDimitry Andric     attributes.Parse(contents, /*isLittle*/ config->ekind == ELF32LEKind);
8000b57cec5SDimitry Andric     updateSupportedARMFeatures(attributes);
8010b57cec5SDimitry Andric     updateARMVFPArgs(attributes, this);
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric     // FIXME: Retain the first attribute section we see. The eglibc ARM
8040b57cec5SDimitry Andric     // dynamic loaders require the presence of an attribute section for dlopen
8050b57cec5SDimitry Andric     // to work. In a full implementation we would merge all attribute sections.
8060b57cec5SDimitry Andric     if (in.armAttributes == nullptr) {
8070b57cec5SDimitry Andric       in.armAttributes = make<InputSection>(*this, sec, name);
8080b57cec5SDimitry Andric       return in.armAttributes;
8090b57cec5SDimitry Andric     }
8100b57cec5SDimitry Andric     return &InputSection::discarded;
8110b57cec5SDimitry Andric   }
8120b57cec5SDimitry Andric   case SHT_LLVM_DEPENDENT_LIBRARIES: {
8130b57cec5SDimitry Andric     if (config->relocatable)
8140b57cec5SDimitry Andric       break;
8150b57cec5SDimitry Andric     ArrayRef<char> data =
8160b57cec5SDimitry Andric         CHECK(this->getObj().template getSectionContentsAsArray<char>(&sec), this);
8170b57cec5SDimitry Andric     if (!data.empty() && data.back() != '\0') {
8180b57cec5SDimitry Andric       error(toString(this) +
8190b57cec5SDimitry Andric             ": corrupted dependent libraries section (unterminated string): " +
8200b57cec5SDimitry Andric             name);
8210b57cec5SDimitry Andric       return &InputSection::discarded;
8220b57cec5SDimitry Andric     }
8230b57cec5SDimitry Andric     for (const char *d = data.begin(), *e = data.end(); d < e;) {
8240b57cec5SDimitry Andric       StringRef s(d);
8250b57cec5SDimitry Andric       addDependentLibrary(s, this);
8260b57cec5SDimitry Andric       d += s.size() + 1;
8270b57cec5SDimitry Andric     }
8280b57cec5SDimitry Andric     return &InputSection::discarded;
8290b57cec5SDimitry Andric   }
8300b57cec5SDimitry Andric   case SHT_RELA:
8310b57cec5SDimitry Andric   case SHT_REL: {
8320b57cec5SDimitry Andric     // Find a relocation target section and associate this section with that.
8330b57cec5SDimitry Andric     // Target may have been discarded if it is in a different section group
8340b57cec5SDimitry Andric     // and the group is discarded, even though it's a violation of the
8350b57cec5SDimitry Andric     // spec. We handle that situation gracefully by discarding dangling
8360b57cec5SDimitry Andric     // relocation sections.
8370b57cec5SDimitry Andric     InputSectionBase *target = getRelocTarget(sec);
8380b57cec5SDimitry Andric     if (!target)
8390b57cec5SDimitry Andric       return nullptr;
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric     // This section contains relocation information.
8420b57cec5SDimitry Andric     // If -r is given, we do not interpret or apply relocation
8430b57cec5SDimitry Andric     // but just copy relocation sections to output.
8440b57cec5SDimitry Andric     if (config->relocatable) {
8450b57cec5SDimitry Andric       InputSection *relocSec = make<InputSection>(*this, sec, name);
8460b57cec5SDimitry Andric       // We want to add a dependency to target, similar like we do for
8470b57cec5SDimitry Andric       // -emit-relocs below. This is useful for the case when linker script
8480b57cec5SDimitry Andric       // contains the "/DISCARD/". It is perhaps uncommon to use a script with
8490b57cec5SDimitry Andric       // -r, but we faced it in the Linux kernel and have to handle such case
8500b57cec5SDimitry Andric       // and not to crash.
8510b57cec5SDimitry Andric       target->dependentSections.push_back(relocSec);
8520b57cec5SDimitry Andric       return relocSec;
8530b57cec5SDimitry Andric     }
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric     if (target->firstRelocation)
8560b57cec5SDimitry Andric       fatal(toString(this) +
8570b57cec5SDimitry Andric             ": multiple relocation sections to one section are not supported");
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric     // ELF spec allows mergeable sections with relocations, but they are
8600b57cec5SDimitry Andric     // rare, and it is in practice hard to merge such sections by contents,
8610b57cec5SDimitry Andric     // because applying relocations at end of linking changes section
8620b57cec5SDimitry Andric     // contents. So, we simply handle such sections as non-mergeable ones.
8630b57cec5SDimitry Andric     // Degrading like this is acceptable because section merging is optional.
8640b57cec5SDimitry Andric     if (auto *ms = dyn_cast<MergeInputSection>(target)) {
8650b57cec5SDimitry Andric       target = toRegularSection(ms);
8660b57cec5SDimitry Andric       this->sections[sec.sh_info] = target;
8670b57cec5SDimitry Andric     }
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric     if (sec.sh_type == SHT_RELA) {
8700b57cec5SDimitry Andric       ArrayRef<Elf_Rela> rels = CHECK(getObj().relas(&sec), this);
8710b57cec5SDimitry Andric       target->firstRelocation = rels.begin();
8720b57cec5SDimitry Andric       target->numRelocations = rels.size();
8730b57cec5SDimitry Andric       target->areRelocsRela = true;
8740b57cec5SDimitry Andric     } else {
8750b57cec5SDimitry Andric       ArrayRef<Elf_Rel> rels = CHECK(getObj().rels(&sec), this);
8760b57cec5SDimitry Andric       target->firstRelocation = rels.begin();
8770b57cec5SDimitry Andric       target->numRelocations = rels.size();
8780b57cec5SDimitry Andric       target->areRelocsRela = false;
8790b57cec5SDimitry Andric     }
8800b57cec5SDimitry Andric     assert(isUInt<31>(target->numRelocations));
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric     // Relocation sections processed by the linker are usually removed
8830b57cec5SDimitry Andric     // from the output, so returning `nullptr` for the normal case.
8840b57cec5SDimitry Andric     // However, if -emit-relocs is given, we need to leave them in the output.
8850b57cec5SDimitry Andric     // (Some post link analysis tools need this information.)
8860b57cec5SDimitry Andric     if (config->emitRelocs) {
8870b57cec5SDimitry Andric       InputSection *relocSec = make<InputSection>(*this, sec, name);
8880b57cec5SDimitry Andric       // We will not emit relocation section if target was discarded.
8890b57cec5SDimitry Andric       target->dependentSections.push_back(relocSec);
8900b57cec5SDimitry Andric       return relocSec;
8910b57cec5SDimitry Andric     }
8920b57cec5SDimitry Andric     return nullptr;
8930b57cec5SDimitry Andric   }
8940b57cec5SDimitry Andric   }
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric   // The GNU linker uses .note.GNU-stack section as a marker indicating
8970b57cec5SDimitry Andric   // that the code in the object file does not expect that the stack is
8980b57cec5SDimitry Andric   // executable (in terms of NX bit). If all input files have the marker,
8990b57cec5SDimitry Andric   // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
9000b57cec5SDimitry Andric   // make the stack non-executable. Most object files have this section as
9010b57cec5SDimitry Andric   // of 2017.
9020b57cec5SDimitry Andric   //
9030b57cec5SDimitry Andric   // But making the stack non-executable is a norm today for security
9040b57cec5SDimitry Andric   // reasons. Failure to do so may result in a serious security issue.
9050b57cec5SDimitry Andric   // Therefore, we make LLD always add PT_GNU_STACK unless it is
9060b57cec5SDimitry Andric   // explicitly told to do otherwise (by -z execstack). Because the stack
9070b57cec5SDimitry Andric   // executable-ness is controlled solely by command line options,
9080b57cec5SDimitry Andric   // .note.GNU-stack sections are simply ignored.
9090b57cec5SDimitry Andric   if (name == ".note.GNU-stack")
9100b57cec5SDimitry Andric     return &InputSection::discarded;
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric   // Object files that use processor features such as Intel Control-Flow
9130b57cec5SDimitry Andric   // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
9140b57cec5SDimitry Andric   // .note.gnu.property section containing a bitfield of feature bits like the
9150b57cec5SDimitry Andric   // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
9160b57cec5SDimitry Andric   //
9170b57cec5SDimitry Andric   // Since we merge bitmaps from multiple object files to create a new
9180b57cec5SDimitry Andric   // .note.gnu.property containing a single AND'ed bitmap, we discard an input
9190b57cec5SDimitry Andric   // file's .note.gnu.property section.
9200b57cec5SDimitry Andric   if (name == ".note.gnu.property") {
9210b57cec5SDimitry Andric     ArrayRef<uint8_t> contents = check(this->getObj().getSectionContents(&sec));
9220b57cec5SDimitry Andric     this->andFeatures = readAndFeatures(this, contents);
9230b57cec5SDimitry Andric     return &InputSection::discarded;
9240b57cec5SDimitry Andric   }
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   // Split stacks is a feature to support a discontiguous stack,
9270b57cec5SDimitry Andric   // commonly used in the programming language Go. For the details,
9280b57cec5SDimitry Andric   // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
9290b57cec5SDimitry Andric   // for split stack will include a .note.GNU-split-stack section.
9300b57cec5SDimitry Andric   if (name == ".note.GNU-split-stack") {
9310b57cec5SDimitry Andric     if (config->relocatable) {
9320b57cec5SDimitry Andric       error("cannot mix split-stack and non-split-stack in a relocatable link");
9330b57cec5SDimitry Andric       return &InputSection::discarded;
9340b57cec5SDimitry Andric     }
9350b57cec5SDimitry Andric     this->splitStack = true;
9360b57cec5SDimitry Andric     return &InputSection::discarded;
9370b57cec5SDimitry Andric   }
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   // An object file cmpiled for split stack, but where some of the
9400b57cec5SDimitry Andric   // functions were compiled with the no_split_stack_attribute will
9410b57cec5SDimitry Andric   // include a .note.GNU-no-split-stack section.
9420b57cec5SDimitry Andric   if (name == ".note.GNU-no-split-stack") {
9430b57cec5SDimitry Andric     this->someNoSplitStack = true;
9440b57cec5SDimitry Andric     return &InputSection::discarded;
9450b57cec5SDimitry Andric   }
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
9480b57cec5SDimitry Andric   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
9490b57cec5SDimitry Andric   // sections. Drop those sections to avoid duplicate symbol errors.
9500b57cec5SDimitry Andric   // FIXME: This is glibc PR20543, we should remove this hack once that has been
9510b57cec5SDimitry Andric   // fixed for a while.
9520b57cec5SDimitry Andric   if (name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
9530b57cec5SDimitry Andric       name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
9540b57cec5SDimitry Andric     return &InputSection::discarded;
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric   // If we are creating a new .build-id section, strip existing .build-id
9570b57cec5SDimitry Andric   // sections so that the output won't have more than one .build-id.
9580b57cec5SDimitry Andric   // This is not usually a problem because input object files normally don't
9590b57cec5SDimitry Andric   // have .build-id sections, but you can create such files by
9600b57cec5SDimitry Andric   // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
9610b57cec5SDimitry Andric   if (name == ".note.gnu.build-id" && config->buildId != BuildIdKind::None)
9620b57cec5SDimitry Andric     return &InputSection::discarded;
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric   // The linker merges EH (exception handling) frames and creates a
9650b57cec5SDimitry Andric   // .eh_frame_hdr section for runtime. So we handle them with a special
9660b57cec5SDimitry Andric   // class. For relocatable outputs, they are just passed through.
9670b57cec5SDimitry Andric   if (name == ".eh_frame" && !config->relocatable)
9680b57cec5SDimitry Andric     return make<EhInputSection>(*this, sec, name);
9690b57cec5SDimitry Andric 
970*85868e8aSDimitry Andric   if (shouldMerge(sec, name))
9710b57cec5SDimitry Andric     return make<MergeInputSection>(*this, sec, name);
9720b57cec5SDimitry Andric   return make<InputSection>(*this, sec, name);
9730b57cec5SDimitry Andric }
9740b57cec5SDimitry Andric 
9750b57cec5SDimitry Andric template <class ELFT>
9760b57cec5SDimitry Andric StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &sec) {
9770b57cec5SDimitry Andric   return CHECK(getObj().getSectionName(&sec, sectionStringTable), this);
9780b57cec5SDimitry Andric }
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric // Initialize this->Symbols. this->Symbols is a parallel array as
9810b57cec5SDimitry Andric // its corresponding ELF symbol table.
9820b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
9830b57cec5SDimitry Andric   ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
9840b57cec5SDimitry Andric   this->symbols.resize(eSyms.size());
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric   // Our symbol table may have already been partially initialized
9870b57cec5SDimitry Andric   // because of LazyObjFile.
9880b57cec5SDimitry Andric   for (size_t i = 0, end = eSyms.size(); i != end; ++i)
9890b57cec5SDimitry Andric     if (!this->symbols[i] && eSyms[i].getBinding() != STB_LOCAL)
9900b57cec5SDimitry Andric       this->symbols[i] =
9910b57cec5SDimitry Andric           symtab->insert(CHECK(eSyms[i].getName(this->stringTable), this));
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric   // Fill this->Symbols. A symbol is either local or global.
9940b57cec5SDimitry Andric   for (size_t i = 0, end = eSyms.size(); i != end; ++i) {
9950b57cec5SDimitry Andric     const Elf_Sym &eSym = eSyms[i];
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric     // Read symbol attributes.
9980b57cec5SDimitry Andric     uint32_t secIdx = getSectionIndex(eSym);
9990b57cec5SDimitry Andric     if (secIdx >= this->sections.size())
10000b57cec5SDimitry Andric       fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric     InputSectionBase *sec = this->sections[secIdx];
10030b57cec5SDimitry Andric     uint8_t binding = eSym.getBinding();
10040b57cec5SDimitry Andric     uint8_t stOther = eSym.st_other;
10050b57cec5SDimitry Andric     uint8_t type = eSym.getType();
10060b57cec5SDimitry Andric     uint64_t value = eSym.st_value;
10070b57cec5SDimitry Andric     uint64_t size = eSym.st_size;
10080b57cec5SDimitry Andric     StringRefZ name = this->stringTable.data() + eSym.st_name;
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric     // Handle local symbols. Local symbols are not added to the symbol
10110b57cec5SDimitry Andric     // table because they are not visible from other object files. We
10120b57cec5SDimitry Andric     // allocate symbol instances and add their pointers to Symbols.
10130b57cec5SDimitry Andric     if (binding == STB_LOCAL) {
10140b57cec5SDimitry Andric       if (eSym.getType() == STT_FILE)
10150b57cec5SDimitry Andric         sourceFile = CHECK(eSym.getName(this->stringTable), this);
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric       if (this->stringTable.size() <= eSym.st_name)
10180b57cec5SDimitry Andric         fatal(toString(this) + ": invalid symbol name offset");
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric       if (eSym.st_shndx == SHN_UNDEF)
10210b57cec5SDimitry Andric         this->symbols[i] = make<Undefined>(this, name, binding, stOther, type);
10220b57cec5SDimitry Andric       else if (sec == &InputSection::discarded)
10230b57cec5SDimitry Andric         this->symbols[i] = make<Undefined>(this, name, binding, stOther, type,
10240b57cec5SDimitry Andric                                            /*DiscardedSecIdx=*/secIdx);
10250b57cec5SDimitry Andric       else
10260b57cec5SDimitry Andric         this->symbols[i] =
10270b57cec5SDimitry Andric             make<Defined>(this, name, binding, stOther, type, value, size, sec);
10280b57cec5SDimitry Andric       continue;
10290b57cec5SDimitry Andric     }
10300b57cec5SDimitry Andric 
10310b57cec5SDimitry Andric     // Handle global undefined symbols.
10320b57cec5SDimitry Andric     if (eSym.st_shndx == SHN_UNDEF) {
10330b57cec5SDimitry Andric       this->symbols[i]->resolve(Undefined{this, name, binding, stOther, type});
1034*85868e8aSDimitry Andric       this->symbols[i]->referenced = true;
10350b57cec5SDimitry Andric       continue;
10360b57cec5SDimitry Andric     }
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric     // Handle global common symbols.
10390b57cec5SDimitry Andric     if (eSym.st_shndx == SHN_COMMON) {
10400b57cec5SDimitry Andric       if (value == 0 || value >= UINT32_MAX)
10410b57cec5SDimitry Andric         fatal(toString(this) + ": common symbol '" + StringRef(name.data) +
10420b57cec5SDimitry Andric               "' has invalid alignment: " + Twine(value));
10430b57cec5SDimitry Andric       this->symbols[i]->resolve(
10440b57cec5SDimitry Andric           CommonSymbol{this, name, binding, stOther, type, value, size});
10450b57cec5SDimitry Andric       continue;
10460b57cec5SDimitry Andric     }
10470b57cec5SDimitry Andric 
10480b57cec5SDimitry Andric     // If a defined symbol is in a discarded section, handle it as if it
10490b57cec5SDimitry Andric     // were an undefined symbol. Such symbol doesn't comply with the
10500b57cec5SDimitry Andric     // standard, but in practice, a .eh_frame often directly refer
10510b57cec5SDimitry Andric     // COMDAT member sections, and if a comdat group is discarded, some
10520b57cec5SDimitry Andric     // defined symbol in a .eh_frame becomes dangling symbols.
10530b57cec5SDimitry Andric     if (sec == &InputSection::discarded) {
10540b57cec5SDimitry Andric       this->symbols[i]->resolve(
10550b57cec5SDimitry Andric           Undefined{this, name, binding, stOther, type, secIdx});
10560b57cec5SDimitry Andric       continue;
10570b57cec5SDimitry Andric     }
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric     // Handle global defined symbols.
10600b57cec5SDimitry Andric     if (binding == STB_GLOBAL || binding == STB_WEAK ||
10610b57cec5SDimitry Andric         binding == STB_GNU_UNIQUE) {
10620b57cec5SDimitry Andric       this->symbols[i]->resolve(
10630b57cec5SDimitry Andric           Defined{this, name, binding, stOther, type, value, size, sec});
10640b57cec5SDimitry Andric       continue;
10650b57cec5SDimitry Andric     }
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric     fatal(toString(this) + ": unexpected binding: " + Twine((int)binding));
10680b57cec5SDimitry Andric   }
10690b57cec5SDimitry Andric }
10700b57cec5SDimitry Andric 
10710b57cec5SDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&file)
10720b57cec5SDimitry Andric     : InputFile(ArchiveKind, file->getMemoryBufferRef()),
10730b57cec5SDimitry Andric       file(std::move(file)) {}
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric void ArchiveFile::parse() {
10760b57cec5SDimitry Andric   for (const Archive::Symbol &sym : file->symbols())
10770b57cec5SDimitry Andric     symtab->addSymbol(LazyArchive{*this, sym});
10780b57cec5SDimitry Andric }
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric // Returns a buffer pointing to a member file containing a given symbol.
10810b57cec5SDimitry Andric void ArchiveFile::fetch(const Archive::Symbol &sym) {
10820b57cec5SDimitry Andric   Archive::Child c =
10830b57cec5SDimitry Andric       CHECK(sym.getMember(), toString(this) +
10840b57cec5SDimitry Andric                                  ": could not get the member for symbol " +
10850b57cec5SDimitry Andric                                  toELFString(sym));
10860b57cec5SDimitry Andric 
10870b57cec5SDimitry Andric   if (!seen.insert(c.getChildOffset()).second)
10880b57cec5SDimitry Andric     return;
10890b57cec5SDimitry Andric 
10900b57cec5SDimitry Andric   MemoryBufferRef mb =
10910b57cec5SDimitry Andric       CHECK(c.getMemoryBufferRef(),
10920b57cec5SDimitry Andric             toString(this) +
10930b57cec5SDimitry Andric                 ": could not get the buffer for the member defining symbol " +
10940b57cec5SDimitry Andric                 toELFString(sym));
10950b57cec5SDimitry Andric 
10960b57cec5SDimitry Andric   if (tar && c.getParent()->isThin())
10970b57cec5SDimitry Andric     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
10980b57cec5SDimitry Andric 
10990b57cec5SDimitry Andric   InputFile *file = createObjectFile(
11000b57cec5SDimitry Andric       mb, getName(), c.getParent()->isThin() ? 0 : c.getChildOffset());
11010b57cec5SDimitry Andric   file->groupId = groupId;
11020b57cec5SDimitry Andric   parseFile(file);
11030b57cec5SDimitry Andric }
11040b57cec5SDimitry Andric 
11050b57cec5SDimitry Andric unsigned SharedFile::vernauxNum;
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric // Parse the version definitions in the object file if present, and return a
11080b57cec5SDimitry Andric // vector whose nth element contains a pointer to the Elf_Verdef for version
11090b57cec5SDimitry Andric // identifier n. Version identifiers that are not definitions map to nullptr.
11100b57cec5SDimitry Andric template <typename ELFT>
11110b57cec5SDimitry Andric static std::vector<const void *> parseVerdefs(const uint8_t *base,
11120b57cec5SDimitry Andric                                               const typename ELFT::Shdr *sec) {
11130b57cec5SDimitry Andric   if (!sec)
11140b57cec5SDimitry Andric     return {};
11150b57cec5SDimitry Andric 
11160b57cec5SDimitry Andric   // We cannot determine the largest verdef identifier without inspecting
11170b57cec5SDimitry Andric   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
11180b57cec5SDimitry Andric   // sequentially starting from 1, so we predict that the largest identifier
11190b57cec5SDimitry Andric   // will be verdefCount.
11200b57cec5SDimitry Andric   unsigned verdefCount = sec->sh_info;
11210b57cec5SDimitry Andric   std::vector<const void *> verdefs(verdefCount + 1);
11220b57cec5SDimitry Andric 
11230b57cec5SDimitry Andric   // Build the Verdefs array by following the chain of Elf_Verdef objects
11240b57cec5SDimitry Andric   // from the start of the .gnu.version_d section.
11250b57cec5SDimitry Andric   const uint8_t *verdef = base + sec->sh_offset;
11260b57cec5SDimitry Andric   for (unsigned i = 0; i != verdefCount; ++i) {
11270b57cec5SDimitry Andric     auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
11280b57cec5SDimitry Andric     verdef += curVerdef->vd_next;
11290b57cec5SDimitry Andric     unsigned verdefIndex = curVerdef->vd_ndx;
11300b57cec5SDimitry Andric     verdefs.resize(verdefIndex + 1);
11310b57cec5SDimitry Andric     verdefs[verdefIndex] = curVerdef;
11320b57cec5SDimitry Andric   }
11330b57cec5SDimitry Andric   return verdefs;
11340b57cec5SDimitry Andric }
11350b57cec5SDimitry Andric 
11360b57cec5SDimitry Andric // We do not usually care about alignments of data in shared object
11370b57cec5SDimitry Andric // files because the loader takes care of it. However, if we promote a
11380b57cec5SDimitry Andric // DSO symbol to point to .bss due to copy relocation, we need to keep
11390b57cec5SDimitry Andric // the original alignment requirements. We infer it in this function.
11400b57cec5SDimitry Andric template <typename ELFT>
11410b57cec5SDimitry Andric static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
11420b57cec5SDimitry Andric                              const typename ELFT::Sym &sym) {
11430b57cec5SDimitry Andric   uint64_t ret = UINT64_MAX;
11440b57cec5SDimitry Andric   if (sym.st_value)
11450b57cec5SDimitry Andric     ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
11460b57cec5SDimitry Andric   if (0 < sym.st_shndx && sym.st_shndx < sections.size())
11470b57cec5SDimitry Andric     ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
11480b57cec5SDimitry Andric   return (ret > UINT32_MAX) ? 0 : ret;
11490b57cec5SDimitry Andric }
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric // Fully parse the shared object file.
11520b57cec5SDimitry Andric //
11530b57cec5SDimitry Andric // This function parses symbol versions. If a DSO has version information,
11540b57cec5SDimitry Andric // the file has a ".gnu.version_d" section which contains symbol version
11550b57cec5SDimitry Andric // definitions. Each symbol is associated to one version through a table in
11560b57cec5SDimitry Andric // ".gnu.version" section. That table is a parallel array for the symbol
11570b57cec5SDimitry Andric // table, and each table entry contains an index in ".gnu.version_d".
11580b57cec5SDimitry Andric //
11590b57cec5SDimitry Andric // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
11600b57cec5SDimitry Andric // VER_NDX_GLOBAL. There's no table entry for these special versions in
11610b57cec5SDimitry Andric // ".gnu.version_d".
11620b57cec5SDimitry Andric //
11630b57cec5SDimitry Andric // The file format for symbol versioning is perhaps a bit more complicated
11640b57cec5SDimitry Andric // than necessary, but you can easily understand the code if you wrap your
11650b57cec5SDimitry Andric // head around the data structure described above.
11660b57cec5SDimitry Andric template <class ELFT> void SharedFile::parse() {
11670b57cec5SDimitry Andric   using Elf_Dyn = typename ELFT::Dyn;
11680b57cec5SDimitry Andric   using Elf_Shdr = typename ELFT::Shdr;
11690b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
11700b57cec5SDimitry Andric   using Elf_Verdef = typename ELFT::Verdef;
11710b57cec5SDimitry Andric   using Elf_Versym = typename ELFT::Versym;
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric   ArrayRef<Elf_Dyn> dynamicTags;
11740b57cec5SDimitry Andric   const ELFFile<ELFT> obj = this->getObj<ELFT>();
11750b57cec5SDimitry Andric   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
11760b57cec5SDimitry Andric 
11770b57cec5SDimitry Andric   const Elf_Shdr *versymSec = nullptr;
11780b57cec5SDimitry Andric   const Elf_Shdr *verdefSec = nullptr;
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
11810b57cec5SDimitry Andric   for (const Elf_Shdr &sec : sections) {
11820b57cec5SDimitry Andric     switch (sec.sh_type) {
11830b57cec5SDimitry Andric     default:
11840b57cec5SDimitry Andric       continue;
11850b57cec5SDimitry Andric     case SHT_DYNAMIC:
11860b57cec5SDimitry Andric       dynamicTags =
11870b57cec5SDimitry Andric           CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(&sec), this);
11880b57cec5SDimitry Andric       break;
11890b57cec5SDimitry Andric     case SHT_GNU_versym:
11900b57cec5SDimitry Andric       versymSec = &sec;
11910b57cec5SDimitry Andric       break;
11920b57cec5SDimitry Andric     case SHT_GNU_verdef:
11930b57cec5SDimitry Andric       verdefSec = &sec;
11940b57cec5SDimitry Andric       break;
11950b57cec5SDimitry Andric     }
11960b57cec5SDimitry Andric   }
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric   if (versymSec && numELFSyms == 0) {
11990b57cec5SDimitry Andric     error("SHT_GNU_versym should be associated with symbol table");
12000b57cec5SDimitry Andric     return;
12010b57cec5SDimitry Andric   }
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   // Search for a DT_SONAME tag to initialize this->soName.
12040b57cec5SDimitry Andric   for (const Elf_Dyn &dyn : dynamicTags) {
12050b57cec5SDimitry Andric     if (dyn.d_tag == DT_NEEDED) {
12060b57cec5SDimitry Andric       uint64_t val = dyn.getVal();
12070b57cec5SDimitry Andric       if (val >= this->stringTable.size())
12080b57cec5SDimitry Andric         fatal(toString(this) + ": invalid DT_NEEDED entry");
12090b57cec5SDimitry Andric       dtNeeded.push_back(this->stringTable.data() + val);
12100b57cec5SDimitry Andric     } else if (dyn.d_tag == DT_SONAME) {
12110b57cec5SDimitry Andric       uint64_t val = dyn.getVal();
12120b57cec5SDimitry Andric       if (val >= this->stringTable.size())
12130b57cec5SDimitry Andric         fatal(toString(this) + ": invalid DT_SONAME entry");
12140b57cec5SDimitry Andric       soName = this->stringTable.data() + val;
12150b57cec5SDimitry Andric     }
12160b57cec5SDimitry Andric   }
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric   // DSOs are uniquified not by filename but by soname.
12190b57cec5SDimitry Andric   DenseMap<StringRef, SharedFile *>::iterator it;
12200b57cec5SDimitry Andric   bool wasInserted;
12210b57cec5SDimitry Andric   std::tie(it, wasInserted) = symtab->soNames.try_emplace(soName, this);
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric   // If a DSO appears more than once on the command line with and without
12240b57cec5SDimitry Andric   // --as-needed, --no-as-needed takes precedence over --as-needed because a
12250b57cec5SDimitry Andric   // user can add an extra DSO with --no-as-needed to force it to be added to
12260b57cec5SDimitry Andric   // the dependency list.
12270b57cec5SDimitry Andric   it->second->isNeeded |= isNeeded;
12280b57cec5SDimitry Andric   if (!wasInserted)
12290b57cec5SDimitry Andric     return;
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric   sharedFiles.push_back(this);
12320b57cec5SDimitry Andric 
12330b57cec5SDimitry Andric   verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric   // Parse ".gnu.version" section which is a parallel array for the symbol
12360b57cec5SDimitry Andric   // table. If a given file doesn't have a ".gnu.version" section, we use
12370b57cec5SDimitry Andric   // VER_NDX_GLOBAL.
12380b57cec5SDimitry Andric   size_t size = numELFSyms - firstGlobal;
12390b57cec5SDimitry Andric   std::vector<uint32_t> versyms(size, VER_NDX_GLOBAL);
12400b57cec5SDimitry Andric   if (versymSec) {
12410b57cec5SDimitry Andric     ArrayRef<Elf_Versym> versym =
12420b57cec5SDimitry Andric         CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(versymSec),
12430b57cec5SDimitry Andric               this)
12440b57cec5SDimitry Andric             .slice(firstGlobal);
12450b57cec5SDimitry Andric     for (size_t i = 0; i < size; ++i)
12460b57cec5SDimitry Andric       versyms[i] = versym[i].vs_index;
12470b57cec5SDimitry Andric   }
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric   // System libraries can have a lot of symbols with versions. Using a
12500b57cec5SDimitry Andric   // fixed buffer for computing the versions name (foo@ver) can save a
12510b57cec5SDimitry Andric   // lot of allocations.
12520b57cec5SDimitry Andric   SmallString<0> versionedNameBuffer;
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric   // Add symbols to the symbol table.
12550b57cec5SDimitry Andric   ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
12560b57cec5SDimitry Andric   for (size_t i = 0; i < syms.size(); ++i) {
12570b57cec5SDimitry Andric     const Elf_Sym &sym = syms[i];
12580b57cec5SDimitry Andric 
12590b57cec5SDimitry Andric     // ELF spec requires that all local symbols precede weak or global
12600b57cec5SDimitry Andric     // symbols in each symbol table, and the index of first non-local symbol
12610b57cec5SDimitry Andric     // is stored to sh_info. If a local symbol appears after some non-local
12620b57cec5SDimitry Andric     // symbol, that's a violation of the spec.
12630b57cec5SDimitry Andric     StringRef name = CHECK(sym.getName(this->stringTable), this);
12640b57cec5SDimitry Andric     if (sym.getBinding() == STB_LOCAL) {
12650b57cec5SDimitry Andric       warn("found local symbol '" + name +
12660b57cec5SDimitry Andric            "' in global part of symbol table in file " + toString(this));
12670b57cec5SDimitry Andric       continue;
12680b57cec5SDimitry Andric     }
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric     if (sym.isUndefined()) {
12710b57cec5SDimitry Andric       Symbol *s = symtab->addSymbol(
12720b57cec5SDimitry Andric           Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
12730b57cec5SDimitry Andric       s->exportDynamic = true;
12740b57cec5SDimitry Andric       continue;
12750b57cec5SDimitry Andric     }
12760b57cec5SDimitry Andric 
12770b57cec5SDimitry Andric     // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
12780b57cec5SDimitry Andric     // assigns VER_NDX_LOCAL to this section global symbol. Here is a
12790b57cec5SDimitry Andric     // workaround for this bug.
12800b57cec5SDimitry Andric     uint32_t idx = versyms[i] & ~VERSYM_HIDDEN;
12810b57cec5SDimitry Andric     if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL &&
12820b57cec5SDimitry Andric         name == "_gp_disp")
12830b57cec5SDimitry Andric       continue;
12840b57cec5SDimitry Andric 
12850b57cec5SDimitry Andric     uint32_t alignment = getAlignment<ELFT>(sections, sym);
12860b57cec5SDimitry Andric     if (!(versyms[i] & VERSYM_HIDDEN)) {
12870b57cec5SDimitry Andric       symtab->addSymbol(SharedSymbol{*this, name, sym.getBinding(),
12880b57cec5SDimitry Andric                                      sym.st_other, sym.getType(), sym.st_value,
12890b57cec5SDimitry Andric                                      sym.st_size, alignment, idx});
12900b57cec5SDimitry Andric     }
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric     // Also add the symbol with the versioned name to handle undefined symbols
12930b57cec5SDimitry Andric     // with explicit versions.
12940b57cec5SDimitry Andric     if (idx == VER_NDX_GLOBAL)
12950b57cec5SDimitry Andric       continue;
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric     if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) {
12980b57cec5SDimitry Andric       error("corrupt input file: version definition index " + Twine(idx) +
12990b57cec5SDimitry Andric             " for symbol " + name + " is out of bounds\n>>> defined in " +
13000b57cec5SDimitry Andric             toString(this));
13010b57cec5SDimitry Andric       continue;
13020b57cec5SDimitry Andric     }
13030b57cec5SDimitry Andric 
13040b57cec5SDimitry Andric     StringRef verName =
13050b57cec5SDimitry Andric         this->stringTable.data() +
13060b57cec5SDimitry Andric         reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
13070b57cec5SDimitry Andric     versionedNameBuffer.clear();
13080b57cec5SDimitry Andric     name = (name + "@" + verName).toStringRef(versionedNameBuffer);
13090b57cec5SDimitry Andric     symtab->addSymbol(SharedSymbol{*this, saver.save(name), sym.getBinding(),
13100b57cec5SDimitry Andric                                    sym.st_other, sym.getType(), sym.st_value,
13110b57cec5SDimitry Andric                                    sym.st_size, alignment, idx});
13120b57cec5SDimitry Andric   }
13130b57cec5SDimitry Andric }
13140b57cec5SDimitry Andric 
13150b57cec5SDimitry Andric static ELFKind getBitcodeELFKind(const Triple &t) {
13160b57cec5SDimitry Andric   if (t.isLittleEndian())
13170b57cec5SDimitry Andric     return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
13180b57cec5SDimitry Andric   return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
13190b57cec5SDimitry Andric }
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric static uint8_t getBitcodeMachineKind(StringRef path, const Triple &t) {
13220b57cec5SDimitry Andric   switch (t.getArch()) {
13230b57cec5SDimitry Andric   case Triple::aarch64:
13240b57cec5SDimitry Andric     return EM_AARCH64;
13250b57cec5SDimitry Andric   case Triple::amdgcn:
13260b57cec5SDimitry Andric   case Triple::r600:
13270b57cec5SDimitry Andric     return EM_AMDGPU;
13280b57cec5SDimitry Andric   case Triple::arm:
13290b57cec5SDimitry Andric   case Triple::thumb:
13300b57cec5SDimitry Andric     return EM_ARM;
13310b57cec5SDimitry Andric   case Triple::avr:
13320b57cec5SDimitry Andric     return EM_AVR;
13330b57cec5SDimitry Andric   case Triple::mips:
13340b57cec5SDimitry Andric   case Triple::mipsel:
13350b57cec5SDimitry Andric   case Triple::mips64:
13360b57cec5SDimitry Andric   case Triple::mips64el:
13370b57cec5SDimitry Andric     return EM_MIPS;
13380b57cec5SDimitry Andric   case Triple::msp430:
13390b57cec5SDimitry Andric     return EM_MSP430;
13400b57cec5SDimitry Andric   case Triple::ppc:
13410b57cec5SDimitry Andric     return EM_PPC;
13420b57cec5SDimitry Andric   case Triple::ppc64:
13430b57cec5SDimitry Andric   case Triple::ppc64le:
13440b57cec5SDimitry Andric     return EM_PPC64;
13450b57cec5SDimitry Andric   case Triple::riscv32:
13460b57cec5SDimitry Andric   case Triple::riscv64:
13470b57cec5SDimitry Andric     return EM_RISCV;
13480b57cec5SDimitry Andric   case Triple::x86:
13490b57cec5SDimitry Andric     return t.isOSIAMCU() ? EM_IAMCU : EM_386;
13500b57cec5SDimitry Andric   case Triple::x86_64:
13510b57cec5SDimitry Andric     return EM_X86_64;
13520b57cec5SDimitry Andric   default:
13530b57cec5SDimitry Andric     error(path + ": could not infer e_machine from bitcode target triple " +
13540b57cec5SDimitry Andric           t.str());
13550b57cec5SDimitry Andric     return EM_NONE;
13560b57cec5SDimitry Andric   }
13570b57cec5SDimitry Andric }
13580b57cec5SDimitry Andric 
13590b57cec5SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
13600b57cec5SDimitry Andric                          uint64_t offsetInArchive)
13610b57cec5SDimitry Andric     : InputFile(BitcodeKind, mb) {
13620b57cec5SDimitry Andric   this->archiveName = archiveName;
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric   std::string path = mb.getBufferIdentifier().str();
13650b57cec5SDimitry Andric   if (config->thinLTOIndexOnly)
13660b57cec5SDimitry Andric     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
13670b57cec5SDimitry Andric 
13680b57cec5SDimitry Andric   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
13690b57cec5SDimitry Andric   // name. If two archives define two members with the same name, this
13700b57cec5SDimitry Andric   // causes a collision which result in only one of the objects being taken
13710b57cec5SDimitry Andric   // into consideration at LTO time (which very likely causes undefined
13720b57cec5SDimitry Andric   // symbols later in the link stage). So we append file offset to make
13730b57cec5SDimitry Andric   // filename unique.
13740b57cec5SDimitry Andric   StringRef name = archiveName.empty()
13750b57cec5SDimitry Andric                        ? saver.save(path)
13760b57cec5SDimitry Andric                        : saver.save(archiveName + "(" + path + " at " +
13770b57cec5SDimitry Andric                                     utostr(offsetInArchive) + ")");
13780b57cec5SDimitry Andric   MemoryBufferRef mbref(mb.getBuffer(), name);
13790b57cec5SDimitry Andric 
13800b57cec5SDimitry Andric   obj = CHECK(lto::InputFile::create(mbref), this);
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric   Triple t(obj->getTargetTriple());
13830b57cec5SDimitry Andric   ekind = getBitcodeELFKind(t);
13840b57cec5SDimitry Andric   emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t);
13850b57cec5SDimitry Andric }
13860b57cec5SDimitry Andric 
13870b57cec5SDimitry Andric static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
13880b57cec5SDimitry Andric   switch (gvVisibility) {
13890b57cec5SDimitry Andric   case GlobalValue::DefaultVisibility:
13900b57cec5SDimitry Andric     return STV_DEFAULT;
13910b57cec5SDimitry Andric   case GlobalValue::HiddenVisibility:
13920b57cec5SDimitry Andric     return STV_HIDDEN;
13930b57cec5SDimitry Andric   case GlobalValue::ProtectedVisibility:
13940b57cec5SDimitry Andric     return STV_PROTECTED;
13950b57cec5SDimitry Andric   }
13960b57cec5SDimitry Andric   llvm_unreachable("unknown visibility");
13970b57cec5SDimitry Andric }
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric template <class ELFT>
14000b57cec5SDimitry Andric static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
14010b57cec5SDimitry Andric                                    const lto::InputFile::Symbol &objSym,
14020b57cec5SDimitry Andric                                    BitcodeFile &f) {
14030b57cec5SDimitry Andric   StringRef name = saver.save(objSym.getName());
14040b57cec5SDimitry Andric   uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
14050b57cec5SDimitry Andric   uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
14060b57cec5SDimitry Andric   uint8_t visibility = mapVisibility(objSym.getVisibility());
14070b57cec5SDimitry Andric   bool canOmitFromDynSym = objSym.canBeOmittedFromSymbolTable();
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric   int c = objSym.getComdatIndex();
14100b57cec5SDimitry Andric   if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) {
1411*85868e8aSDimitry Andric     Undefined newSym(&f, name, binding, visibility, type);
14120b57cec5SDimitry Andric     if (canOmitFromDynSym)
1413*85868e8aSDimitry Andric       newSym.exportDynamic = false;
1414*85868e8aSDimitry Andric     Symbol *ret = symtab->addSymbol(newSym);
1415*85868e8aSDimitry Andric     ret->referenced = true;
1416*85868e8aSDimitry Andric     return ret;
14170b57cec5SDimitry Andric   }
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric   if (objSym.isCommon())
14200b57cec5SDimitry Andric     return symtab->addSymbol(
14210b57cec5SDimitry Andric         CommonSymbol{&f, name, binding, visibility, STT_OBJECT,
14220b57cec5SDimitry Andric                      objSym.getCommonAlignment(), objSym.getCommonSize()});
14230b57cec5SDimitry Andric 
1424*85868e8aSDimitry Andric   Defined newSym(&f, name, binding, visibility, type, 0, 0, nullptr);
14250b57cec5SDimitry Andric   if (canOmitFromDynSym)
1426*85868e8aSDimitry Andric     newSym.exportDynamic = false;
1427*85868e8aSDimitry Andric   return symtab->addSymbol(newSym);
14280b57cec5SDimitry Andric }
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric template <class ELFT> void BitcodeFile::parse() {
14310b57cec5SDimitry Andric   std::vector<bool> keptComdats;
14320b57cec5SDimitry Andric   for (StringRef s : obj->getComdatTable())
14330b57cec5SDimitry Andric     keptComdats.push_back(
14340b57cec5SDimitry Andric         symtab->comdatGroups.try_emplace(CachedHashStringRef(s), this).second);
14350b57cec5SDimitry Andric 
14360b57cec5SDimitry Andric   for (const lto::InputFile::Symbol &objSym : obj->symbols())
14370b57cec5SDimitry Andric     symbols.push_back(createBitcodeSymbol<ELFT>(keptComdats, objSym, *this));
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric   for (auto l : obj->getDependentLibraries())
14400b57cec5SDimitry Andric     addDependentLibrary(l, this);
14410b57cec5SDimitry Andric }
14420b57cec5SDimitry Andric 
14430b57cec5SDimitry Andric void BinaryFile::parse() {
14440b57cec5SDimitry Andric   ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
14450b57cec5SDimitry Andric   auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
14460b57cec5SDimitry Andric                                      8, data, ".data");
14470b57cec5SDimitry Andric   sections.push_back(section);
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric   // For each input file foo that is embedded to a result as a binary
14500b57cec5SDimitry Andric   // blob, we define _binary_foo_{start,end,size} symbols, so that
14510b57cec5SDimitry Andric   // user programs can access blobs by name. Non-alphanumeric
14520b57cec5SDimitry Andric   // characters in a filename are replaced with underscore.
14530b57cec5SDimitry Andric   std::string s = "_binary_" + mb.getBufferIdentifier().str();
14540b57cec5SDimitry Andric   for (size_t i = 0; i < s.size(); ++i)
14550b57cec5SDimitry Andric     if (!isAlnum(s[i]))
14560b57cec5SDimitry Andric       s[i] = '_';
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric   symtab->addSymbol(Defined{nullptr, saver.save(s + "_start"), STB_GLOBAL,
14590b57cec5SDimitry Andric                             STV_DEFAULT, STT_OBJECT, 0, 0, section});
14600b57cec5SDimitry Andric   symtab->addSymbol(Defined{nullptr, saver.save(s + "_end"), STB_GLOBAL,
14610b57cec5SDimitry Andric                             STV_DEFAULT, STT_OBJECT, data.size(), 0, section});
14620b57cec5SDimitry Andric   symtab->addSymbol(Defined{nullptr, saver.save(s + "_size"), STB_GLOBAL,
14630b57cec5SDimitry Andric                             STV_DEFAULT, STT_OBJECT, data.size(), 0, nullptr});
14640b57cec5SDimitry Andric }
14650b57cec5SDimitry Andric 
1466*85868e8aSDimitry Andric InputFile *createObjectFile(MemoryBufferRef mb, StringRef archiveName,
14670b57cec5SDimitry Andric                             uint64_t offsetInArchive) {
14680b57cec5SDimitry Andric   if (isBitcode(mb))
14690b57cec5SDimitry Andric     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
14700b57cec5SDimitry Andric 
14710b57cec5SDimitry Andric   switch (getELFKind(mb, archiveName)) {
14720b57cec5SDimitry Andric   case ELF32LEKind:
14730b57cec5SDimitry Andric     return make<ObjFile<ELF32LE>>(mb, archiveName);
14740b57cec5SDimitry Andric   case ELF32BEKind:
14750b57cec5SDimitry Andric     return make<ObjFile<ELF32BE>>(mb, archiveName);
14760b57cec5SDimitry Andric   case ELF64LEKind:
14770b57cec5SDimitry Andric     return make<ObjFile<ELF64LE>>(mb, archiveName);
14780b57cec5SDimitry Andric   case ELF64BEKind:
14790b57cec5SDimitry Andric     return make<ObjFile<ELF64BE>>(mb, archiveName);
14800b57cec5SDimitry Andric   default:
14810b57cec5SDimitry Andric     llvm_unreachable("getELFKind");
14820b57cec5SDimitry Andric   }
14830b57cec5SDimitry Andric }
14840b57cec5SDimitry Andric 
14850b57cec5SDimitry Andric void LazyObjFile::fetch() {
14860b57cec5SDimitry Andric   if (mb.getBuffer().empty())
14870b57cec5SDimitry Andric     return;
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric   InputFile *file = createObjectFile(mb, archiveName, offsetInArchive);
14900b57cec5SDimitry Andric   file->groupId = groupId;
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric   mb = {};
14930b57cec5SDimitry Andric 
14940b57cec5SDimitry Andric   // Copy symbol vector so that the new InputFile doesn't have to
14950b57cec5SDimitry Andric   // insert the same defined symbols to the symbol table again.
14960b57cec5SDimitry Andric   file->symbols = std::move(symbols);
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric   parseFile(file);
14990b57cec5SDimitry Andric }
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric template <class ELFT> void LazyObjFile::parse() {
15020b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
15030b57cec5SDimitry Andric 
15040b57cec5SDimitry Andric   // A lazy object file wraps either a bitcode file or an ELF file.
15050b57cec5SDimitry Andric   if (isBitcode(this->mb)) {
15060b57cec5SDimitry Andric     std::unique_ptr<lto::InputFile> obj =
15070b57cec5SDimitry Andric         CHECK(lto::InputFile::create(this->mb), this);
15080b57cec5SDimitry Andric     for (const lto::InputFile::Symbol &sym : obj->symbols()) {
15090b57cec5SDimitry Andric       if (sym.isUndefined())
15100b57cec5SDimitry Andric         continue;
15110b57cec5SDimitry Andric       symtab->addSymbol(LazyObject{*this, saver.save(sym.getName())});
15120b57cec5SDimitry Andric     }
15130b57cec5SDimitry Andric     return;
15140b57cec5SDimitry Andric   }
15150b57cec5SDimitry Andric 
15160b57cec5SDimitry Andric   if (getELFKind(this->mb, archiveName) != config->ekind) {
15170b57cec5SDimitry Andric     error("incompatible file: " + this->mb.getBufferIdentifier());
15180b57cec5SDimitry Andric     return;
15190b57cec5SDimitry Andric   }
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric   // Find a symbol table.
15220b57cec5SDimitry Andric   ELFFile<ELFT> obj = check(ELFFile<ELFT>::create(mb.getBuffer()));
15230b57cec5SDimitry Andric   ArrayRef<typename ELFT::Shdr> sections = CHECK(obj.sections(), this);
15240b57cec5SDimitry Andric 
15250b57cec5SDimitry Andric   for (const typename ELFT::Shdr &sec : sections) {
15260b57cec5SDimitry Andric     if (sec.sh_type != SHT_SYMTAB)
15270b57cec5SDimitry Andric       continue;
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric     // A symbol table is found.
15300b57cec5SDimitry Andric     ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(&sec), this);
15310b57cec5SDimitry Andric     uint32_t firstGlobal = sec.sh_info;
15320b57cec5SDimitry Andric     StringRef strtab = CHECK(obj.getStringTableForSymtab(sec, sections), this);
15330b57cec5SDimitry Andric     this->symbols.resize(eSyms.size());
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric     // Get existing symbols or insert placeholder symbols.
15360b57cec5SDimitry Andric     for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
15370b57cec5SDimitry Andric       if (eSyms[i].st_shndx != SHN_UNDEF)
15380b57cec5SDimitry Andric         this->symbols[i] = symtab->insert(CHECK(eSyms[i].getName(strtab), this));
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric     // Replace existing symbols with LazyObject symbols.
15410b57cec5SDimitry Andric     //
15420b57cec5SDimitry Andric     // resolve() may trigger this->fetch() if an existing symbol is an
15430b57cec5SDimitry Andric     // undefined symbol. If that happens, this LazyObjFile has served
15440b57cec5SDimitry Andric     // its purpose, and we can exit from the loop early.
15450b57cec5SDimitry Andric     for (Symbol *sym : this->symbols) {
15460b57cec5SDimitry Andric       if (!sym)
15470b57cec5SDimitry Andric         continue;
15480b57cec5SDimitry Andric       sym->resolve(LazyObject{*this, sym->getName()});
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric       // MemoryBuffer is emptied if this file is instantiated as ObjFile.
15510b57cec5SDimitry Andric       if (mb.getBuffer().empty())
15520b57cec5SDimitry Andric         return;
15530b57cec5SDimitry Andric     }
15540b57cec5SDimitry Andric     return;
15550b57cec5SDimitry Andric   }
15560b57cec5SDimitry Andric }
15570b57cec5SDimitry Andric 
1558*85868e8aSDimitry Andric std::string replaceThinLTOSuffix(StringRef path) {
15590b57cec5SDimitry Andric   StringRef suffix = config->thinLTOObjectSuffixReplace.first;
15600b57cec5SDimitry Andric   StringRef repl = config->thinLTOObjectSuffixReplace.second;
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric   if (path.consume_back(suffix))
15630b57cec5SDimitry Andric     return (path + repl).str();
15640b57cec5SDimitry Andric   return path;
15650b57cec5SDimitry Andric }
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32LE>();
15680b57cec5SDimitry Andric template void BitcodeFile::parse<ELF32BE>();
15690b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64LE>();
15700b57cec5SDimitry Andric template void BitcodeFile::parse<ELF64BE>();
15710b57cec5SDimitry Andric 
15720b57cec5SDimitry Andric template void LazyObjFile::parse<ELF32LE>();
15730b57cec5SDimitry Andric template void LazyObjFile::parse<ELF32BE>();
15740b57cec5SDimitry Andric template void LazyObjFile::parse<ELF64LE>();
15750b57cec5SDimitry Andric template void LazyObjFile::parse<ELF64BE>();
15760b57cec5SDimitry Andric 
1577*85868e8aSDimitry Andric template class ObjFile<ELF32LE>;
1578*85868e8aSDimitry Andric template class ObjFile<ELF32BE>;
1579*85868e8aSDimitry Andric template class ObjFile<ELF64LE>;
1580*85868e8aSDimitry Andric template class ObjFile<ELF64BE>;
15810b57cec5SDimitry Andric 
15820b57cec5SDimitry Andric template void SharedFile::parse<ELF32LE>();
15830b57cec5SDimitry Andric template void SharedFile::parse<ELF32BE>();
15840b57cec5SDimitry Andric template void SharedFile::parse<ELF64LE>();
15850b57cec5SDimitry Andric template void SharedFile::parse<ELF64BE>();
1586*85868e8aSDimitry Andric 
1587*85868e8aSDimitry Andric } // namespace elf
1588*85868e8aSDimitry Andric } // namespace lld
1589