xref: /freebsd/contrib/llvm-project/lld/ELF/InputFiles.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
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"
1081ad6265SDimitry Andric #include "Config.h"
1181ad6265SDimitry Andric #include "DWARF.h"
120b57cec5SDimitry Andric #include "Driver.h"
130b57cec5SDimitry Andric #include "InputSection.h"
140b57cec5SDimitry Andric #include "LinkerScript.h"
150b57cec5SDimitry Andric #include "SymbolTable.h"
160b57cec5SDimitry Andric #include "Symbols.h"
170b57cec5SDimitry Andric #include "SyntheticSections.h"
181fd87a68SDimitry Andric #include "Target.h"
1904eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h"
20480093f4SDimitry Andric #include "lld/Common/DWARF.h"
2181ad6265SDimitry Andric #include "llvm/ADT/CachedHashString.h"
220b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
230b57cec5SDimitry Andric #include "llvm/LTO/LTO.h"
2481ad6265SDimitry Andric #include "llvm/Object/IRObjectFile.h"
250b57cec5SDimitry Andric #include "llvm/Support/ARMAttributeParser.h"
260b57cec5SDimitry Andric #include "llvm/Support/ARMBuildAttributes.h"
270b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
2881ad6265SDimitry Andric #include "llvm/Support/FileSystem.h"
290b57cec5SDimitry Andric #include "llvm/Support/Path.h"
30e8d8bef9SDimitry Andric #include "llvm/Support/RISCVAttributeParser.h"
310b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h"
320b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric using namespace llvm;
350b57cec5SDimitry Andric using namespace llvm::ELF;
360b57cec5SDimitry Andric using namespace llvm::object;
370b57cec5SDimitry Andric using namespace llvm::sys;
380b57cec5SDimitry Andric using namespace llvm::sys::fs;
390b57cec5SDimitry Andric using namespace llvm::support::endian;
405ffd83dbSDimitry Andric using namespace lld;
415ffd83dbSDimitry Andric using namespace lld::elf;
420b57cec5SDimitry Andric 
435ffd83dbSDimitry Andric bool InputFile::isInGroup;
445ffd83dbSDimitry Andric uint32_t InputFile::nextGroupId;
455ffd83dbSDimitry Andric 
465ffd83dbSDimitry Andric std::unique_ptr<TarWriter> elf::tar;
475ffd83dbSDimitry Andric 
4885868e8aSDimitry Andric // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
495ffd83dbSDimitry Andric std::string lld::toString(const InputFile *f) {
50*bdd1243dSDimitry Andric   static std::mutex mu;
5185868e8aSDimitry Andric   if (!f)
5285868e8aSDimitry Andric     return "<internal>";
530b57cec5SDimitry Andric 
54*bdd1243dSDimitry Andric   {
55*bdd1243dSDimitry Andric     std::lock_guard<std::mutex> lock(mu);
5685868e8aSDimitry Andric     if (f->toStringCache.empty()) {
5785868e8aSDimitry Andric       if (f->archiveName.empty())
580eae32dcSDimitry Andric         f->toStringCache = f->getName();
5985868e8aSDimitry Andric       else
600eae32dcSDimitry Andric         (f->archiveName + "(" + f->getName() + ")").toVector(f->toStringCache);
6185868e8aSDimitry Andric     }
62*bdd1243dSDimitry Andric   }
630eae32dcSDimitry Andric   return std::string(f->toStringCache);
6485868e8aSDimitry Andric }
6585868e8aSDimitry Andric 
660b57cec5SDimitry Andric static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) {
670b57cec5SDimitry Andric   unsigned char size;
680b57cec5SDimitry Andric   unsigned char endian;
690b57cec5SDimitry Andric   std::tie(size, endian) = getElfArchType(mb.getBuffer());
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric   auto report = [&](StringRef msg) {
720b57cec5SDimitry Andric     StringRef filename = mb.getBufferIdentifier();
730b57cec5SDimitry Andric     if (archiveName.empty())
740b57cec5SDimitry Andric       fatal(filename + ": " + msg);
750b57cec5SDimitry Andric     else
760b57cec5SDimitry Andric       fatal(archiveName + "(" + filename + "): " + msg);
770b57cec5SDimitry Andric   };
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric   if (!mb.getBuffer().startswith(ElfMagic))
800b57cec5SDimitry Andric     report("not an ELF file");
810b57cec5SDimitry Andric   if (endian != ELFDATA2LSB && endian != ELFDATA2MSB)
820b57cec5SDimitry Andric     report("corrupted ELF file: invalid data encoding");
830b57cec5SDimitry Andric   if (size != ELFCLASS32 && size != ELFCLASS64)
840b57cec5SDimitry Andric     report("corrupted ELF file: invalid file class");
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric   size_t bufSize = mb.getBuffer().size();
870b57cec5SDimitry Andric   if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) ||
880b57cec5SDimitry Andric       (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr)))
890b57cec5SDimitry Andric     report("corrupted ELF file: file is too short");
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric   if (size == ELFCLASS32)
920b57cec5SDimitry Andric     return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
930b57cec5SDimitry Andric   return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
940b57cec5SDimitry Andric }
950b57cec5SDimitry Andric 
96*bdd1243dSDimitry Andric // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
97*bdd1243dSDimitry Andric // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
98*bdd1243dSDimitry Andric // the input objects have been compiled.
99*bdd1243dSDimitry Andric static void updateARMVFPArgs(const ARMAttributeParser &attributes,
100*bdd1243dSDimitry Andric                              const InputFile *f) {
101*bdd1243dSDimitry Andric   std::optional<unsigned> attr =
102*bdd1243dSDimitry Andric       attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
103*bdd1243dSDimitry Andric   if (!attr)
104*bdd1243dSDimitry Andric     // If an ABI tag isn't present then it is implicitly given the value of 0
105*bdd1243dSDimitry Andric     // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
106*bdd1243dSDimitry Andric     // including some in glibc that don't use FP args (and should have value 3)
107*bdd1243dSDimitry Andric     // don't have the attribute so we do not consider an implicit value of 0
108*bdd1243dSDimitry Andric     // as a clash.
109*bdd1243dSDimitry Andric     return;
110*bdd1243dSDimitry Andric 
111*bdd1243dSDimitry Andric   unsigned vfpArgs = *attr;
112*bdd1243dSDimitry Andric   ARMVFPArgKind arg;
113*bdd1243dSDimitry Andric   switch (vfpArgs) {
114*bdd1243dSDimitry Andric   case ARMBuildAttrs::BaseAAPCS:
115*bdd1243dSDimitry Andric     arg = ARMVFPArgKind::Base;
116*bdd1243dSDimitry Andric     break;
117*bdd1243dSDimitry Andric   case ARMBuildAttrs::HardFPAAPCS:
118*bdd1243dSDimitry Andric     arg = ARMVFPArgKind::VFP;
119*bdd1243dSDimitry Andric     break;
120*bdd1243dSDimitry Andric   case ARMBuildAttrs::ToolChainFPPCS:
121*bdd1243dSDimitry Andric     // Tool chain specific convention that conforms to neither AAPCS variant.
122*bdd1243dSDimitry Andric     arg = ARMVFPArgKind::ToolChain;
123*bdd1243dSDimitry Andric     break;
124*bdd1243dSDimitry Andric   case ARMBuildAttrs::CompatibleFPAAPCS:
125*bdd1243dSDimitry Andric     // Object compatible with all conventions.
126*bdd1243dSDimitry Andric     return;
127*bdd1243dSDimitry Andric   default:
128*bdd1243dSDimitry Andric     error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs));
129*bdd1243dSDimitry Andric     return;
130*bdd1243dSDimitry Andric   }
131*bdd1243dSDimitry Andric   // Follow ld.bfd and error if there is a mix of calling conventions.
132*bdd1243dSDimitry Andric   if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default)
133*bdd1243dSDimitry Andric     error(toString(f) + ": incompatible Tag_ABI_VFP_args");
134*bdd1243dSDimitry Andric   else
135*bdd1243dSDimitry Andric     config->armVFPArgs = arg;
136*bdd1243dSDimitry Andric }
137*bdd1243dSDimitry Andric 
138*bdd1243dSDimitry Andric // The ARM support in lld makes some use of instructions that are not available
139*bdd1243dSDimitry Andric // on all ARM architectures. Namely:
140*bdd1243dSDimitry Andric // - Use of BLX instruction for interworking between ARM and Thumb state.
141*bdd1243dSDimitry Andric // - Use of the extended Thumb branch encoding in relocation.
142*bdd1243dSDimitry Andric // - Use of the MOVT/MOVW instructions in Thumb Thunks.
143*bdd1243dSDimitry Andric // The ARM Attributes section contains information about the architecture chosen
144*bdd1243dSDimitry Andric // at compile time. We follow the convention that if at least one input object
145*bdd1243dSDimitry Andric // is compiled with an architecture that supports these features then lld is
146*bdd1243dSDimitry Andric // permitted to use them.
147*bdd1243dSDimitry Andric static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
148*bdd1243dSDimitry Andric   std::optional<unsigned> attr =
149*bdd1243dSDimitry Andric       attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
150*bdd1243dSDimitry Andric   if (!attr)
151*bdd1243dSDimitry Andric     return;
152*bdd1243dSDimitry Andric   auto arch = *attr;
153*bdd1243dSDimitry Andric   switch (arch) {
154*bdd1243dSDimitry Andric   case ARMBuildAttrs::Pre_v4:
155*bdd1243dSDimitry Andric   case ARMBuildAttrs::v4:
156*bdd1243dSDimitry Andric   case ARMBuildAttrs::v4T:
157*bdd1243dSDimitry Andric     // Architectures prior to v5 do not support BLX instruction
158*bdd1243dSDimitry Andric     break;
159*bdd1243dSDimitry Andric   case ARMBuildAttrs::v5T:
160*bdd1243dSDimitry Andric   case ARMBuildAttrs::v5TE:
161*bdd1243dSDimitry Andric   case ARMBuildAttrs::v5TEJ:
162*bdd1243dSDimitry Andric   case ARMBuildAttrs::v6:
163*bdd1243dSDimitry Andric   case ARMBuildAttrs::v6KZ:
164*bdd1243dSDimitry Andric   case ARMBuildAttrs::v6K:
165*bdd1243dSDimitry Andric     config->armHasBlx = true;
166*bdd1243dSDimitry Andric     // Architectures used in pre-Cortex processors do not support
167*bdd1243dSDimitry Andric     // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
168*bdd1243dSDimitry Andric     // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
169*bdd1243dSDimitry Andric     break;
170*bdd1243dSDimitry Andric   default:
171*bdd1243dSDimitry Andric     // All other Architectures have BLX and extended branch encoding
172*bdd1243dSDimitry Andric     config->armHasBlx = true;
173*bdd1243dSDimitry Andric     config->armJ1J2BranchEncoding = true;
174*bdd1243dSDimitry Andric     if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
175*bdd1243dSDimitry Andric       // All Architectures used in Cortex processors with the exception
176*bdd1243dSDimitry Andric       // of v6-M and v6S-M have the MOVT and MOVW instructions.
177*bdd1243dSDimitry Andric       config->armHasMovtMovw = true;
178*bdd1243dSDimitry Andric     break;
179*bdd1243dSDimitry Andric   }
180*bdd1243dSDimitry Andric }
181*bdd1243dSDimitry Andric 
1820b57cec5SDimitry Andric InputFile::InputFile(Kind k, MemoryBufferRef m)
1830b57cec5SDimitry Andric     : mb(m), groupId(nextGroupId), fileKind(k) {
1840b57cec5SDimitry Andric   // All files within the same --{start,end}-group get the same group ID.
1850b57cec5SDimitry Andric   // Otherwise, a new file will get a new group ID.
1860b57cec5SDimitry Andric   if (!isInGroup)
1870b57cec5SDimitry Andric     ++nextGroupId;
1880b57cec5SDimitry Andric }
1890b57cec5SDimitry Andric 
190*bdd1243dSDimitry Andric std::optional<MemoryBufferRef> elf::readFile(StringRef path) {
191e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Load input files", path);
192e8d8bef9SDimitry Andric 
1930b57cec5SDimitry Andric   // The --chroot option changes our virtual root directory.
1940b57cec5SDimitry Andric   // This is useful when you are dealing with files created by --reproduce.
1950b57cec5SDimitry Andric   if (!config->chroot.empty() && path.startswith("/"))
19604eeddc0SDimitry Andric     path = saver().save(config->chroot + path);
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric   log(path);
199e8d8bef9SDimitry Andric   config->dependencyFiles.insert(llvm::CachedHashString(path));
2000b57cec5SDimitry Andric 
201fe6060f1SDimitry Andric   auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
202fe6060f1SDimitry Andric                                        /*RequiresNullTerminator=*/false);
2030b57cec5SDimitry Andric   if (auto ec = mbOrErr.getError()) {
2040b57cec5SDimitry Andric     error("cannot open " + path + ": " + ec.message());
205*bdd1243dSDimitry Andric     return std::nullopt;
2060b57cec5SDimitry Andric   }
2070b57cec5SDimitry Andric 
20804eeddc0SDimitry Andric   MemoryBufferRef mbref = (*mbOrErr)->getMemBufferRef();
209*bdd1243dSDimitry Andric   ctx.memoryBuffers.push_back(std::move(*mbOrErr)); // take MB ownership
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric   if (tar)
2120b57cec5SDimitry Andric     tar->append(relativeToRoot(path), mbref.getBuffer());
2130b57cec5SDimitry Andric   return mbref;
2140b57cec5SDimitry Andric }
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric // All input object files must be for the same architecture
2170b57cec5SDimitry Andric // (e.g. it does not make sense to link x86 object files with
2180b57cec5SDimitry Andric // MIPS object files.) This function checks for that error.
2190b57cec5SDimitry Andric static bool isCompatible(InputFile *file) {
2200b57cec5SDimitry Andric   if (!file->isElf() && !isa<BitcodeFile>(file))
2210b57cec5SDimitry Andric     return true;
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric   if (file->ekind == config->ekind && file->emachine == config->emachine) {
2240b57cec5SDimitry Andric     if (config->emachine != EM_MIPS)
2250b57cec5SDimitry Andric       return true;
2260b57cec5SDimitry Andric     if (isMipsN32Abi(file) == config->mipsN32Abi)
2270b57cec5SDimitry Andric       return true;
2280b57cec5SDimitry Andric   }
2290b57cec5SDimitry Andric 
2305ffd83dbSDimitry Andric   StringRef target =
2315ffd83dbSDimitry Andric       !config->bfdname.empty() ? config->bfdname : config->emulation;
2325ffd83dbSDimitry Andric   if (!target.empty()) {
2335ffd83dbSDimitry Andric     error(toString(file) + " is incompatible with " + target);
23485868e8aSDimitry Andric     return false;
23585868e8aSDimitry Andric   }
23685868e8aSDimitry Andric 
237d56accc7SDimitry Andric   InputFile *existing = nullptr;
238*bdd1243dSDimitry Andric   if (!ctx.objectFiles.empty())
239*bdd1243dSDimitry Andric     existing = ctx.objectFiles[0];
240*bdd1243dSDimitry Andric   else if (!ctx.sharedFiles.empty())
241*bdd1243dSDimitry Andric     existing = ctx.sharedFiles[0];
242*bdd1243dSDimitry Andric   else if (!ctx.bitcodeFiles.empty())
243*bdd1243dSDimitry Andric     existing = ctx.bitcodeFiles[0];
244d56accc7SDimitry Andric   std::string with;
245d56accc7SDimitry Andric   if (existing)
246d56accc7SDimitry Andric     with = " with " + toString(existing);
247d56accc7SDimitry Andric   error(toString(file) + " is incompatible" + with);
2480b57cec5SDimitry Andric   return false;
2490b57cec5SDimitry Andric }
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric template <class ELFT> static void doParseFile(InputFile *file) {
2520b57cec5SDimitry Andric   if (!isCompatible(file))
2530b57cec5SDimitry Andric     return;
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   // Binary file
2560b57cec5SDimitry Andric   if (auto *f = dyn_cast<BinaryFile>(file)) {
257*bdd1243dSDimitry Andric     ctx.binaryFiles.push_back(f);
2580b57cec5SDimitry Andric     f->parse();
2590b57cec5SDimitry Andric     return;
2600b57cec5SDimitry Andric   }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric   // Lazy object file
2630eae32dcSDimitry Andric   if (file->lazy) {
2640eae32dcSDimitry Andric     if (auto *f = dyn_cast<BitcodeFile>(file)) {
265*bdd1243dSDimitry Andric       ctx.lazyBitcodeFiles.push_back(f);
2660eae32dcSDimitry Andric       f->parseLazy();
2670eae32dcSDimitry Andric     } else {
2680eae32dcSDimitry Andric       cast<ObjFile<ELFT>>(file)->parseLazy();
2690eae32dcSDimitry Andric     }
2700b57cec5SDimitry Andric     return;
2710b57cec5SDimitry Andric   }
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   if (config->trace)
2740b57cec5SDimitry Andric     message(toString(file));
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric   // .so file
2770b57cec5SDimitry Andric   if (auto *f = dyn_cast<SharedFile>(file)) {
2780b57cec5SDimitry Andric     f->parse<ELFT>();
2790b57cec5SDimitry Andric     return;
2800b57cec5SDimitry Andric   }
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   // LLVM bitcode file
2830b57cec5SDimitry Andric   if (auto *f = dyn_cast<BitcodeFile>(file)) {
284*bdd1243dSDimitry Andric     ctx.bitcodeFiles.push_back(f);
285*bdd1243dSDimitry Andric     f->parse();
2860b57cec5SDimitry Andric     return;
2870b57cec5SDimitry Andric   }
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric   // Regular object file
290*bdd1243dSDimitry Andric   ctx.objectFiles.push_back(cast<ELFFileBase>(file));
2910b57cec5SDimitry Andric   cast<ObjFile<ELFT>>(file)->parse();
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric // Add symbols in File to the symbol table.
2951fd87a68SDimitry Andric void elf::parseFile(InputFile *file) { invokeELFT(doParseFile, file); }
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric // Concatenates arguments to construct a string representing an error location.
2980b57cec5SDimitry Andric static std::string createFileLineMsg(StringRef path, unsigned line) {
2995ffd83dbSDimitry Andric   std::string filename = std::string(path::filename(path));
3000b57cec5SDimitry Andric   std::string lineno = ":" + std::to_string(line);
3010b57cec5SDimitry Andric   if (filename == path)
3020b57cec5SDimitry Andric     return filename + lineno;
3030b57cec5SDimitry Andric   return filename + lineno + " (" + path.str() + lineno + ")";
3040b57cec5SDimitry Andric }
3050b57cec5SDimitry Andric 
3060b57cec5SDimitry Andric template <class ELFT>
3070b57cec5SDimitry Andric static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym,
3080b57cec5SDimitry Andric                                 InputSectionBase &sec, uint64_t offset) {
3090b57cec5SDimitry Andric   // In DWARF, functions and variables are stored to different places.
3100b57cec5SDimitry Andric   // First, look up a function for a given offset.
311*bdd1243dSDimitry Andric   if (std::optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
3120b57cec5SDimitry Andric     return createFileLineMsg(info->FileName, info->Line);
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   // If it failed, look up again as a variable.
315*bdd1243dSDimitry Andric   if (std::optional<std::pair<std::string, unsigned>> fileLine =
3160b57cec5SDimitry Andric           file.getVariableLoc(sym.getName()))
3170b57cec5SDimitry Andric     return createFileLineMsg(fileLine->first, fileLine->second);
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric   // File.sourceFile contains STT_FILE symbol, and that is a last resort.
3205ffd83dbSDimitry Andric   return std::string(file.sourceFile);
3210b57cec5SDimitry Andric }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec,
3240b57cec5SDimitry Andric                                  uint64_t offset) {
3250b57cec5SDimitry Andric   if (kind() != ObjKind)
3260b57cec5SDimitry Andric     return "";
327*bdd1243dSDimitry Andric   switch (ekind) {
3280b57cec5SDimitry Andric   default:
3290b57cec5SDimitry Andric     llvm_unreachable("Invalid kind");
3300b57cec5SDimitry Andric   case ELF32LEKind:
3310b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset);
3320b57cec5SDimitry Andric   case ELF32BEKind:
3330b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset);
3340b57cec5SDimitry Andric   case ELF64LEKind:
3350b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset);
3360b57cec5SDimitry Andric   case ELF64BEKind:
3370b57cec5SDimitry Andric     return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset);
3380b57cec5SDimitry Andric   }
3390b57cec5SDimitry Andric }
3400b57cec5SDimitry Andric 
341e8d8bef9SDimitry Andric StringRef InputFile::getNameForScript() const {
342e8d8bef9SDimitry Andric   if (archiveName.empty())
343e8d8bef9SDimitry Andric     return getName();
344e8d8bef9SDimitry Andric 
345e8d8bef9SDimitry Andric   if (nameForScriptCache.empty())
346e8d8bef9SDimitry Andric     nameForScriptCache = (archiveName + Twine(':') + getName()).str();
347e8d8bef9SDimitry Andric 
348e8d8bef9SDimitry Andric   return nameForScriptCache;
349e8d8bef9SDimitry Andric }
350e8d8bef9SDimitry Andric 
351*bdd1243dSDimitry Andric // An ELF object file may contain a `.deplibs` section. If it exists, the
352*bdd1243dSDimitry Andric // section contains a list of library specifiers such as `m` for libm. This
353*bdd1243dSDimitry Andric // function resolves a given name by finding the first matching library checking
354*bdd1243dSDimitry Andric // the various ways that a library can be specified to LLD. This ELF extension
355*bdd1243dSDimitry Andric // is a form of autolinking and is called `dependent libraries`. It is currently
356*bdd1243dSDimitry Andric // unique to LLVM and lld.
357*bdd1243dSDimitry Andric static void addDependentLibrary(StringRef specifier, const InputFile *f) {
358*bdd1243dSDimitry Andric   if (!config->dependentLibraries)
359*bdd1243dSDimitry Andric     return;
360*bdd1243dSDimitry Andric   if (std::optional<std::string> s = searchLibraryBaseName(specifier))
361*bdd1243dSDimitry Andric     ctx.driver.addFile(saver().save(*s), /*withLOption=*/true);
362*bdd1243dSDimitry Andric   else if (std::optional<std::string> s = findFromSearchPaths(specifier))
363*bdd1243dSDimitry Andric     ctx.driver.addFile(saver().save(*s), /*withLOption=*/true);
364*bdd1243dSDimitry Andric   else if (fs::exists(specifier))
365*bdd1243dSDimitry Andric     ctx.driver.addFile(specifier, /*withLOption=*/false);
366*bdd1243dSDimitry Andric   else
367*bdd1243dSDimitry Andric     error(toString(f) +
368*bdd1243dSDimitry Andric           ": unable to find library from dependent library specifier: " +
369*bdd1243dSDimitry Andric           specifier);
370*bdd1243dSDimitry Andric }
371*bdd1243dSDimitry Andric 
372*bdd1243dSDimitry Andric // Record the membership of a section group so that in the garbage collection
373*bdd1243dSDimitry Andric // pass, section group members are kept or discarded as a unit.
374*bdd1243dSDimitry Andric template <class ELFT>
375*bdd1243dSDimitry Andric static void handleSectionGroup(ArrayRef<InputSectionBase *> sections,
376*bdd1243dSDimitry Andric                                ArrayRef<typename ELFT::Word> entries) {
377*bdd1243dSDimitry Andric   bool hasAlloc = false;
378*bdd1243dSDimitry Andric   for (uint32_t index : entries.slice(1)) {
379*bdd1243dSDimitry Andric     if (index >= sections.size())
380*bdd1243dSDimitry Andric       return;
381*bdd1243dSDimitry Andric     if (InputSectionBase *s = sections[index])
382*bdd1243dSDimitry Andric       if (s != &InputSection::discarded && s->flags & SHF_ALLOC)
383*bdd1243dSDimitry Andric         hasAlloc = true;
384*bdd1243dSDimitry Andric   }
385*bdd1243dSDimitry Andric 
386*bdd1243dSDimitry Andric   // If any member has the SHF_ALLOC flag, the whole group is subject to garbage
387*bdd1243dSDimitry Andric   // collection. See the comment in markLive(). This rule retains .debug_types
388*bdd1243dSDimitry Andric   // and .rela.debug_types.
389*bdd1243dSDimitry Andric   if (!hasAlloc)
390*bdd1243dSDimitry Andric     return;
391*bdd1243dSDimitry Andric 
392*bdd1243dSDimitry Andric   // Connect the members in a circular doubly-linked list via
393*bdd1243dSDimitry Andric   // nextInSectionGroup.
394*bdd1243dSDimitry Andric   InputSectionBase *head;
395*bdd1243dSDimitry Andric   InputSectionBase *prev = nullptr;
396*bdd1243dSDimitry Andric   for (uint32_t index : entries.slice(1)) {
397*bdd1243dSDimitry Andric     InputSectionBase *s = sections[index];
398*bdd1243dSDimitry Andric     if (!s || s == &InputSection::discarded)
399*bdd1243dSDimitry Andric       continue;
400*bdd1243dSDimitry Andric     if (prev)
401*bdd1243dSDimitry Andric       prev->nextInSectionGroup = s;
402*bdd1243dSDimitry Andric     else
403*bdd1243dSDimitry Andric       head = s;
404*bdd1243dSDimitry Andric     prev = s;
405*bdd1243dSDimitry Andric   }
406*bdd1243dSDimitry Andric   if (prev)
407*bdd1243dSDimitry Andric     prev->nextInSectionGroup = head;
408*bdd1243dSDimitry Andric }
409*bdd1243dSDimitry Andric 
4105ffd83dbSDimitry Andric template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() {
4115ffd83dbSDimitry Andric   llvm::call_once(initDwarf, [this]() {
4125ffd83dbSDimitry Andric     dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
4135ffd83dbSDimitry Andric         std::make_unique<LLDDwarfObj<ELFT>>(this), "",
4145ffd83dbSDimitry Andric         [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
4155ffd83dbSDimitry Andric         [&](Error warning) {
4165ffd83dbSDimitry Andric           warn(getName() + ": " + toString(std::move(warning)));
4175ffd83dbSDimitry Andric         }));
4185ffd83dbSDimitry Andric   });
4195ffd83dbSDimitry Andric 
4205ffd83dbSDimitry Andric   return dwarf.get();
4210b57cec5SDimitry Andric }
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric // Returns the pair of file name and line number describing location of data
4240b57cec5SDimitry Andric // object (variable, array, etc) definition.
4250b57cec5SDimitry Andric template <class ELFT>
426*bdd1243dSDimitry Andric std::optional<std::pair<std::string, unsigned>>
4270b57cec5SDimitry Andric ObjFile<ELFT>::getVariableLoc(StringRef name) {
4285ffd83dbSDimitry Andric   return getDwarf()->getVariableLoc(name);
4290b57cec5SDimitry Andric }
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric // Returns source line information for a given offset
4320b57cec5SDimitry Andric // using DWARF debug info.
4330b57cec5SDimitry Andric template <class ELFT>
434*bdd1243dSDimitry Andric std::optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s,
4350b57cec5SDimitry Andric                                                        uint64_t offset) {
4360b57cec5SDimitry Andric   // Detect SectionIndex for specified section.
4370b57cec5SDimitry Andric   uint64_t sectionIndex = object::SectionedAddress::UndefSection;
4380b57cec5SDimitry Andric   ArrayRef<InputSectionBase *> sections = s->file->getSections();
4390b57cec5SDimitry Andric   for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) {
4400b57cec5SDimitry Andric     if (s == sections[curIndex]) {
4410b57cec5SDimitry Andric       sectionIndex = curIndex;
4420b57cec5SDimitry Andric       break;
4430b57cec5SDimitry Andric     }
4440b57cec5SDimitry Andric   }
4450b57cec5SDimitry Andric 
4465ffd83dbSDimitry Andric   return getDwarf()->getDILineInfo(offset, sectionIndex);
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric 
449*bdd1243dSDimitry Andric ELFFileBase::ELFFileBase(Kind k, ELFKind ekind, MemoryBufferRef mb)
450*bdd1243dSDimitry Andric     : InputFile(k, mb) {
451*bdd1243dSDimitry Andric   this->ekind = ekind;
4520b57cec5SDimitry Andric }
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric template <typename Elf_Shdr>
4550b57cec5SDimitry Andric static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
4560b57cec5SDimitry Andric   for (const Elf_Shdr &sec : sections)
4570b57cec5SDimitry Andric     if (sec.sh_type == type)
4580b57cec5SDimitry Andric       return &sec;
4590b57cec5SDimitry Andric   return nullptr;
4600b57cec5SDimitry Andric }
4610b57cec5SDimitry Andric 
462*bdd1243dSDimitry Andric void ELFFileBase::init() {
463*bdd1243dSDimitry Andric   switch (ekind) {
464*bdd1243dSDimitry Andric   case ELF32LEKind:
465*bdd1243dSDimitry Andric     init<ELF32LE>(fileKind);
466*bdd1243dSDimitry Andric     break;
467*bdd1243dSDimitry Andric   case ELF32BEKind:
468*bdd1243dSDimitry Andric     init<ELF32BE>(fileKind);
469*bdd1243dSDimitry Andric     break;
470*bdd1243dSDimitry Andric   case ELF64LEKind:
471*bdd1243dSDimitry Andric     init<ELF64LE>(fileKind);
472*bdd1243dSDimitry Andric     break;
473*bdd1243dSDimitry Andric   case ELF64BEKind:
474*bdd1243dSDimitry Andric     init<ELF64BE>(fileKind);
475*bdd1243dSDimitry Andric     break;
476*bdd1243dSDimitry Andric   default:
477*bdd1243dSDimitry Andric     llvm_unreachable("getELFKind");
478*bdd1243dSDimitry Andric   }
479*bdd1243dSDimitry Andric }
480*bdd1243dSDimitry Andric 
481*bdd1243dSDimitry Andric template <class ELFT> void ELFFileBase::init(InputFile::Kind k) {
4820b57cec5SDimitry Andric   using Elf_Shdr = typename ELFT::Shdr;
4830b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric   // Initialize trivial attributes.
4860b57cec5SDimitry Andric   const ELFFile<ELFT> &obj = getObj<ELFT>();
487e8d8bef9SDimitry Andric   emachine = obj.getHeader().e_machine;
488e8d8bef9SDimitry Andric   osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI];
489e8d8bef9SDimitry Andric   abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION];
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric   ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
4920eae32dcSDimitry Andric   elfShdrs = sections.data();
4930eae32dcSDimitry Andric   numELFShdrs = sections.size();
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   // Find a symbol table.
4960b57cec5SDimitry Andric   const Elf_Shdr *symtabSec =
497*bdd1243dSDimitry Andric       findSection(sections, k == SharedKind ? SHT_DYNSYM : SHT_SYMTAB);
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric   if (!symtabSec)
5000b57cec5SDimitry Andric     return;
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   // Initialize members corresponding to a symbol table.
5030b57cec5SDimitry Andric   firstGlobal = symtabSec->sh_info;
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
5060b57cec5SDimitry Andric   if (firstGlobal == 0 || firstGlobal > eSyms.size())
5070b57cec5SDimitry Andric     fatal(toString(this) + ": invalid sh_info in symbol table");
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric   elfSyms = reinterpret_cast<const void *>(eSyms.data());
5100eae32dcSDimitry Andric   numELFSyms = uint32_t(eSyms.size());
5110b57cec5SDimitry Andric   stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
5120b57cec5SDimitry Andric }
5130b57cec5SDimitry Andric 
5140b57cec5SDimitry Andric template <class ELFT>
5150b57cec5SDimitry Andric uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
5160b57cec5SDimitry Andric   return CHECK(
517e8d8bef9SDimitry Andric       this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable),
5180b57cec5SDimitry Andric       this);
5190b57cec5SDimitry Andric }
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
5221fd87a68SDimitry Andric   object::ELFFile<ELFT> obj = this->getObj();
5230b57cec5SDimitry Andric   // Read a section table. justSymbols is usually false.
524*bdd1243dSDimitry Andric   if (this->justSymbols) {
5250b57cec5SDimitry Andric     initializeJustSymbols();
526*bdd1243dSDimitry Andric     initializeSymbols(obj);
527*bdd1243dSDimitry Andric     return;
528*bdd1243dSDimitry Andric   }
529*bdd1243dSDimitry Andric 
530*bdd1243dSDimitry Andric   // Handle dependent libraries and selection of section groups as these are not
531*bdd1243dSDimitry Andric   // done in parallel.
532*bdd1243dSDimitry Andric   ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
533*bdd1243dSDimitry Andric   StringRef shstrtab = CHECK(obj.getSectionStringTable(objSections), this);
534*bdd1243dSDimitry Andric   uint64_t size = objSections.size();
535*bdd1243dSDimitry Andric   sections.resize(size);
536*bdd1243dSDimitry Andric   for (size_t i = 0; i != size; ++i) {
537*bdd1243dSDimitry Andric     const Elf_Shdr &sec = objSections[i];
538*bdd1243dSDimitry Andric     if (sec.sh_type == SHT_LLVM_DEPENDENT_LIBRARIES && !config->relocatable) {
539*bdd1243dSDimitry Andric       StringRef name = check(obj.getSectionName(sec, shstrtab));
540*bdd1243dSDimitry Andric       ArrayRef<char> data = CHECK(
541*bdd1243dSDimitry Andric           this->getObj().template getSectionContentsAsArray<char>(sec), this);
542*bdd1243dSDimitry Andric       if (!data.empty() && data.back() != '\0') {
543*bdd1243dSDimitry Andric         error(
544*bdd1243dSDimitry Andric             toString(this) +
545*bdd1243dSDimitry Andric             ": corrupted dependent libraries section (unterminated string): " +
546*bdd1243dSDimitry Andric             name);
547*bdd1243dSDimitry Andric       } else {
548*bdd1243dSDimitry Andric         for (const char *d = data.begin(), *e = data.end(); d < e;) {
549*bdd1243dSDimitry Andric           StringRef s(d);
550*bdd1243dSDimitry Andric           addDependentLibrary(s, this);
551*bdd1243dSDimitry Andric           d += s.size() + 1;
552*bdd1243dSDimitry Andric         }
553*bdd1243dSDimitry Andric       }
554*bdd1243dSDimitry Andric       this->sections[i] = &InputSection::discarded;
555*bdd1243dSDimitry Andric       continue;
556*bdd1243dSDimitry Andric     }
557*bdd1243dSDimitry Andric 
558*bdd1243dSDimitry Andric     if (sec.sh_type == SHT_ARM_ATTRIBUTES && config->emachine == EM_ARM) {
559*bdd1243dSDimitry Andric       ARMAttributeParser attributes;
560*bdd1243dSDimitry Andric       ArrayRef<uint8_t> contents =
561*bdd1243dSDimitry Andric           check(this->getObj().getSectionContents(sec));
562*bdd1243dSDimitry Andric       StringRef name = check(obj.getSectionName(sec, shstrtab));
563*bdd1243dSDimitry Andric       this->sections[i] = &InputSection::discarded;
564*bdd1243dSDimitry Andric       if (Error e =
565*bdd1243dSDimitry Andric               attributes.parse(contents, ekind == ELF32LEKind ? support::little
566*bdd1243dSDimitry Andric                                                               : support::big)) {
567*bdd1243dSDimitry Andric         InputSection isec(*this, sec, name);
568*bdd1243dSDimitry Andric         warn(toString(&isec) + ": " + llvm::toString(std::move(e)));
569*bdd1243dSDimitry Andric       } else {
570*bdd1243dSDimitry Andric         updateSupportedARMFeatures(attributes);
571*bdd1243dSDimitry Andric         updateARMVFPArgs(attributes, this);
572*bdd1243dSDimitry Andric 
573*bdd1243dSDimitry Andric         // FIXME: Retain the first attribute section we see. The eglibc ARM
574*bdd1243dSDimitry Andric         // dynamic loaders require the presence of an attribute section for
575*bdd1243dSDimitry Andric         // dlopen to work. In a full implementation we would merge all attribute
576*bdd1243dSDimitry Andric         // sections.
577*bdd1243dSDimitry Andric         if (in.attributes == nullptr) {
578*bdd1243dSDimitry Andric           in.attributes = std::make_unique<InputSection>(*this, sec, name);
579*bdd1243dSDimitry Andric           this->sections[i] = in.attributes.get();
580*bdd1243dSDimitry Andric         }
581*bdd1243dSDimitry Andric       }
582*bdd1243dSDimitry Andric     }
583*bdd1243dSDimitry Andric 
584*bdd1243dSDimitry Andric     if (sec.sh_type != SHT_GROUP)
585*bdd1243dSDimitry Andric       continue;
586*bdd1243dSDimitry Andric     StringRef signature = getShtGroupSignature(objSections, sec);
587*bdd1243dSDimitry Andric     ArrayRef<Elf_Word> entries =
588*bdd1243dSDimitry Andric         CHECK(obj.template getSectionContentsAsArray<Elf_Word>(sec), this);
589*bdd1243dSDimitry Andric     if (entries.empty())
590*bdd1243dSDimitry Andric       fatal(toString(this) + ": empty SHT_GROUP");
591*bdd1243dSDimitry Andric 
592*bdd1243dSDimitry Andric     Elf_Word flag = entries[0];
593*bdd1243dSDimitry Andric     if (flag && flag != GRP_COMDAT)
594*bdd1243dSDimitry Andric       fatal(toString(this) + ": unsupported SHT_GROUP format");
595*bdd1243dSDimitry Andric 
596*bdd1243dSDimitry Andric     bool keepGroup =
597*bdd1243dSDimitry Andric         (flag & GRP_COMDAT) == 0 || ignoreComdats ||
598*bdd1243dSDimitry Andric         symtab.comdatGroups.try_emplace(CachedHashStringRef(signature), this)
599*bdd1243dSDimitry Andric             .second;
600*bdd1243dSDimitry Andric     if (keepGroup) {
601*bdd1243dSDimitry Andric       if (config->relocatable)
602*bdd1243dSDimitry Andric         this->sections[i] = createInputSection(
603*bdd1243dSDimitry Andric             i, sec, check(obj.getSectionName(sec, shstrtab)));
604*bdd1243dSDimitry Andric       continue;
605*bdd1243dSDimitry Andric     }
606*bdd1243dSDimitry Andric 
607*bdd1243dSDimitry Andric     // Otherwise, discard group members.
608*bdd1243dSDimitry Andric     for (uint32_t secIndex : entries.slice(1)) {
609*bdd1243dSDimitry Andric       if (secIndex >= size)
610*bdd1243dSDimitry Andric         fatal(toString(this) +
611*bdd1243dSDimitry Andric               ": invalid section index in group: " + Twine(secIndex));
612*bdd1243dSDimitry Andric       this->sections[secIndex] = &InputSection::discarded;
613*bdd1243dSDimitry Andric     }
614*bdd1243dSDimitry Andric   }
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric   // Read a symbol table.
6171fd87a68SDimitry Andric   initializeSymbols(obj);
6180b57cec5SDimitry Andric }
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric // Sections with SHT_GROUP and comdat bits define comdat section groups.
6210b57cec5SDimitry Andric // They are identified and deduplicated by group name. This function
6220b57cec5SDimitry Andric // returns a group name.
6230b57cec5SDimitry Andric template <class ELFT>
6240b57cec5SDimitry Andric StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
6250b57cec5SDimitry Andric                                               const Elf_Shdr &sec) {
6260b57cec5SDimitry Andric   typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
6270b57cec5SDimitry Andric   if (sec.sh_info >= symbols.size())
6280b57cec5SDimitry Andric     fatal(toString(this) + ": invalid symbol index");
6290b57cec5SDimitry Andric   const typename ELFT::Sym &sym = symbols[sec.sh_info];
630349cc55cSDimitry Andric   return CHECK(sym.getName(this->stringTable), this);
6310b57cec5SDimitry Andric }
6320b57cec5SDimitry Andric 
63385868e8aSDimitry Andric template <class ELFT>
63485868e8aSDimitry Andric bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
6350b57cec5SDimitry Andric   // On a regular link we don't merge sections if -O0 (default is -O1). This
6360b57cec5SDimitry Andric   // sometimes makes the linker significantly faster, although the output will
6370b57cec5SDimitry Andric   // be bigger.
6380b57cec5SDimitry Andric   //
6390b57cec5SDimitry Andric   // Doing the same for -r would create a problem as it would combine sections
6400b57cec5SDimitry Andric   // with different sh_entsize. One option would be to just copy every SHF_MERGE
6410b57cec5SDimitry Andric   // section as is to the output. While this would produce a valid ELF file with
6420b57cec5SDimitry Andric   // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
6430b57cec5SDimitry Andric   // they see two .debug_str. We could have separate logic for combining
6440b57cec5SDimitry Andric   // SHF_MERGE sections based both on their name and sh_entsize, but that seems
6450b57cec5SDimitry Andric   // to be more trouble than it is worth. Instead, we just use the regular (-O1)
6460b57cec5SDimitry Andric   // logic for -r.
6470b57cec5SDimitry Andric   if (config->optimize == 0 && !config->relocatable)
6480b57cec5SDimitry Andric     return false;
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric   // A mergeable section with size 0 is useless because they don't have
6510b57cec5SDimitry Andric   // any data to merge. A mergeable string section with size 0 can be
6520b57cec5SDimitry Andric   // argued as invalid because it doesn't end with a null character.
6530b57cec5SDimitry Andric   // We'll avoid a mess by handling them as if they were non-mergeable.
6540b57cec5SDimitry Andric   if (sec.sh_size == 0)
6550b57cec5SDimitry Andric     return false;
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric   // Check for sh_entsize. The ELF spec is not clear about the zero
6580b57cec5SDimitry Andric   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
6590b57cec5SDimitry Andric   // the section does not hold a table of fixed-size entries". We know
6600b57cec5SDimitry Andric   // that Rust 1.13 produces a string mergeable section with a zero
6610b57cec5SDimitry Andric   // sh_entsize. Here we just accept it rather than being picky about it.
6620b57cec5SDimitry Andric   uint64_t entSize = sec.sh_entsize;
6630b57cec5SDimitry Andric   if (entSize == 0)
6640b57cec5SDimitry Andric     return false;
6650b57cec5SDimitry Andric   if (sec.sh_size % entSize)
66685868e8aSDimitry Andric     fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" +
66785868e8aSDimitry Andric           Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" +
66885868e8aSDimitry Andric           Twine(entSize) + ")");
6690b57cec5SDimitry Andric 
6705ffd83dbSDimitry Andric   if (sec.sh_flags & SHF_WRITE)
67185868e8aSDimitry Andric     fatal(toString(this) + ":(" + name +
67285868e8aSDimitry Andric           "): writable SHF_MERGE section is not supported");
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric   return true;
6750b57cec5SDimitry Andric }
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric // This is for --just-symbols.
6780b57cec5SDimitry Andric //
6790b57cec5SDimitry Andric // --just-symbols is a very minor feature that allows you to link your
6800b57cec5SDimitry Andric // output against other existing program, so that if you load both your
6810b57cec5SDimitry Andric // program and the other program into memory, your output can refer the
6820b57cec5SDimitry Andric // other program's symbols.
6830b57cec5SDimitry Andric //
6840b57cec5SDimitry Andric // When the option is given, we link "just symbols". The section table is
6850b57cec5SDimitry Andric // initialized with null pointers.
6860b57cec5SDimitry Andric template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
6870eae32dcSDimitry Andric   sections.resize(numELFShdrs);
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric template <class ELFT>
6911fd87a68SDimitry Andric void ObjFile<ELFT>::initializeSections(bool ignoreComdats,
6921fd87a68SDimitry Andric                                        const llvm::object::ELFFile<ELFT> &obj) {
6930eae32dcSDimitry Andric   ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
694349cc55cSDimitry Andric   StringRef shstrtab = CHECK(obj.getSectionStringTable(objSections), this);
6950b57cec5SDimitry Andric   uint64_t size = objSections.size();
696*bdd1243dSDimitry Andric   SmallVector<ArrayRef<Elf_Word>, 0> selectedGroups;
69704eeddc0SDimitry Andric   for (size_t i = 0; i != size; ++i) {
6980b57cec5SDimitry Andric     if (this->sections[i] == &InputSection::discarded)
6990b57cec5SDimitry Andric       continue;
7000b57cec5SDimitry Andric     const Elf_Shdr &sec = objSections[i];
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
7030b57cec5SDimitry Andric     // if -r is given, we'll let the final link discard such sections.
7040b57cec5SDimitry Andric     // This is compatible with GNU.
7050b57cec5SDimitry Andric     if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) {
7060eae32dcSDimitry Andric       if (sec.sh_type == SHT_LLVM_CALL_GRAPH_PROFILE)
7070eae32dcSDimitry Andric         cgProfileSectionIndex = i;
7080b57cec5SDimitry Andric       if (sec.sh_type == SHT_LLVM_ADDRSIG) {
7090b57cec5SDimitry Andric         // We ignore the address-significance table if we know that the object
7100b57cec5SDimitry Andric         // file was created by objcopy or ld -r. This is because these tools
7110b57cec5SDimitry Andric         // will reorder the symbols in the symbol table, invalidating the data
7120b57cec5SDimitry Andric         // in the address-significance table, which refers to symbols by index.
7130b57cec5SDimitry Andric         if (sec.sh_link != 0)
7140b57cec5SDimitry Andric           this->addrsigSec = &sec;
7150b57cec5SDimitry Andric         else if (config->icf == ICFLevel::Safe)
716fe6060f1SDimitry Andric           warn(toString(this) +
717fe6060f1SDimitry Andric                ": --icf=safe conservatively ignores "
718fe6060f1SDimitry Andric                "SHT_LLVM_ADDRSIG [index " +
719fe6060f1SDimitry Andric                Twine(i) +
720fe6060f1SDimitry Andric                "] with sh_link=0 "
721fe6060f1SDimitry Andric                "(likely created using objcopy or ld -r)");
7220b57cec5SDimitry Andric       }
7230b57cec5SDimitry Andric       this->sections[i] = &InputSection::discarded;
7240b57cec5SDimitry Andric       continue;
7250b57cec5SDimitry Andric     }
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric     switch (sec.sh_type) {
7280b57cec5SDimitry Andric     case SHT_GROUP: {
729*bdd1243dSDimitry Andric       if (!config->relocatable)
730*bdd1243dSDimitry Andric         sections[i] = &InputSection::discarded;
731*bdd1243dSDimitry Andric       StringRef signature =
732*bdd1243dSDimitry Andric           cantFail(this->getELFSyms<ELFT>()[sec.sh_info].getName(stringTable));
7330b57cec5SDimitry Andric       ArrayRef<Elf_Word> entries =
734*bdd1243dSDimitry Andric           cantFail(obj.template getSectionContentsAsArray<Elf_Word>(sec));
735*bdd1243dSDimitry Andric       if ((entries[0] & GRP_COMDAT) == 0 || ignoreComdats ||
736*bdd1243dSDimitry Andric           symtab.comdatGroups.find(CachedHashStringRef(signature))->second ==
737*bdd1243dSDimitry Andric               this)
738480093f4SDimitry Andric         selectedGroups.push_back(entries);
7390b57cec5SDimitry Andric       break;
7400b57cec5SDimitry Andric     }
7410b57cec5SDimitry Andric     case SHT_SYMTAB_SHNDX:
7420b57cec5SDimitry Andric       shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
7430b57cec5SDimitry Andric       break;
7440b57cec5SDimitry Andric     case SHT_SYMTAB:
7450b57cec5SDimitry Andric     case SHT_STRTAB:
7465ffd83dbSDimitry Andric     case SHT_REL:
7475ffd83dbSDimitry Andric     case SHT_RELA:
7480b57cec5SDimitry Andric     case SHT_NULL:
7490b57cec5SDimitry Andric       break;
75081ad6265SDimitry Andric     case SHT_LLVM_SYMPART:
751*bdd1243dSDimitry Andric       ctx.hasSympart.store(true, std::memory_order_relaxed);
752*bdd1243dSDimitry Andric       [[fallthrough]];
7530b57cec5SDimitry Andric     default:
7541fd87a68SDimitry Andric       this->sections[i] =
7551fd87a68SDimitry Andric           createInputSection(i, sec, check(obj.getSectionName(sec, shstrtab)));
7560b57cec5SDimitry Andric     }
75785868e8aSDimitry Andric   }
75885868e8aSDimitry Andric 
7595ffd83dbSDimitry Andric   // We have a second loop. It is used to:
7605ffd83dbSDimitry Andric   // 1) handle SHF_LINK_ORDER sections.
7615ffd83dbSDimitry Andric   // 2) create SHT_REL[A] sections. In some cases the section header index of a
7625ffd83dbSDimitry Andric   //    relocation section may be smaller than that of the relocated section. In
7635ffd83dbSDimitry Andric   //    such cases, the relocation section would attempt to reference a target
7645ffd83dbSDimitry Andric   //    section that has not yet been created. For simplicity, delay creation of
7655ffd83dbSDimitry Andric   //    relocation sections until now.
76604eeddc0SDimitry Andric   for (size_t i = 0; i != size; ++i) {
76785868e8aSDimitry Andric     if (this->sections[i] == &InputSection::discarded)
76885868e8aSDimitry Andric       continue;
76985868e8aSDimitry Andric     const Elf_Shdr &sec = objSections[i];
7705ffd83dbSDimitry Andric 
77104eeddc0SDimitry Andric     if (sec.sh_type == SHT_REL || sec.sh_type == SHT_RELA) {
77204eeddc0SDimitry Andric       // Find a relocation target section and associate this section with that.
77304eeddc0SDimitry Andric       // Target may have been discarded if it is in a different section group
77404eeddc0SDimitry Andric       // and the group is discarded, even though it's a violation of the spec.
77504eeddc0SDimitry Andric       // We handle that situation gracefully by discarding dangling relocation
77604eeddc0SDimitry Andric       // sections.
77704eeddc0SDimitry Andric       const uint32_t info = sec.sh_info;
77804eeddc0SDimitry Andric       InputSectionBase *s = getRelocTarget(i, sec, info);
77904eeddc0SDimitry Andric       if (!s)
78004eeddc0SDimitry Andric         continue;
78104eeddc0SDimitry Andric 
78204eeddc0SDimitry Andric       // ELF spec allows mergeable sections with relocations, but they are rare,
78304eeddc0SDimitry Andric       // and it is in practice hard to merge such sections by contents, because
78404eeddc0SDimitry Andric       // applying relocations at end of linking changes section contents. So, we
78504eeddc0SDimitry Andric       // simply handle such sections as non-mergeable ones. Degrading like this
78604eeddc0SDimitry Andric       // is acceptable because section merging is optional.
78704eeddc0SDimitry Andric       if (auto *ms = dyn_cast<MergeInputSection>(s)) {
788*bdd1243dSDimitry Andric         s = makeThreadLocal<InputSection>(
789*bdd1243dSDimitry Andric             ms->file, ms->flags, ms->type, ms->addralign,
790*bdd1243dSDimitry Andric             ms->contentMaybeDecompress(), ms->name);
79104eeddc0SDimitry Andric         sections[info] = s;
79204eeddc0SDimitry Andric       }
79304eeddc0SDimitry Andric 
79404eeddc0SDimitry Andric       if (s->relSecIdx != 0)
79504eeddc0SDimitry Andric         error(
79604eeddc0SDimitry Andric             toString(s) +
79704eeddc0SDimitry Andric             ": multiple relocation sections to one section are not supported");
79804eeddc0SDimitry Andric       s->relSecIdx = i;
79904eeddc0SDimitry Andric 
80004eeddc0SDimitry Andric       // Relocation sections are usually removed from the output, so return
80104eeddc0SDimitry Andric       // `nullptr` for the normal case. However, if -r or --emit-relocs is
80204eeddc0SDimitry Andric       // specified, we need to copy them to the output. (Some post link analysis
80304eeddc0SDimitry Andric       // tools specify --emit-relocs to obtain the information.)
80404eeddc0SDimitry Andric       if (config->copyRelocs) {
805*bdd1243dSDimitry Andric         auto *isec = makeThreadLocal<InputSection>(
80604eeddc0SDimitry Andric             *this, sec, check(obj.getSectionName(sec, shstrtab)));
80704eeddc0SDimitry Andric         // If the relocated section is discarded (due to /DISCARD/ or
80804eeddc0SDimitry Andric         // --gc-sections), the relocation section should be discarded as well.
80904eeddc0SDimitry Andric         s->dependentSections.push_back(isec);
81004eeddc0SDimitry Andric         sections[i] = isec;
81104eeddc0SDimitry Andric       }
81204eeddc0SDimitry Andric       continue;
81304eeddc0SDimitry Andric     }
8145ffd83dbSDimitry Andric 
815e8d8bef9SDimitry Andric     // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have
816e8d8bef9SDimitry Andric     // the flag.
81704eeddc0SDimitry Andric     if (!sec.sh_link || !(sec.sh_flags & SHF_LINK_ORDER))
81885868e8aSDimitry Andric       continue;
8190b57cec5SDimitry Andric 
8200b57cec5SDimitry Andric     InputSectionBase *linkSec = nullptr;
82104eeddc0SDimitry Andric     if (sec.sh_link < size)
8220b57cec5SDimitry Andric       linkSec = this->sections[sec.sh_link];
8230b57cec5SDimitry Andric     if (!linkSec)
82485868e8aSDimitry Andric       fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
8250b57cec5SDimitry Andric 
826e8d8bef9SDimitry Andric     // A SHF_LINK_ORDER section is discarded if its linked-to section is
827e8d8bef9SDimitry Andric     // discarded.
8280b57cec5SDimitry Andric     InputSection *isec = cast<InputSection>(this->sections[i]);
8290b57cec5SDimitry Andric     linkSec->dependentSections.push_back(isec);
8300b57cec5SDimitry Andric     if (!isa<InputSection>(linkSec))
8310b57cec5SDimitry Andric       error("a section " + isec->name +
83285868e8aSDimitry Andric             " with SHF_LINK_ORDER should not refer a non-regular section: " +
8330b57cec5SDimitry Andric             toString(linkSec));
8340b57cec5SDimitry Andric   }
835480093f4SDimitry Andric 
836480093f4SDimitry Andric   for (ArrayRef<Elf_Word> entries : selectedGroups)
837480093f4SDimitry Andric     handleSectionGroup<ELFT>(this->sections, entries);
8380b57cec5SDimitry Andric }
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric // If a source file is compiled with x86 hardware-assisted call flow control
8410b57cec5SDimitry Andric // enabled, the generated object file contains feature flags indicating that
8420b57cec5SDimitry Andric // fact. This function reads the feature flags and returns it.
8430b57cec5SDimitry Andric //
8440b57cec5SDimitry Andric // Essentially we want to read a single 32-bit value in this function, but this
8450b57cec5SDimitry Andric // function is rather complicated because the value is buried deep inside a
8460b57cec5SDimitry Andric // .note.gnu.property section.
8470b57cec5SDimitry Andric //
8480b57cec5SDimitry Andric // The section consists of one or more NOTE records. Each NOTE record consists
8490b57cec5SDimitry Andric // of zero or more type-length-value fields. We want to find a field of a
8500b57cec5SDimitry Andric // certain type. It seems a bit too much to just store a 32-bit value, perhaps
8510b57cec5SDimitry Andric // the ABI is unnecessarily complicated.
852e8d8bef9SDimitry Andric template <class ELFT> static uint32_t readAndFeatures(const InputSection &sec) {
8530b57cec5SDimitry Andric   using Elf_Nhdr = typename ELFT::Nhdr;
8540b57cec5SDimitry Andric   using Elf_Note = typename ELFT::Note;
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric   uint32_t featuresSet = 0;
857*bdd1243dSDimitry Andric   ArrayRef<uint8_t> data = sec.content();
858e8d8bef9SDimitry Andric   auto reportFatal = [&](const uint8_t *place, const char *msg) {
859e8d8bef9SDimitry Andric     fatal(toString(sec.file) + ":(" + sec.name + "+0x" +
860*bdd1243dSDimitry Andric           Twine::utohexstr(place - sec.content().data()) + "): " + msg);
861e8d8bef9SDimitry Andric   };
8620b57cec5SDimitry Andric   while (!data.empty()) {
8630b57cec5SDimitry Andric     // Read one NOTE record.
8640b57cec5SDimitry Andric     auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
865e8d8bef9SDimitry Andric     if (data.size() < sizeof(Elf_Nhdr) || data.size() < nhdr->getSize())
866e8d8bef9SDimitry Andric       reportFatal(data.data(), "data is too short");
8670b57cec5SDimitry Andric 
8680b57cec5SDimitry Andric     Elf_Note note(*nhdr);
8690b57cec5SDimitry Andric     if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
8700b57cec5SDimitry Andric       data = data.slice(nhdr->getSize());
8710b57cec5SDimitry Andric       continue;
8720b57cec5SDimitry Andric     }
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric     uint32_t featureAndType = config->emachine == EM_AARCH64
8750b57cec5SDimitry Andric                                   ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
8760b57cec5SDimitry Andric                                   : GNU_PROPERTY_X86_FEATURE_1_AND;
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric     // Read a body of a NOTE record, which consists of type-length-value fields.
8790b57cec5SDimitry Andric     ArrayRef<uint8_t> desc = note.getDesc();
8800b57cec5SDimitry Andric     while (!desc.empty()) {
881e8d8bef9SDimitry Andric       const uint8_t *place = desc.data();
8820b57cec5SDimitry Andric       if (desc.size() < 8)
883e8d8bef9SDimitry Andric         reportFatal(place, "program property is too short");
884e8d8bef9SDimitry Andric       uint32_t type = read32<ELFT::TargetEndianness>(desc.data());
885e8d8bef9SDimitry Andric       uint32_t size = read32<ELFT::TargetEndianness>(desc.data() + 4);
886e8d8bef9SDimitry Andric       desc = desc.slice(8);
887e8d8bef9SDimitry Andric       if (desc.size() < size)
888e8d8bef9SDimitry Andric         reportFatal(place, "program property is too short");
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric       if (type == featureAndType) {
8910b57cec5SDimitry Andric         // We found a FEATURE_1_AND field. There may be more than one of these
892480093f4SDimitry Andric         // in a .note.gnu.property section, for a relocatable object we
8930b57cec5SDimitry Andric         // accumulate the bits set.
894e8d8bef9SDimitry Andric         if (size < 4)
895e8d8bef9SDimitry Andric           reportFatal(place, "FEATURE_1_AND entry is too short");
896e8d8bef9SDimitry Andric         featuresSet |= read32<ELFT::TargetEndianness>(desc.data());
8970b57cec5SDimitry Andric       }
8980b57cec5SDimitry Andric 
899e8d8bef9SDimitry Andric       // Padding is present in the note descriptor, if necessary.
900e8d8bef9SDimitry Andric       desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size));
9010b57cec5SDimitry Andric     }
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric     // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
9040b57cec5SDimitry Andric     data = data.slice(nhdr->getSize());
9050b57cec5SDimitry Andric   }
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric   return featuresSet;
9080b57cec5SDimitry Andric }
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric template <class ELFT>
91104eeddc0SDimitry Andric InputSectionBase *ObjFile<ELFT>::getRelocTarget(uint32_t idx,
91204eeddc0SDimitry Andric                                                 const Elf_Shdr &sec,
91304eeddc0SDimitry Andric                                                 uint32_t info) {
914349cc55cSDimitry Andric   if (info < this->sections.size()) {
915349cc55cSDimitry Andric     InputSectionBase *target = this->sections[info];
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric     // Strictly speaking, a relocation section must be included in the
9180b57cec5SDimitry Andric     // group of the section it relocates. However, LLVM 3.3 and earlier
9190b57cec5SDimitry Andric     // would fail to do so, so we gracefully handle that case.
9200b57cec5SDimitry Andric     if (target == &InputSection::discarded)
9210b57cec5SDimitry Andric       return nullptr;
9220b57cec5SDimitry Andric 
923349cc55cSDimitry Andric     if (target != nullptr)
9240b57cec5SDimitry Andric       return target;
9250b57cec5SDimitry Andric   }
9260b57cec5SDimitry Andric 
92704eeddc0SDimitry Andric   error(toString(this) + Twine(": relocation section (index ") + Twine(idx) +
92804eeddc0SDimitry Andric         ") has invalid sh_info (" + Twine(info) + ")");
929349cc55cSDimitry Andric   return nullptr;
930349cc55cSDimitry Andric }
931349cc55cSDimitry Andric 
932*bdd1243dSDimitry Andric // The function may be called concurrently for different input files. For
933*bdd1243dSDimitry Andric // allocation, prefer makeThreadLocal which does not require holding a lock.
9340b57cec5SDimitry Andric template <class ELFT>
935349cc55cSDimitry Andric InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx,
936349cc55cSDimitry Andric                                                     const Elf_Shdr &sec,
9371fd87a68SDimitry Andric                                                     StringRef name) {
9380eae32dcSDimitry Andric   if (name.startswith(".n")) {
9390b57cec5SDimitry Andric     // The GNU linker uses .note.GNU-stack section as a marker indicating
9400b57cec5SDimitry Andric     // that the code in the object file does not expect that the stack is
9410b57cec5SDimitry Andric     // executable (in terms of NX bit). If all input files have the marker,
9420b57cec5SDimitry Andric     // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
9430b57cec5SDimitry Andric     // make the stack non-executable. Most object files have this section as
9440b57cec5SDimitry Andric     // of 2017.
9450b57cec5SDimitry Andric     //
9460b57cec5SDimitry Andric     // But making the stack non-executable is a norm today for security
9470b57cec5SDimitry Andric     // reasons. Failure to do so may result in a serious security issue.
9480b57cec5SDimitry Andric     // Therefore, we make LLD always add PT_GNU_STACK unless it is
9490b57cec5SDimitry Andric     // explicitly told to do otherwise (by -z execstack). Because the stack
9500b57cec5SDimitry Andric     // executable-ness is controlled solely by command line options,
9510b57cec5SDimitry Andric     // .note.GNU-stack sections are simply ignored.
9520b57cec5SDimitry Andric     if (name == ".note.GNU-stack")
9530b57cec5SDimitry Andric       return &InputSection::discarded;
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry Andric     // Object files that use processor features such as Intel Control-Flow
9560b57cec5SDimitry Andric     // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
9570b57cec5SDimitry Andric     // .note.gnu.property section containing a bitfield of feature bits like the
9580b57cec5SDimitry Andric     // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
9590b57cec5SDimitry Andric     //
9600b57cec5SDimitry Andric     // Since we merge bitmaps from multiple object files to create a new
9610b57cec5SDimitry Andric     // .note.gnu.property containing a single AND'ed bitmap, we discard an input
9620b57cec5SDimitry Andric     // file's .note.gnu.property section.
9630b57cec5SDimitry Andric     if (name == ".note.gnu.property") {
964e8d8bef9SDimitry Andric       this->andFeatures = readAndFeatures<ELFT>(InputSection(*this, sec, name));
9650b57cec5SDimitry Andric       return &InputSection::discarded;
9660b57cec5SDimitry Andric     }
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric     // Split stacks is a feature to support a discontiguous stack,
9690b57cec5SDimitry Andric     // commonly used in the programming language Go. For the details,
9700b57cec5SDimitry Andric     // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
9710b57cec5SDimitry Andric     // for split stack will include a .note.GNU-split-stack section.
9720b57cec5SDimitry Andric     if (name == ".note.GNU-split-stack") {
9730b57cec5SDimitry Andric       if (config->relocatable) {
9740eae32dcSDimitry Andric         error(
9750eae32dcSDimitry Andric             "cannot mix split-stack and non-split-stack in a relocatable link");
9760b57cec5SDimitry Andric         return &InputSection::discarded;
9770b57cec5SDimitry Andric       }
9780b57cec5SDimitry Andric       this->splitStack = true;
9790b57cec5SDimitry Andric       return &InputSection::discarded;
9800b57cec5SDimitry Andric     }
9810b57cec5SDimitry Andric 
982*bdd1243dSDimitry Andric     // An object file compiled for split stack, but where some of the
9830b57cec5SDimitry Andric     // functions were compiled with the no_split_stack_attribute will
9840b57cec5SDimitry Andric     // include a .note.GNU-no-split-stack section.
9850b57cec5SDimitry Andric     if (name == ".note.GNU-no-split-stack") {
9860b57cec5SDimitry Andric       this->someNoSplitStack = true;
9870b57cec5SDimitry Andric       return &InputSection::discarded;
9880b57cec5SDimitry Andric     }
9890b57cec5SDimitry Andric 
9900eae32dcSDimitry Andric     // Strip existing .note.gnu.build-id sections so that the output won't have
9910eae32dcSDimitry Andric     // more than one build-id. This is not usually a problem because input
9920eae32dcSDimitry Andric     // object files normally don't have .build-id sections, but you can create
9930eae32dcSDimitry Andric     // such files by "ld.{bfd,gold,lld} -r --build-id", and we want to guard
9940eae32dcSDimitry Andric     // against it.
9950eae32dcSDimitry Andric     if (name == ".note.gnu.build-id")
9960eae32dcSDimitry Andric       return &InputSection::discarded;
9970eae32dcSDimitry Andric   }
9980eae32dcSDimitry Andric 
9990b57cec5SDimitry Andric   // The linker merges EH (exception handling) frames and creates a
10000b57cec5SDimitry Andric   // .eh_frame_hdr section for runtime. So we handle them with a special
10010b57cec5SDimitry Andric   // class. For relocatable outputs, they are just passed through.
10020b57cec5SDimitry Andric   if (name == ".eh_frame" && !config->relocatable)
1003*bdd1243dSDimitry Andric     return makeThreadLocal<EhInputSection>(*this, sec, name);
10040b57cec5SDimitry Andric 
10050eae32dcSDimitry Andric   if ((sec.sh_flags & SHF_MERGE) && shouldMerge(sec, name))
1006*bdd1243dSDimitry Andric     return makeThreadLocal<MergeInputSection>(*this, sec, name);
1007*bdd1243dSDimitry Andric   return makeThreadLocal<InputSection>(*this, sec, name);
10080b57cec5SDimitry Andric }
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric // Initialize this->Symbols. this->Symbols is a parallel array as
10110b57cec5SDimitry Andric // its corresponding ELF symbol table.
10121fd87a68SDimitry Andric template <class ELFT>
10131fd87a68SDimitry Andric void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) {
10140eae32dcSDimitry Andric   ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1015*bdd1243dSDimitry Andric   if (numSymbols == 0) {
1016*bdd1243dSDimitry Andric     numSymbols = eSyms.size();
1017*bdd1243dSDimitry Andric     symbols = std::make_unique<Symbol *[]>(numSymbols);
1018*bdd1243dSDimitry Andric   }
10190eae32dcSDimitry Andric 
102081ad6265SDimitry Andric   // Some entries have been filled by LazyObjFile.
102181ad6265SDimitry Andric   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
102281ad6265SDimitry Andric     if (!symbols[i])
102381ad6265SDimitry Andric       symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this));
102481ad6265SDimitry Andric 
102581ad6265SDimitry Andric   // Perform symbol resolution on non-local symbols.
102681ad6265SDimitry Andric   SmallVector<unsigned, 32> undefineds;
102781ad6265SDimitry Andric   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
102881ad6265SDimitry Andric     const Elf_Sym &eSym = eSyms[i];
102981ad6265SDimitry Andric     uint32_t secIdx = eSym.st_shndx;
103081ad6265SDimitry Andric     if (secIdx == SHN_UNDEF) {
103181ad6265SDimitry Andric       undefineds.push_back(i);
103281ad6265SDimitry Andric       continue;
103381ad6265SDimitry Andric     }
103481ad6265SDimitry Andric 
103581ad6265SDimitry Andric     uint8_t binding = eSym.getBinding();
103681ad6265SDimitry Andric     uint8_t stOther = eSym.st_other;
103781ad6265SDimitry Andric     uint8_t type = eSym.getType();
103881ad6265SDimitry Andric     uint64_t value = eSym.st_value;
103981ad6265SDimitry Andric     uint64_t size = eSym.st_size;
104081ad6265SDimitry Andric 
104181ad6265SDimitry Andric     Symbol *sym = symbols[i];
104281ad6265SDimitry Andric     sym->isUsedInRegularObj = true;
104381ad6265SDimitry Andric     if (LLVM_UNLIKELY(eSym.st_shndx == SHN_COMMON)) {
104481ad6265SDimitry Andric       if (value == 0 || value >= UINT32_MAX)
104581ad6265SDimitry Andric         fatal(toString(this) + ": common symbol '" + sym->getName() +
104681ad6265SDimitry Andric               "' has invalid alignment: " + Twine(value));
104781ad6265SDimitry Andric       hasCommonSyms = true;
104881ad6265SDimitry Andric       sym->resolve(
104981ad6265SDimitry Andric           CommonSymbol{this, StringRef(), binding, stOther, type, value, size});
105081ad6265SDimitry Andric       continue;
105181ad6265SDimitry Andric     }
105281ad6265SDimitry Andric 
105381ad6265SDimitry Andric     // Handle global defined symbols. Defined::section will be set in postParse.
105481ad6265SDimitry Andric     sym->resolve(Defined{this, StringRef(), binding, stOther, type, value, size,
105581ad6265SDimitry Andric                          nullptr});
105681ad6265SDimitry Andric   }
105781ad6265SDimitry Andric 
105881ad6265SDimitry Andric   // Undefined symbols (excluding those defined relative to non-prevailing
105981ad6265SDimitry Andric   // sections) can trigger recursive extract. Process defined symbols first so
106081ad6265SDimitry Andric   // that the relative order between a defined symbol and an undefined symbol
106181ad6265SDimitry Andric   // does not change the symbol resolution behavior. In addition, a set of
106281ad6265SDimitry Andric   // interconnected symbols will all be resolved to the same file, instead of
106381ad6265SDimitry Andric   // being resolved to different files.
106481ad6265SDimitry Andric   for (unsigned i : undefineds) {
106581ad6265SDimitry Andric     const Elf_Sym &eSym = eSyms[i];
106681ad6265SDimitry Andric     Symbol *sym = symbols[i];
106781ad6265SDimitry Andric     sym->resolve(Undefined{this, StringRef(), eSym.getBinding(), eSym.st_other,
106881ad6265SDimitry Andric                            eSym.getType()});
106981ad6265SDimitry Andric     sym->isUsedInRegularObj = true;
107081ad6265SDimitry Andric     sym->referenced = true;
107181ad6265SDimitry Andric   }
107281ad6265SDimitry Andric }
107381ad6265SDimitry Andric 
1074*bdd1243dSDimitry Andric template <class ELFT>
1075*bdd1243dSDimitry Andric void ObjFile<ELFT>::initSectionsAndLocalSyms(bool ignoreComdats) {
1076*bdd1243dSDimitry Andric   if (!justSymbols)
1077*bdd1243dSDimitry Andric     initializeSections(ignoreComdats, getObj());
1078*bdd1243dSDimitry Andric 
107981ad6265SDimitry Andric   if (!firstGlobal)
108081ad6265SDimitry Andric     return;
1081*bdd1243dSDimitry Andric   SymbolUnion *locals = makeThreadLocalN<SymbolUnion>(firstGlobal);
1082*bdd1243dSDimitry Andric   memset(locals, 0, sizeof(SymbolUnion) * firstGlobal);
108381ad6265SDimitry Andric 
108481ad6265SDimitry Andric   ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
10850eae32dcSDimitry Andric   for (size_t i = 0, end = firstGlobal; i != end; ++i) {
10860b57cec5SDimitry Andric     const Elf_Sym &eSym = eSyms[i];
10871fd87a68SDimitry Andric     uint32_t secIdx = eSym.st_shndx;
10881fd87a68SDimitry Andric     if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
10891fd87a68SDimitry Andric       secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
10901fd87a68SDimitry Andric     else if (secIdx >= SHN_LORESERVE)
10911fd87a68SDimitry Andric       secIdx = 0;
10920eae32dcSDimitry Andric     if (LLVM_UNLIKELY(secIdx >= sections.size()))
10930b57cec5SDimitry Andric       fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
10940eae32dcSDimitry Andric     if (LLVM_UNLIKELY(eSym.getBinding() != STB_LOCAL))
10955ffd83dbSDimitry Andric       error(toString(this) + ": non-local symbol (" + Twine(i) +
10960eae32dcSDimitry Andric             ") found at index < .symtab's sh_info (" + Twine(end) + ")");
10975ffd83dbSDimitry Andric 
10980eae32dcSDimitry Andric     InputSectionBase *sec = sections[secIdx];
10995ffd83dbSDimitry Andric     uint8_t type = eSym.getType();
11005ffd83dbSDimitry Andric     if (type == STT_FILE)
11010eae32dcSDimitry Andric       sourceFile = CHECK(eSym.getName(stringTable), this);
11020eae32dcSDimitry Andric     if (LLVM_UNLIKELY(stringTable.size() <= eSym.st_name))
11035ffd83dbSDimitry Andric       fatal(toString(this) + ": invalid symbol name offset");
110404eeddc0SDimitry Andric     StringRef name(stringTable.data() + eSym.st_name);
11055ffd83dbSDimitry Andric 
11060eae32dcSDimitry Andric     symbols[i] = reinterpret_cast<Symbol *>(locals + i);
11070eae32dcSDimitry Andric     if (eSym.st_shndx == SHN_UNDEF || sec == &InputSection::discarded)
11080eae32dcSDimitry Andric       new (symbols[i]) Undefined(this, name, STB_LOCAL, eSym.st_other, type,
11095ffd83dbSDimitry Andric                                  /*discardedSecIdx=*/secIdx);
11105ffd83dbSDimitry Andric     else
11110eae32dcSDimitry Andric       new (symbols[i]) Defined(this, name, STB_LOCAL, eSym.st_other, type,
11120eae32dcSDimitry Andric                                eSym.st_value, eSym.st_size, sec);
1113*bdd1243dSDimitry Andric     symbols[i]->partition = 1;
111481ad6265SDimitry Andric     symbols[i]->isUsedInRegularObj = true;
111581ad6265SDimitry Andric   }
11165ffd83dbSDimitry Andric }
11175ffd83dbSDimitry Andric 
111881ad6265SDimitry Andric // Called after all ObjFile::parse is called for all ObjFiles. This checks
111981ad6265SDimitry Andric // duplicate symbols and may do symbol property merge in the future.
112081ad6265SDimitry Andric template <class ELFT> void ObjFile<ELFT>::postParse() {
112181ad6265SDimitry Andric   static std::mutex mu;
112281ad6265SDimitry Andric   ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
11235ffd83dbSDimitry Andric   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
11245ffd83dbSDimitry Andric     const Elf_Sym &eSym = eSyms[i];
112581ad6265SDimitry Andric     Symbol &sym = *symbols[i];
11261fd87a68SDimitry Andric     uint32_t secIdx = eSym.st_shndx;
112781ad6265SDimitry Andric     uint8_t binding = eSym.getBinding();
112881ad6265SDimitry Andric     if (LLVM_UNLIKELY(binding != STB_GLOBAL && binding != STB_WEAK &&
112981ad6265SDimitry Andric                       binding != STB_GNU_UNIQUE))
113081ad6265SDimitry Andric       errorOrWarn(toString(this) + ": symbol (" + Twine(i) +
113181ad6265SDimitry Andric                   ") has invalid binding: " + Twine((int)binding));
113281ad6265SDimitry Andric 
113381ad6265SDimitry Andric     // st_value of STT_TLS represents the assigned offset, not the actual
113481ad6265SDimitry Andric     // address which is used by STT_FUNC and STT_OBJECT. STT_TLS symbols can
113581ad6265SDimitry Andric     // only be referenced by special TLS relocations. It is usually an error if
113681ad6265SDimitry Andric     // a STT_TLS symbol is replaced by a non-STT_TLS symbol, vice versa.
113781ad6265SDimitry Andric     if (LLVM_UNLIKELY(sym.isTls()) && eSym.getType() != STT_TLS &&
113881ad6265SDimitry Andric         eSym.getType() != STT_NOTYPE)
113981ad6265SDimitry Andric       errorOrWarn("TLS attribute mismatch: " + toString(sym) + "\n>>> in " +
114081ad6265SDimitry Andric                   toString(sym.file) + "\n>>> in " + toString(this));
114181ad6265SDimitry Andric 
114281ad6265SDimitry Andric     // Handle non-COMMON defined symbol below. !sym.file allows a symbol
114381ad6265SDimitry Andric     // assignment to redefine a symbol without an error.
114481ad6265SDimitry Andric     if (!sym.file || !sym.isDefined() || secIdx == SHN_UNDEF ||
114581ad6265SDimitry Andric         secIdx == SHN_COMMON)
114681ad6265SDimitry Andric       continue;
114781ad6265SDimitry Andric 
11481fd87a68SDimitry Andric     if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
11491fd87a68SDimitry Andric       secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
11501fd87a68SDimitry Andric     else if (secIdx >= SHN_LORESERVE)
11511fd87a68SDimitry Andric       secIdx = 0;
11520eae32dcSDimitry Andric     if (LLVM_UNLIKELY(secIdx >= sections.size()))
11530eae32dcSDimitry Andric       fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
11540eae32dcSDimitry Andric     InputSectionBase *sec = sections[secIdx];
11550b57cec5SDimitry Andric     if (sec == &InputSection::discarded) {
115681ad6265SDimitry Andric       if (sym.traced) {
115781ad6265SDimitry Andric         printTraceSymbol(Undefined{this, sym.getName(), sym.binding,
115881ad6265SDimitry Andric                                    sym.stOther, sym.type, secIdx},
115981ad6265SDimitry Andric                          sym.getName());
116081ad6265SDimitry Andric       }
116181ad6265SDimitry Andric       if (sym.file == this) {
116281ad6265SDimitry Andric         std::lock_guard<std::mutex> lock(mu);
1163*bdd1243dSDimitry Andric         ctx.nonPrevailingSyms.emplace_back(&sym, secIdx);
116481ad6265SDimitry Andric       }
11650b57cec5SDimitry Andric       continue;
11660b57cec5SDimitry Andric     }
11670b57cec5SDimitry Andric 
116881ad6265SDimitry Andric     if (sym.file == this) {
116981ad6265SDimitry Andric       cast<Defined>(sym).section = sec;
11700b57cec5SDimitry Andric       continue;
11710b57cec5SDimitry Andric     }
11720b57cec5SDimitry Andric 
1173f3fd488fSDimitry Andric     if (sym.binding == STB_WEAK || binding == STB_WEAK)
117481ad6265SDimitry Andric       continue;
117581ad6265SDimitry Andric     std::lock_guard<std::mutex> lock(mu);
1176*bdd1243dSDimitry Andric     ctx.duplicates.push_back({&sym, this, sec, eSym.st_value});
11770b57cec5SDimitry Andric   }
11780b57cec5SDimitry Andric }
11790b57cec5SDimitry Andric 
1180e8d8bef9SDimitry Andric // The handling of tentative definitions (COMMON symbols) in archives is murky.
1181fe6060f1SDimitry Andric // A tentative definition will be promoted to a global definition if there are
1182fe6060f1SDimitry Andric // no non-tentative definitions to dominate it. When we hold a tentative
1183fe6060f1SDimitry Andric // definition to a symbol and are inspecting archive members for inclusion
1184fe6060f1SDimitry Andric // there are 2 ways we can proceed:
1185e8d8bef9SDimitry Andric //
1186e8d8bef9SDimitry Andric // 1) Consider the tentative definition a 'real' definition (ie promotion from
1187e8d8bef9SDimitry Andric //    tentative to real definition has already happened) and not inspect
1188e8d8bef9SDimitry Andric //    archive members for Global/Weak definitions to replace the tentative
1189e8d8bef9SDimitry Andric //    definition. An archive member would only be included if it satisfies some
1190e8d8bef9SDimitry Andric //    other undefined symbol. This is the behavior Gold uses.
1191e8d8bef9SDimitry Andric //
1192e8d8bef9SDimitry Andric // 2) Consider the tentative definition as still undefined (ie the promotion to
1193fe6060f1SDimitry Andric //    a real definition happens only after all symbol resolution is done).
1194fe6060f1SDimitry Andric //    The linker searches archive members for STB_GLOBAL definitions to
1195e8d8bef9SDimitry Andric //    replace the tentative definition with. This is the behavior used by
1196e8d8bef9SDimitry Andric //    GNU ld.
1197e8d8bef9SDimitry Andric //
1198e8d8bef9SDimitry Andric //  The second behavior is inherited from SysVR4, which based it on the FORTRAN
1199fe6060f1SDimitry Andric //  COMMON BLOCK model. This behavior is needed for proper initialization in old
1200e8d8bef9SDimitry Andric //  (pre F90) FORTRAN code that is packaged into an archive.
1201e8d8bef9SDimitry Andric //
1202fe6060f1SDimitry Andric //  The following functions search archive members for definitions to replace
1203fe6060f1SDimitry Andric //  tentative definitions (implementing behavior 2).
1204e8d8bef9SDimitry Andric static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName,
1205e8d8bef9SDimitry Andric                                   StringRef archiveName) {
1206e8d8bef9SDimitry Andric   IRSymtabFile symtabFile = check(readIRSymtab(mb));
1207e8d8bef9SDimitry Andric   for (const irsymtab::Reader::SymbolRef &sym :
1208e8d8bef9SDimitry Andric        symtabFile.TheReader.symbols()) {
1209e8d8bef9SDimitry Andric     if (sym.isGlobal() && sym.getName() == symName)
1210fe6060f1SDimitry Andric       return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon();
1211e8d8bef9SDimitry Andric   }
1212e8d8bef9SDimitry Andric   return false;
1213e8d8bef9SDimitry Andric }
1214e8d8bef9SDimitry Andric 
1215e8d8bef9SDimitry Andric template <class ELFT>
1216*bdd1243dSDimitry Andric static bool isNonCommonDef(ELFKind ekind, MemoryBufferRef mb, StringRef symName,
1217e8d8bef9SDimitry Andric                            StringRef archiveName) {
1218*bdd1243dSDimitry Andric   ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(ekind, mb, archiveName);
1219*bdd1243dSDimitry Andric   obj->init();
1220e8d8bef9SDimitry Andric   StringRef stringtable = obj->getStringTable();
1221e8d8bef9SDimitry Andric 
1222e8d8bef9SDimitry Andric   for (auto sym : obj->template getGlobalELFSyms<ELFT>()) {
1223e8d8bef9SDimitry Andric     Expected<StringRef> name = sym.getName(stringtable);
1224e8d8bef9SDimitry Andric     if (name && name.get() == symName)
1225fe6060f1SDimitry Andric       return sym.isDefined() && sym.getBinding() == STB_GLOBAL &&
1226fe6060f1SDimitry Andric              !sym.isCommon();
1227e8d8bef9SDimitry Andric   }
1228e8d8bef9SDimitry Andric   return false;
1229e8d8bef9SDimitry Andric }
1230e8d8bef9SDimitry Andric 
1231e8d8bef9SDimitry Andric static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName,
1232e8d8bef9SDimitry Andric                            StringRef archiveName) {
1233e8d8bef9SDimitry Andric   switch (getELFKind(mb, archiveName)) {
1234e8d8bef9SDimitry Andric   case ELF32LEKind:
1235*bdd1243dSDimitry Andric     return isNonCommonDef<ELF32LE>(ELF32LEKind, mb, symName, archiveName);
1236e8d8bef9SDimitry Andric   case ELF32BEKind:
1237*bdd1243dSDimitry Andric     return isNonCommonDef<ELF32BE>(ELF32BEKind, mb, symName, archiveName);
1238e8d8bef9SDimitry Andric   case ELF64LEKind:
1239*bdd1243dSDimitry Andric     return isNonCommonDef<ELF64LE>(ELF64LEKind, mb, symName, archiveName);
1240e8d8bef9SDimitry Andric   case ELF64BEKind:
1241*bdd1243dSDimitry Andric     return isNonCommonDef<ELF64BE>(ELF64BEKind, mb, symName, archiveName);
1242e8d8bef9SDimitry Andric   default:
1243e8d8bef9SDimitry Andric     llvm_unreachable("getELFKind");
1244e8d8bef9SDimitry Andric   }
1245e8d8bef9SDimitry Andric }
1246e8d8bef9SDimitry Andric 
12470b57cec5SDimitry Andric unsigned SharedFile::vernauxNum;
12480b57cec5SDimitry Andric 
1249*bdd1243dSDimitry Andric SharedFile::SharedFile(MemoryBufferRef m, StringRef defaultSoName)
1250*bdd1243dSDimitry Andric     : ELFFileBase(SharedKind, getELFKind(m, ""), m), soName(defaultSoName),
1251*bdd1243dSDimitry Andric       isNeeded(!config->asNeeded) {}
1252*bdd1243dSDimitry Andric 
12530b57cec5SDimitry Andric // Parse the version definitions in the object file if present, and return a
12540b57cec5SDimitry Andric // vector whose nth element contains a pointer to the Elf_Verdef for version
12550b57cec5SDimitry Andric // identifier n. Version identifiers that are not definitions map to nullptr.
12560b57cec5SDimitry Andric template <typename ELFT>
12570eae32dcSDimitry Andric static SmallVector<const void *, 0>
12580eae32dcSDimitry Andric parseVerdefs(const uint8_t *base, const typename ELFT::Shdr *sec) {
12590b57cec5SDimitry Andric   if (!sec)
12600b57cec5SDimitry Andric     return {};
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric   // Build the Verdefs array by following the chain of Elf_Verdef objects
12630b57cec5SDimitry Andric   // from the start of the .gnu.version_d section.
12640eae32dcSDimitry Andric   SmallVector<const void *, 0> verdefs;
12650b57cec5SDimitry Andric   const uint8_t *verdef = base + sec->sh_offset;
12660eae32dcSDimitry Andric   for (unsigned i = 0, e = sec->sh_info; i != e; ++i) {
12670b57cec5SDimitry Andric     auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
12680b57cec5SDimitry Andric     verdef += curVerdef->vd_next;
12690b57cec5SDimitry Andric     unsigned verdefIndex = curVerdef->vd_ndx;
12700eae32dcSDimitry Andric     if (verdefIndex >= verdefs.size())
12710b57cec5SDimitry Andric       verdefs.resize(verdefIndex + 1);
12720b57cec5SDimitry Andric     verdefs[verdefIndex] = curVerdef;
12730b57cec5SDimitry Andric   }
12740b57cec5SDimitry Andric   return verdefs;
12750b57cec5SDimitry Andric }
12760b57cec5SDimitry Andric 
12775ffd83dbSDimitry Andric // Parse SHT_GNU_verneed to properly set the name of a versioned undefined
12785ffd83dbSDimitry Andric // symbol. We detect fatal issues which would cause vulnerabilities, but do not
12795ffd83dbSDimitry Andric // implement sophisticated error checking like in llvm-readobj because the value
12805ffd83dbSDimitry Andric // of such diagnostics is low.
12815ffd83dbSDimitry Andric template <typename ELFT>
12825ffd83dbSDimitry Andric std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
12835ffd83dbSDimitry Andric                                                const typename ELFT::Shdr *sec) {
12845ffd83dbSDimitry Andric   if (!sec)
12855ffd83dbSDimitry Andric     return {};
12865ffd83dbSDimitry Andric   std::vector<uint32_t> verneeds;
1287e8d8bef9SDimitry Andric   ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(*sec), this);
12885ffd83dbSDimitry Andric   const uint8_t *verneedBuf = data.begin();
12895ffd83dbSDimitry Andric   for (unsigned i = 0; i != sec->sh_info; ++i) {
12905ffd83dbSDimitry Andric     if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end())
12915ffd83dbSDimitry Andric       fatal(toString(this) + " has an invalid Verneed");
12925ffd83dbSDimitry Andric     auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
12935ffd83dbSDimitry Andric     const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
12945ffd83dbSDimitry Andric     for (unsigned j = 0; j != vn->vn_cnt; ++j) {
12955ffd83dbSDimitry Andric       if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end())
12965ffd83dbSDimitry Andric         fatal(toString(this) + " has an invalid Vernaux");
12975ffd83dbSDimitry Andric       auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
12985ffd83dbSDimitry Andric       if (aux->vna_name >= this->stringTable.size())
12995ffd83dbSDimitry Andric         fatal(toString(this) + " has a Vernaux with an invalid vna_name");
13005ffd83dbSDimitry Andric       uint16_t version = aux->vna_other & VERSYM_VERSION;
13015ffd83dbSDimitry Andric       if (version >= verneeds.size())
13025ffd83dbSDimitry Andric         verneeds.resize(version + 1);
13035ffd83dbSDimitry Andric       verneeds[version] = aux->vna_name;
13045ffd83dbSDimitry Andric       vernauxBuf += aux->vna_next;
13055ffd83dbSDimitry Andric     }
13065ffd83dbSDimitry Andric     verneedBuf += vn->vn_next;
13075ffd83dbSDimitry Andric   }
13085ffd83dbSDimitry Andric   return verneeds;
13095ffd83dbSDimitry Andric }
13105ffd83dbSDimitry Andric 
13110b57cec5SDimitry Andric // We do not usually care about alignments of data in shared object
13120b57cec5SDimitry Andric // files because the loader takes care of it. However, if we promote a
13130b57cec5SDimitry Andric // DSO symbol to point to .bss due to copy relocation, we need to keep
13140b57cec5SDimitry Andric // the original alignment requirements. We infer it in this function.
13150b57cec5SDimitry Andric template <typename ELFT>
13160b57cec5SDimitry Andric static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
13170b57cec5SDimitry Andric                              const typename ELFT::Sym &sym) {
13180b57cec5SDimitry Andric   uint64_t ret = UINT64_MAX;
13190b57cec5SDimitry Andric   if (sym.st_value)
13200b57cec5SDimitry Andric     ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
13210b57cec5SDimitry Andric   if (0 < sym.st_shndx && sym.st_shndx < sections.size())
13220b57cec5SDimitry Andric     ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
13230b57cec5SDimitry Andric   return (ret > UINT32_MAX) ? 0 : ret;
13240b57cec5SDimitry Andric }
13250b57cec5SDimitry Andric 
13260b57cec5SDimitry Andric // Fully parse the shared object file.
13270b57cec5SDimitry Andric //
13280b57cec5SDimitry Andric // This function parses symbol versions. If a DSO has version information,
13290b57cec5SDimitry Andric // the file has a ".gnu.version_d" section which contains symbol version
13300b57cec5SDimitry Andric // definitions. Each symbol is associated to one version through a table in
13310b57cec5SDimitry Andric // ".gnu.version" section. That table is a parallel array for the symbol
13320b57cec5SDimitry Andric // table, and each table entry contains an index in ".gnu.version_d".
13330b57cec5SDimitry Andric //
13340b57cec5SDimitry Andric // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
13350b57cec5SDimitry Andric // VER_NDX_GLOBAL. There's no table entry for these special versions in
13360b57cec5SDimitry Andric // ".gnu.version_d".
13370b57cec5SDimitry Andric //
13380b57cec5SDimitry Andric // The file format for symbol versioning is perhaps a bit more complicated
13390b57cec5SDimitry Andric // than necessary, but you can easily understand the code if you wrap your
13400b57cec5SDimitry Andric // head around the data structure described above.
13410b57cec5SDimitry Andric template <class ELFT> void SharedFile::parse() {
13420b57cec5SDimitry Andric   using Elf_Dyn = typename ELFT::Dyn;
13430b57cec5SDimitry Andric   using Elf_Shdr = typename ELFT::Shdr;
13440b57cec5SDimitry Andric   using Elf_Sym = typename ELFT::Sym;
13450b57cec5SDimitry Andric   using Elf_Verdef = typename ELFT::Verdef;
13460b57cec5SDimitry Andric   using Elf_Versym = typename ELFT::Versym;
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric   ArrayRef<Elf_Dyn> dynamicTags;
13490b57cec5SDimitry Andric   const ELFFile<ELFT> obj = this->getObj<ELFT>();
13500eae32dcSDimitry Andric   ArrayRef<Elf_Shdr> sections = getELFShdrs<ELFT>();
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric   const Elf_Shdr *versymSec = nullptr;
13530b57cec5SDimitry Andric   const Elf_Shdr *verdefSec = nullptr;
13545ffd83dbSDimitry Andric   const Elf_Shdr *verneedSec = nullptr;
13550b57cec5SDimitry Andric 
13560b57cec5SDimitry Andric   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
13570b57cec5SDimitry Andric   for (const Elf_Shdr &sec : sections) {
13580b57cec5SDimitry Andric     switch (sec.sh_type) {
13590b57cec5SDimitry Andric     default:
13600b57cec5SDimitry Andric       continue;
13610b57cec5SDimitry Andric     case SHT_DYNAMIC:
13620b57cec5SDimitry Andric       dynamicTags =
1363e8d8bef9SDimitry Andric           CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this);
13640b57cec5SDimitry Andric       break;
13650b57cec5SDimitry Andric     case SHT_GNU_versym:
13660b57cec5SDimitry Andric       versymSec = &sec;
13670b57cec5SDimitry Andric       break;
13680b57cec5SDimitry Andric     case SHT_GNU_verdef:
13690b57cec5SDimitry Andric       verdefSec = &sec;
13700b57cec5SDimitry Andric       break;
13715ffd83dbSDimitry Andric     case SHT_GNU_verneed:
13725ffd83dbSDimitry Andric       verneedSec = &sec;
13735ffd83dbSDimitry Andric       break;
13740b57cec5SDimitry Andric     }
13750b57cec5SDimitry Andric   }
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric   if (versymSec && numELFSyms == 0) {
13780b57cec5SDimitry Andric     error("SHT_GNU_versym should be associated with symbol table");
13790b57cec5SDimitry Andric     return;
13800b57cec5SDimitry Andric   }
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric   // Search for a DT_SONAME tag to initialize this->soName.
13830b57cec5SDimitry Andric   for (const Elf_Dyn &dyn : dynamicTags) {
13840b57cec5SDimitry Andric     if (dyn.d_tag == DT_NEEDED) {
13850b57cec5SDimitry Andric       uint64_t val = dyn.getVal();
13860b57cec5SDimitry Andric       if (val >= this->stringTable.size())
13870b57cec5SDimitry Andric         fatal(toString(this) + ": invalid DT_NEEDED entry");
13880b57cec5SDimitry Andric       dtNeeded.push_back(this->stringTable.data() + val);
13890b57cec5SDimitry Andric     } else if (dyn.d_tag == DT_SONAME) {
13900b57cec5SDimitry Andric       uint64_t val = dyn.getVal();
13910b57cec5SDimitry Andric       if (val >= this->stringTable.size())
13920b57cec5SDimitry Andric         fatal(toString(this) + ": invalid DT_SONAME entry");
13930b57cec5SDimitry Andric       soName = this->stringTable.data() + val;
13940b57cec5SDimitry Andric     }
13950b57cec5SDimitry Andric   }
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric   // DSOs are uniquified not by filename but by soname.
139804eeddc0SDimitry Andric   DenseMap<CachedHashStringRef, SharedFile *>::iterator it;
13990b57cec5SDimitry Andric   bool wasInserted;
140004eeddc0SDimitry Andric   std::tie(it, wasInserted) =
1401*bdd1243dSDimitry Andric       symtab.soNames.try_emplace(CachedHashStringRef(soName), this);
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   // If a DSO appears more than once on the command line with and without
14040b57cec5SDimitry Andric   // --as-needed, --no-as-needed takes precedence over --as-needed because a
14050b57cec5SDimitry Andric   // user can add an extra DSO with --no-as-needed to force it to be added to
14060b57cec5SDimitry Andric   // the dependency list.
14070b57cec5SDimitry Andric   it->second->isNeeded |= isNeeded;
14080b57cec5SDimitry Andric   if (!wasInserted)
14090b57cec5SDimitry Andric     return;
14100b57cec5SDimitry Andric 
1411*bdd1243dSDimitry Andric   ctx.sharedFiles.push_back(this);
14120b57cec5SDimitry Andric 
14130b57cec5SDimitry Andric   verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
14145ffd83dbSDimitry Andric   std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
14150b57cec5SDimitry Andric 
14160b57cec5SDimitry Andric   // Parse ".gnu.version" section which is a parallel array for the symbol
14170b57cec5SDimitry Andric   // table. If a given file doesn't have a ".gnu.version" section, we use
14180b57cec5SDimitry Andric   // VER_NDX_GLOBAL.
14190b57cec5SDimitry Andric   size_t size = numELFSyms - firstGlobal;
14205ffd83dbSDimitry Andric   std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
14210b57cec5SDimitry Andric   if (versymSec) {
14220b57cec5SDimitry Andric     ArrayRef<Elf_Versym> versym =
1423e8d8bef9SDimitry Andric         CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec),
14240b57cec5SDimitry Andric               this)
14250b57cec5SDimitry Andric             .slice(firstGlobal);
14260b57cec5SDimitry Andric     for (size_t i = 0; i < size; ++i)
14270b57cec5SDimitry Andric       versyms[i] = versym[i].vs_index;
14280b57cec5SDimitry Andric   }
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric   // System libraries can have a lot of symbols with versions. Using a
14310b57cec5SDimitry Andric   // fixed buffer for computing the versions name (foo@ver) can save a
14320b57cec5SDimitry Andric   // lot of allocations.
14330b57cec5SDimitry Andric   SmallString<0> versionedNameBuffer;
14340b57cec5SDimitry Andric 
14350b57cec5SDimitry Andric   // Add symbols to the symbol table.
14360b57cec5SDimitry Andric   ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
14370eae32dcSDimitry Andric   for (size_t i = 0, e = syms.size(); i != e; ++i) {
14380b57cec5SDimitry Andric     const Elf_Sym &sym = syms[i];
14390b57cec5SDimitry Andric 
14400b57cec5SDimitry Andric     // ELF spec requires that all local symbols precede weak or global
14410b57cec5SDimitry Andric     // symbols in each symbol table, and the index of first non-local symbol
14420b57cec5SDimitry Andric     // is stored to sh_info. If a local symbol appears after some non-local
14430b57cec5SDimitry Andric     // symbol, that's a violation of the spec.
14440eae32dcSDimitry Andric     StringRef name = CHECK(sym.getName(stringTable), this);
14450b57cec5SDimitry Andric     if (sym.getBinding() == STB_LOCAL) {
1446*bdd1243dSDimitry Andric       errorOrWarn(toString(this) + ": invalid local symbol '" + name +
1447*bdd1243dSDimitry Andric                   "' in global part of symbol table");
14480b57cec5SDimitry Andric       continue;
14490b57cec5SDimitry Andric     }
14500b57cec5SDimitry Andric 
1451*bdd1243dSDimitry Andric     const uint16_t ver = versyms[i], idx = ver & ~VERSYM_HIDDEN;
14520b57cec5SDimitry Andric     if (sym.isUndefined()) {
14535ffd83dbSDimitry Andric       // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but
14545ffd83dbSDimitry Andric       // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL.
1455*bdd1243dSDimitry Andric       if (ver != VER_NDX_LOCAL && ver != VER_NDX_GLOBAL) {
14565ffd83dbSDimitry Andric         if (idx >= verneeds.size()) {
14575ffd83dbSDimitry Andric           error("corrupt input file: version need index " + Twine(idx) +
14585ffd83dbSDimitry Andric                 " for symbol " + name + " is out of bounds\n>>> defined in " +
14595ffd83dbSDimitry Andric                 toString(this));
14605ffd83dbSDimitry Andric           continue;
14615ffd83dbSDimitry Andric         }
14620eae32dcSDimitry Andric         StringRef verName = stringTable.data() + verneeds[idx];
14635ffd83dbSDimitry Andric         versionedNameBuffer.clear();
146404eeddc0SDimitry Andric         name = saver().save(
146504eeddc0SDimitry Andric             (name + "@" + verName).toStringRef(versionedNameBuffer));
14665ffd83dbSDimitry Andric       }
14670eae32dcSDimitry Andric       Symbol *s = symtab.addSymbol(
14680b57cec5SDimitry Andric           Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
14690b57cec5SDimitry Andric       s->exportDynamic = true;
14700eae32dcSDimitry Andric       if (s->isUndefined() && sym.getBinding() != STB_WEAK &&
1471fe6060f1SDimitry Andric           config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore)
1472fe6060f1SDimitry Andric         requiredSymbols.push_back(s);
14730b57cec5SDimitry Andric       continue;
14740b57cec5SDimitry Andric     }
14750b57cec5SDimitry Andric 
1476*bdd1243dSDimitry Andric     if (ver == VER_NDX_LOCAL ||
1477*bdd1243dSDimitry Andric         (ver != VER_NDX_GLOBAL && idx >= verdefs.size())) {
1478*bdd1243dSDimitry Andric       // In GNU ld < 2.31 (before 3be08ea4728b56d35e136af4e6fd3086ade17764), the
1479*bdd1243dSDimitry Andric       // MIPS port puts _gp_disp symbol into DSO files and incorrectly assigns
1480*bdd1243dSDimitry Andric       // VER_NDX_LOCAL. Workaround this bug.
1481*bdd1243dSDimitry Andric       if (config->emachine == EM_MIPS && name == "_gp_disp")
14820b57cec5SDimitry Andric         continue;
14830b57cec5SDimitry Andric       error("corrupt input file: version definition index " + Twine(idx) +
14840b57cec5SDimitry Andric             " for symbol " + name + " is out of bounds\n>>> defined in " +
14850b57cec5SDimitry Andric             toString(this));
14860b57cec5SDimitry Andric       continue;
14870b57cec5SDimitry Andric     }
14880b57cec5SDimitry Andric 
1489*bdd1243dSDimitry Andric     uint32_t alignment = getAlignment<ELFT>(sections, sym);
1490*bdd1243dSDimitry Andric     if (ver == idx) {
1491*bdd1243dSDimitry Andric       auto *s = symtab.addSymbol(
1492*bdd1243dSDimitry Andric           SharedSymbol{*this, name, sym.getBinding(), sym.st_other,
1493*bdd1243dSDimitry Andric                        sym.getType(), sym.st_value, sym.st_size, alignment});
1494*bdd1243dSDimitry Andric       if (s->file == this)
1495*bdd1243dSDimitry Andric         s->verdefIndex = ver;
1496*bdd1243dSDimitry Andric     }
1497*bdd1243dSDimitry Andric 
1498*bdd1243dSDimitry Andric     // Also add the symbol with the versioned name to handle undefined symbols
1499*bdd1243dSDimitry Andric     // with explicit versions.
1500*bdd1243dSDimitry Andric     if (ver == VER_NDX_GLOBAL)
1501*bdd1243dSDimitry Andric       continue;
1502*bdd1243dSDimitry Andric 
15030b57cec5SDimitry Andric     StringRef verName =
15040eae32dcSDimitry Andric         stringTable.data() +
15050b57cec5SDimitry Andric         reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
15060b57cec5SDimitry Andric     versionedNameBuffer.clear();
15070b57cec5SDimitry Andric     name = (name + "@" + verName).toStringRef(versionedNameBuffer);
150881ad6265SDimitry Andric     auto *s = symtab.addSymbol(
150981ad6265SDimitry Andric         SharedSymbol{*this, saver().save(name), sym.getBinding(), sym.st_other,
151081ad6265SDimitry Andric                      sym.getType(), sym.st_value, sym.st_size, alignment});
151181ad6265SDimitry Andric     if (s->file == this)
151281ad6265SDimitry Andric       s->verdefIndex = idx;
15130b57cec5SDimitry Andric   }
15140b57cec5SDimitry Andric }
15150b57cec5SDimitry Andric 
15160b57cec5SDimitry Andric static ELFKind getBitcodeELFKind(const Triple &t) {
15170b57cec5SDimitry Andric   if (t.isLittleEndian())
15180b57cec5SDimitry Andric     return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
15190b57cec5SDimitry Andric   return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
15200b57cec5SDimitry Andric }
15210b57cec5SDimitry Andric 
1522e8d8bef9SDimitry Andric static uint16_t getBitcodeMachineKind(StringRef path, const Triple &t) {
15230b57cec5SDimitry Andric   switch (t.getArch()) {
15240b57cec5SDimitry Andric   case Triple::aarch64:
1525fe6060f1SDimitry Andric   case Triple::aarch64_be:
15260b57cec5SDimitry Andric     return EM_AARCH64;
15270b57cec5SDimitry Andric   case Triple::amdgcn:
15280b57cec5SDimitry Andric   case Triple::r600:
15290b57cec5SDimitry Andric     return EM_AMDGPU;
15300b57cec5SDimitry Andric   case Triple::arm:
15310b57cec5SDimitry Andric   case Triple::thumb:
15320b57cec5SDimitry Andric     return EM_ARM;
15330b57cec5SDimitry Andric   case Triple::avr:
15340b57cec5SDimitry Andric     return EM_AVR;
1535349cc55cSDimitry Andric   case Triple::hexagon:
1536349cc55cSDimitry Andric     return EM_HEXAGON;
15370b57cec5SDimitry Andric   case Triple::mips:
15380b57cec5SDimitry Andric   case Triple::mipsel:
15390b57cec5SDimitry Andric   case Triple::mips64:
15400b57cec5SDimitry Andric   case Triple::mips64el:
15410b57cec5SDimitry Andric     return EM_MIPS;
15420b57cec5SDimitry Andric   case Triple::msp430:
15430b57cec5SDimitry Andric     return EM_MSP430;
15440b57cec5SDimitry Andric   case Triple::ppc:
1545e8d8bef9SDimitry Andric   case Triple::ppcle:
15460b57cec5SDimitry Andric     return EM_PPC;
15470b57cec5SDimitry Andric   case Triple::ppc64:
15480b57cec5SDimitry Andric   case Triple::ppc64le:
15490b57cec5SDimitry Andric     return EM_PPC64;
15500b57cec5SDimitry Andric   case Triple::riscv32:
15510b57cec5SDimitry Andric   case Triple::riscv64:
15520b57cec5SDimitry Andric     return EM_RISCV;
15530b57cec5SDimitry Andric   case Triple::x86:
15540b57cec5SDimitry Andric     return t.isOSIAMCU() ? EM_IAMCU : EM_386;
15550b57cec5SDimitry Andric   case Triple::x86_64:
15560b57cec5SDimitry Andric     return EM_X86_64;
15570b57cec5SDimitry Andric   default:
15580b57cec5SDimitry Andric     error(path + ": could not infer e_machine from bitcode target triple " +
15590b57cec5SDimitry Andric           t.str());
15600b57cec5SDimitry Andric     return EM_NONE;
15610b57cec5SDimitry Andric   }
15620b57cec5SDimitry Andric }
15630b57cec5SDimitry Andric 
1564e8d8bef9SDimitry Andric static uint8_t getOsAbi(const Triple &t) {
1565e8d8bef9SDimitry Andric   switch (t.getOS()) {
1566e8d8bef9SDimitry Andric   case Triple::AMDHSA:
1567e8d8bef9SDimitry Andric     return ELF::ELFOSABI_AMDGPU_HSA;
1568e8d8bef9SDimitry Andric   case Triple::AMDPAL:
1569e8d8bef9SDimitry Andric     return ELF::ELFOSABI_AMDGPU_PAL;
1570e8d8bef9SDimitry Andric   case Triple::Mesa3D:
1571e8d8bef9SDimitry Andric     return ELF::ELFOSABI_AMDGPU_MESA3D;
1572e8d8bef9SDimitry Andric   default:
1573e8d8bef9SDimitry Andric     return ELF::ELFOSABI_NONE;
1574e8d8bef9SDimitry Andric   }
1575e8d8bef9SDimitry Andric }
1576e8d8bef9SDimitry Andric 
15770b57cec5SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
15780eae32dcSDimitry Andric                          uint64_t offsetInArchive, bool lazy)
15790b57cec5SDimitry Andric     : InputFile(BitcodeKind, mb) {
15800eae32dcSDimitry Andric   this->archiveName = archiveName;
15810eae32dcSDimitry Andric   this->lazy = lazy;
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric   std::string path = mb.getBufferIdentifier().str();
15840b57cec5SDimitry Andric   if (config->thinLTOIndexOnly)
15850b57cec5SDimitry Andric     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
15880b57cec5SDimitry Andric   // name. If two archives define two members with the same name, this
15890b57cec5SDimitry Andric   // causes a collision which result in only one of the objects being taken
15900b57cec5SDimitry Andric   // into consideration at LTO time (which very likely causes undefined
15910b57cec5SDimitry Andric   // symbols later in the link stage). So we append file offset to make
15920b57cec5SDimitry Andric   // filename unique.
159304eeddc0SDimitry Andric   StringRef name = archiveName.empty()
159404eeddc0SDimitry Andric                        ? saver().save(path)
159504eeddc0SDimitry Andric                        : saver().save(archiveName + "(" + path::filename(path) +
159604eeddc0SDimitry Andric                                       " at " + utostr(offsetInArchive) + ")");
15970b57cec5SDimitry Andric   MemoryBufferRef mbref(mb.getBuffer(), name);
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric   obj = CHECK(lto::InputFile::create(mbref), this);
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric   Triple t(obj->getTargetTriple());
16020b57cec5SDimitry Andric   ekind = getBitcodeELFKind(t);
16030b57cec5SDimitry Andric   emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t);
1604e8d8bef9SDimitry Andric   osabi = getOsAbi(t);
16050b57cec5SDimitry Andric }
16060b57cec5SDimitry Andric 
16070b57cec5SDimitry Andric static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
16080b57cec5SDimitry Andric   switch (gvVisibility) {
16090b57cec5SDimitry Andric   case GlobalValue::DefaultVisibility:
16100b57cec5SDimitry Andric     return STV_DEFAULT;
16110b57cec5SDimitry Andric   case GlobalValue::HiddenVisibility:
16120b57cec5SDimitry Andric     return STV_HIDDEN;
16130b57cec5SDimitry Andric   case GlobalValue::ProtectedVisibility:
16140b57cec5SDimitry Andric     return STV_PROTECTED;
16150b57cec5SDimitry Andric   }
16160b57cec5SDimitry Andric   llvm_unreachable("unknown visibility");
16170b57cec5SDimitry Andric }
16180b57cec5SDimitry Andric 
161904eeddc0SDimitry Andric static void
162004eeddc0SDimitry Andric createBitcodeSymbol(Symbol *&sym, const std::vector<bool> &keptComdats,
162104eeddc0SDimitry Andric                     const lto::InputFile::Symbol &objSym, BitcodeFile &f) {
16220b57cec5SDimitry Andric   uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
16230b57cec5SDimitry Andric   uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
16240b57cec5SDimitry Andric   uint8_t visibility = mapVisibility(objSym.getVisibility());
16250b57cec5SDimitry Andric 
162681ad6265SDimitry Andric   if (!sym)
1627*bdd1243dSDimitry Andric     sym = symtab.insert(saver().save(objSym.getName()));
162804eeddc0SDimitry Andric 
16290b57cec5SDimitry Andric   int c = objSym.getComdatIndex();
16300b57cec5SDimitry Andric   if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) {
163181ad6265SDimitry Andric     Undefined newSym(&f, StringRef(), binding, visibility, type);
163204eeddc0SDimitry Andric     sym->resolve(newSym);
163304eeddc0SDimitry Andric     sym->referenced = true;
163404eeddc0SDimitry Andric     return;
16350b57cec5SDimitry Andric   }
16360b57cec5SDimitry Andric 
163704eeddc0SDimitry Andric   if (objSym.isCommon()) {
163881ad6265SDimitry Andric     sym->resolve(CommonSymbol{&f, StringRef(), binding, visibility, STT_OBJECT,
163904eeddc0SDimitry Andric                               objSym.getCommonAlignment(),
164004eeddc0SDimitry Andric                               objSym.getCommonSize()});
164104eeddc0SDimitry Andric   } else {
164281ad6265SDimitry Andric     Defined newSym(&f, StringRef(), binding, visibility, type, 0, 0, nullptr);
164381ad6265SDimitry Andric     if (objSym.canBeOmittedFromSymbolTable())
164485868e8aSDimitry Andric       newSym.exportDynamic = false;
164504eeddc0SDimitry Andric     sym->resolve(newSym);
164604eeddc0SDimitry Andric   }
16470b57cec5SDimitry Andric }
16480b57cec5SDimitry Andric 
1649*bdd1243dSDimitry Andric void BitcodeFile::parse() {
1650fe6060f1SDimitry Andric   for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) {
16510b57cec5SDimitry Andric     keptComdats.push_back(
1652fe6060f1SDimitry Andric         s.second == Comdat::NoDeduplicate ||
1653*bdd1243dSDimitry Andric         symtab.comdatGroups.try_emplace(CachedHashStringRef(s.first), this)
1654fe6060f1SDimitry Andric             .second);
1655fe6060f1SDimitry Andric   }
16560b57cec5SDimitry Andric 
1657*bdd1243dSDimitry Andric   if (numSymbols == 0) {
1658*bdd1243dSDimitry Andric     numSymbols = obj->symbols().size();
1659*bdd1243dSDimitry Andric     symbols = std::make_unique<Symbol *[]>(numSymbols);
1660*bdd1243dSDimitry Andric   }
166181ad6265SDimitry Andric   // Process defined symbols first. See the comment in
166281ad6265SDimitry Andric   // ObjFile<ELFT>::initializeSymbols.
1663*bdd1243dSDimitry Andric   for (auto [i, irSym] : llvm::enumerate(obj->symbols()))
1664*bdd1243dSDimitry Andric     if (!irSym.isUndefined())
1665*bdd1243dSDimitry Andric       createBitcodeSymbol(symbols[i], keptComdats, irSym, *this);
1666*bdd1243dSDimitry Andric   for (auto [i, irSym] : llvm::enumerate(obj->symbols()))
1667*bdd1243dSDimitry Andric     if (irSym.isUndefined())
1668*bdd1243dSDimitry Andric       createBitcodeSymbol(symbols[i], keptComdats, irSym, *this);
16690b57cec5SDimitry Andric 
16700b57cec5SDimitry Andric   for (auto l : obj->getDependentLibraries())
16710b57cec5SDimitry Andric     addDependentLibrary(l, this);
16720b57cec5SDimitry Andric }
16730b57cec5SDimitry Andric 
16740eae32dcSDimitry Andric void BitcodeFile::parseLazy() {
1675*bdd1243dSDimitry Andric   numSymbols = obj->symbols().size();
1676*bdd1243dSDimitry Andric   symbols = std::make_unique<Symbol *[]>(numSymbols);
1677*bdd1243dSDimitry Andric   for (auto [i, irSym] : llvm::enumerate(obj->symbols()))
1678*bdd1243dSDimitry Andric     if (!irSym.isUndefined()) {
1679*bdd1243dSDimitry Andric       auto *sym = symtab.insert(saver().save(irSym.getName()));
168081ad6265SDimitry Andric       sym->resolve(LazyObject{*this});
1681*bdd1243dSDimitry Andric       symbols[i] = sym;
168281ad6265SDimitry Andric     }
168381ad6265SDimitry Andric }
168481ad6265SDimitry Andric 
168581ad6265SDimitry Andric void BitcodeFile::postParse() {
1686*bdd1243dSDimitry Andric   for (auto [i, irSym] : llvm::enumerate(obj->symbols())) {
1687*bdd1243dSDimitry Andric     const Symbol &sym = *symbols[i];
1688*bdd1243dSDimitry Andric     if (sym.file == this || !sym.isDefined() || irSym.isUndefined() ||
1689*bdd1243dSDimitry Andric         irSym.isCommon() || irSym.isWeak())
169081ad6265SDimitry Andric       continue;
1691*bdd1243dSDimitry Andric     int c = irSym.getComdatIndex();
169281ad6265SDimitry Andric     if (c != -1 && !keptComdats[c])
169381ad6265SDimitry Andric       continue;
169481ad6265SDimitry Andric     reportDuplicate(sym, this, nullptr, 0);
169581ad6265SDimitry Andric   }
16960eae32dcSDimitry Andric }
16970eae32dcSDimitry Andric 
16980b57cec5SDimitry Andric void BinaryFile::parse() {
16990b57cec5SDimitry Andric   ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
17000b57cec5SDimitry Andric   auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
17010b57cec5SDimitry Andric                                      8, data, ".data");
17020b57cec5SDimitry Andric   sections.push_back(section);
17030b57cec5SDimitry Andric 
17040b57cec5SDimitry Andric   // For each input file foo that is embedded to a result as a binary
17050b57cec5SDimitry Andric   // blob, we define _binary_foo_{start,end,size} symbols, so that
17060b57cec5SDimitry Andric   // user programs can access blobs by name. Non-alphanumeric
17070b57cec5SDimitry Andric   // characters in a filename are replaced with underscore.
17080b57cec5SDimitry Andric   std::string s = "_binary_" + mb.getBufferIdentifier().str();
17090b57cec5SDimitry Andric   for (size_t i = 0; i < s.size(); ++i)
17100b57cec5SDimitry Andric     if (!isAlnum(s[i]))
17110b57cec5SDimitry Andric       s[i] = '_';
17120b57cec5SDimitry Andric 
171304eeddc0SDimitry Andric   llvm::StringSaver &saver = lld::saver();
171404eeddc0SDimitry Andric 
1715*bdd1243dSDimitry Andric   symtab.addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_start"),
1716*bdd1243dSDimitry Andric                                       STB_GLOBAL, STV_DEFAULT, STT_OBJECT, 0, 0,
1717*bdd1243dSDimitry Andric                                       section});
1718*bdd1243dSDimitry Andric   symtab.addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_end"),
171981ad6265SDimitry Andric                                       STB_GLOBAL, STV_DEFAULT, STT_OBJECT,
172081ad6265SDimitry Andric                                       data.size(), 0, section});
1721*bdd1243dSDimitry Andric   symtab.addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_size"),
172281ad6265SDimitry Andric                                       STB_GLOBAL, STV_DEFAULT, STT_OBJECT,
172381ad6265SDimitry Andric                                       data.size(), 0, nullptr});
17240b57cec5SDimitry Andric }
17250b57cec5SDimitry Andric 
1726fcaf7f86SDimitry Andric ELFFileBase *elf::createObjFile(MemoryBufferRef mb, StringRef archiveName,
1727fcaf7f86SDimitry Andric                                 bool lazy) {
1728fcaf7f86SDimitry Andric   ELFFileBase *f;
17290b57cec5SDimitry Andric   switch (getELFKind(mb, archiveName)) {
17300b57cec5SDimitry Andric   case ELF32LEKind:
1731*bdd1243dSDimitry Andric     f = make<ObjFile<ELF32LE>>(ELF32LEKind, mb, archiveName);
1732fcaf7f86SDimitry Andric     break;
17330b57cec5SDimitry Andric   case ELF32BEKind:
1734*bdd1243dSDimitry Andric     f = make<ObjFile<ELF32BE>>(ELF32BEKind, mb, archiveName);
1735fcaf7f86SDimitry Andric     break;
17360b57cec5SDimitry Andric   case ELF64LEKind:
1737*bdd1243dSDimitry Andric     f = make<ObjFile<ELF64LE>>(ELF64LEKind, mb, archiveName);
1738fcaf7f86SDimitry Andric     break;
17390b57cec5SDimitry Andric   case ELF64BEKind:
1740*bdd1243dSDimitry Andric     f = make<ObjFile<ELF64BE>>(ELF64BEKind, mb, archiveName);
1741fcaf7f86SDimitry Andric     break;
17420b57cec5SDimitry Andric   default:
17430b57cec5SDimitry Andric     llvm_unreachable("getELFKind");
17440b57cec5SDimitry Andric   }
1745*bdd1243dSDimitry Andric   f->init();
1746fcaf7f86SDimitry Andric   f->lazy = lazy;
1747fcaf7f86SDimitry Andric   return f;
17480b57cec5SDimitry Andric }
17490b57cec5SDimitry Andric 
17500eae32dcSDimitry Andric template <class ELFT> void ObjFile<ELFT>::parseLazy() {
17510eae32dcSDimitry Andric   const ArrayRef<typename ELFT::Sym> eSyms = this->getELFSyms<ELFT>();
1752*bdd1243dSDimitry Andric   numSymbols = eSyms.size();
1753*bdd1243dSDimitry Andric   symbols = std::make_unique<Symbol *[]>(numSymbols);
17540b57cec5SDimitry Andric 
17550eae32dcSDimitry Andric   // resolve() may trigger this->extract() if an existing symbol is an undefined
17560eae32dcSDimitry Andric   // symbol. If that happens, this function has served its purpose, and we can
17570eae32dcSDimitry Andric   // exit from the loop early.
1758*bdd1243dSDimitry Andric   for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1759*bdd1243dSDimitry Andric     if (eSyms[i].st_shndx == SHN_UNDEF)
1760*bdd1243dSDimitry Andric       continue;
1761*bdd1243dSDimitry Andric     symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this));
1762*bdd1243dSDimitry Andric     symbols[i]->resolve(LazyObject{*this});
17630eae32dcSDimitry Andric     if (!lazy)
1764*bdd1243dSDimitry Andric       break;
17650b57cec5SDimitry Andric   }
17660b57cec5SDimitry Andric }
17670b57cec5SDimitry Andric 
17680eae32dcSDimitry Andric bool InputFile::shouldExtractForCommon(StringRef name) {
1769fcaf7f86SDimitry Andric   if (isa<BitcodeFile>(this))
1770e8d8bef9SDimitry Andric     return isBitcodeNonCommonDef(mb, name, archiveName);
1771e8d8bef9SDimitry Andric 
1772e8d8bef9SDimitry Andric   return isNonCommonDef(mb, name, archiveName);
1773e8d8bef9SDimitry Andric }
1774e8d8bef9SDimitry Andric 
17755ffd83dbSDimitry Andric std::string elf::replaceThinLTOSuffix(StringRef path) {
1776*bdd1243dSDimitry Andric   auto [suffix, repl] = config->thinLTOObjectSuffixReplace;
17770b57cec5SDimitry Andric   if (path.consume_back(suffix))
17780b57cec5SDimitry Andric     return (path + repl).str();
17795ffd83dbSDimitry Andric   return std::string(path);
17800b57cec5SDimitry Andric }
17810b57cec5SDimitry Andric 
17825ffd83dbSDimitry Andric template class elf::ObjFile<ELF32LE>;
17835ffd83dbSDimitry Andric template class elf::ObjFile<ELF32BE>;
17845ffd83dbSDimitry Andric template class elf::ObjFile<ELF64LE>;
17855ffd83dbSDimitry Andric template class elf::ObjFile<ELF64BE>;
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric template void SharedFile::parse<ELF32LE>();
17880b57cec5SDimitry Andric template void SharedFile::parse<ELF32BE>();
17890b57cec5SDimitry Andric template void SharedFile::parse<ELF64LE>();
17900b57cec5SDimitry Andric template void SharedFile::parse<ELF64BE>();
1791