[clang-tidy][use-internal-linkage]fix false positives for global overloaded operator...
[llvm-project.git] / lld / ELF / InputFiles.cpp
blob30fbb5d9fe4527205f5699d3352fa7c4024f500f
1 //===- InputFiles.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #include "InputFiles.h"
10 #include "Config.h"
11 #include "DWARF.h"
12 #include "Driver.h"
13 #include "InputSection.h"
14 #include "LinkerScript.h"
15 #include "SymbolTable.h"
16 #include "Symbols.h"
17 #include "SyntheticSections.h"
18 #include "Target.h"
19 #include "lld/Common/CommonLinkerContext.h"
20 #include "lld/Common/DWARF.h"
21 #include "llvm/ADT/CachedHashString.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/Object/IRObjectFile.h"
25 #include "llvm/Support/ARMAttributeParser.h"
26 #include "llvm/Support/ARMBuildAttributes.h"
27 #include "llvm/Support/Endian.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/RISCVAttributeParser.h"
31 #include "llvm/Support/TimeProfiler.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <optional>
35 using namespace llvm;
36 using namespace llvm::ELF;
37 using namespace llvm::object;
38 using namespace llvm::sys;
39 using namespace llvm::sys::fs;
40 using namespace llvm::support::endian;
41 using namespace lld;
42 using namespace lld::elf;
44 // This function is explicitly instantiated in ARM.cpp, don't do it here to
45 // avoid warnings with MSVC.
46 extern template void ObjFile<ELF32LE>::importCmseSymbols();
47 extern template void ObjFile<ELF32BE>::importCmseSymbols();
48 extern template void ObjFile<ELF64LE>::importCmseSymbols();
49 extern template void ObjFile<ELF64BE>::importCmseSymbols();
51 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
52 std::string elf::toStr(Ctx &ctx, const InputFile *f) {
53 static std::mutex mu;
54 if (!f)
55 return "<internal>";
58 std::lock_guard<std::mutex> lock(mu);
59 if (f->toStringCache.empty()) {
60 if (f->archiveName.empty())
61 f->toStringCache = f->getName();
62 else
63 (f->archiveName + "(" + f->getName() + ")").toVector(f->toStringCache);
66 return std::string(f->toStringCache);
69 const ELFSyncStream &elf::operator<<(const ELFSyncStream &s,
70 const InputFile *f) {
71 return s << toStr(s.ctx, f);
74 static ELFKind getELFKind(Ctx &ctx, MemoryBufferRef mb, StringRef archiveName) {
75 unsigned char size;
76 unsigned char endian;
77 std::tie(size, endian) = getElfArchType(mb.getBuffer());
79 auto report = [&](StringRef msg) {
80 StringRef filename = mb.getBufferIdentifier();
81 if (archiveName.empty())
82 Fatal(ctx) << filename << ": " << msg;
83 else
84 Fatal(ctx) << archiveName << "(" << filename << "): " << msg;
87 if (!mb.getBuffer().starts_with(ElfMagic))
88 report("not an ELF file");
89 if (endian != ELFDATA2LSB && endian != ELFDATA2MSB)
90 report("corrupted ELF file: invalid data encoding");
91 if (size != ELFCLASS32 && size != ELFCLASS64)
92 report("corrupted ELF file: invalid file class");
94 size_t bufSize = mb.getBuffer().size();
95 if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) ||
96 (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr)))
97 report("corrupted ELF file: file is too short");
99 if (size == ELFCLASS32)
100 return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
101 return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
104 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
105 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
106 // the input objects have been compiled.
107 static void updateARMVFPArgs(Ctx &ctx, const ARMAttributeParser &attributes,
108 const InputFile *f) {
109 std::optional<unsigned> attr =
110 attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
111 if (!attr)
112 // If an ABI tag isn't present then it is implicitly given the value of 0
113 // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
114 // including some in glibc that don't use FP args (and should have value 3)
115 // don't have the attribute so we do not consider an implicit value of 0
116 // as a clash.
117 return;
119 unsigned vfpArgs = *attr;
120 ARMVFPArgKind arg;
121 switch (vfpArgs) {
122 case ARMBuildAttrs::BaseAAPCS:
123 arg = ARMVFPArgKind::Base;
124 break;
125 case ARMBuildAttrs::HardFPAAPCS:
126 arg = ARMVFPArgKind::VFP;
127 break;
128 case ARMBuildAttrs::ToolChainFPPCS:
129 // Tool chain specific convention that conforms to neither AAPCS variant.
130 arg = ARMVFPArgKind::ToolChain;
131 break;
132 case ARMBuildAttrs::CompatibleFPAAPCS:
133 // Object compatible with all conventions.
134 return;
135 default:
136 ErrAlways(ctx) << f << ": unknown Tag_ABI_VFP_args value: " << vfpArgs;
137 return;
139 // Follow ld.bfd and error if there is a mix of calling conventions.
140 if (ctx.arg.armVFPArgs != arg && ctx.arg.armVFPArgs != ARMVFPArgKind::Default)
141 ErrAlways(ctx) << f << ": incompatible Tag_ABI_VFP_args";
142 else
143 ctx.arg.armVFPArgs = arg;
146 // The ARM support in lld makes some use of instructions that are not available
147 // on all ARM architectures. Namely:
148 // - Use of BLX instruction for interworking between ARM and Thumb state.
149 // - Use of the extended Thumb branch encoding in relocation.
150 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
151 // The ARM Attributes section contains information about the architecture chosen
152 // at compile time. We follow the convention that if at least one input object
153 // is compiled with an architecture that supports these features then lld is
154 // permitted to use them.
155 static void updateSupportedARMFeatures(Ctx &ctx,
156 const ARMAttributeParser &attributes) {
157 std::optional<unsigned> attr =
158 attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
159 if (!attr)
160 return;
161 auto arch = *attr;
162 switch (arch) {
163 case ARMBuildAttrs::Pre_v4:
164 case ARMBuildAttrs::v4:
165 case ARMBuildAttrs::v4T:
166 // Architectures prior to v5 do not support BLX instruction
167 break;
168 case ARMBuildAttrs::v5T:
169 case ARMBuildAttrs::v5TE:
170 case ARMBuildAttrs::v5TEJ:
171 case ARMBuildAttrs::v6:
172 case ARMBuildAttrs::v6KZ:
173 case ARMBuildAttrs::v6K:
174 ctx.arg.armHasBlx = true;
175 // Architectures used in pre-Cortex processors do not support
176 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
177 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
178 break;
179 default:
180 // All other Architectures have BLX and extended branch encoding
181 ctx.arg.armHasBlx = true;
182 ctx.arg.armJ1J2BranchEncoding = true;
183 if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
184 // All Architectures used in Cortex processors with the exception
185 // of v6-M and v6S-M have the MOVT and MOVW instructions.
186 ctx.arg.armHasMovtMovw = true;
187 break;
190 // Only ARMv8-M or later architectures have CMSE support.
191 std::optional<unsigned> profile =
192 attributes.getAttributeValue(ARMBuildAttrs::CPU_arch_profile);
193 if (!profile)
194 return;
195 if (arch >= ARMBuildAttrs::CPUArch::v8_M_Base &&
196 profile == ARMBuildAttrs::MicroControllerProfile)
197 ctx.arg.armCMSESupport = true;
199 // The thumb PLT entries require Thumb2 which can be used on multiple archs.
200 // For now, let's limit it to ones where ARM isn't available and we know have
201 // Thumb2.
202 std::optional<unsigned> armISA =
203 attributes.getAttributeValue(ARMBuildAttrs::ARM_ISA_use);
204 std::optional<unsigned> thumb =
205 attributes.getAttributeValue(ARMBuildAttrs::THUMB_ISA_use);
206 ctx.arg.armHasArmISA |= armISA && *armISA >= ARMBuildAttrs::Allowed;
207 ctx.arg.armHasThumb2ISA |= thumb && *thumb >= ARMBuildAttrs::AllowThumb32;
210 InputFile::InputFile(Ctx &ctx, Kind k, MemoryBufferRef m)
211 : ctx(ctx), mb(m), groupId(ctx.driver.nextGroupId), fileKind(k) {
212 // All files within the same --{start,end}-group get the same group ID.
213 // Otherwise, a new file will get a new group ID.
214 if (!ctx.driver.isInGroup)
215 ++ctx.driver.nextGroupId;
218 InputFile::~InputFile() {}
220 std::optional<MemoryBufferRef> elf::readFile(Ctx &ctx, StringRef path) {
221 llvm::TimeTraceScope timeScope("Load input files", path);
223 // The --chroot option changes our virtual root directory.
224 // This is useful when you are dealing with files created by --reproduce.
225 if (!ctx.arg.chroot.empty() && path.starts_with("/"))
226 path = ctx.saver.save(ctx.arg.chroot + path);
228 bool remapped = false;
229 auto it = ctx.arg.remapInputs.find(path);
230 if (it != ctx.arg.remapInputs.end()) {
231 path = it->second;
232 remapped = true;
233 } else {
234 for (const auto &[pat, toFile] : ctx.arg.remapInputsWildcards) {
235 if (pat.match(path)) {
236 path = toFile;
237 remapped = true;
238 break;
242 if (remapped) {
243 // Use /dev/null to indicate an input file that should be ignored. Change
244 // the path to NUL on Windows.
245 #ifdef _WIN32
246 if (path == "/dev/null")
247 path = "NUL";
248 #endif
251 Log(ctx) << path;
252 ctx.arg.dependencyFiles.insert(llvm::CachedHashString(path));
254 auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
255 /*RequiresNullTerminator=*/false);
256 if (auto ec = mbOrErr.getError()) {
257 ErrAlways(ctx) << "cannot open " << path << ": " << ec.message();
258 return std::nullopt;
261 MemoryBufferRef mbref = (*mbOrErr)->getMemBufferRef();
262 ctx.memoryBuffers.push_back(std::move(*mbOrErr)); // take MB ownership
264 if (ctx.tar)
265 ctx.tar->append(relativeToRoot(path), mbref.getBuffer());
266 return mbref;
269 // All input object files must be for the same architecture
270 // (e.g. it does not make sense to link x86 object files with
271 // MIPS object files.) This function checks for that error.
272 static bool isCompatible(Ctx &ctx, InputFile *file) {
273 if (!file->isElf() && !isa<BitcodeFile>(file))
274 return true;
276 if (file->ekind == ctx.arg.ekind && file->emachine == ctx.arg.emachine) {
277 if (ctx.arg.emachine != EM_MIPS)
278 return true;
279 if (isMipsN32Abi(ctx, *file) == ctx.arg.mipsN32Abi)
280 return true;
283 StringRef target =
284 !ctx.arg.bfdname.empty() ? ctx.arg.bfdname : ctx.arg.emulation;
285 if (!target.empty()) {
286 Err(ctx) << file << " is incompatible with " << target;
287 return false;
290 InputFile *existing = nullptr;
291 if (!ctx.objectFiles.empty())
292 existing = ctx.objectFiles[0];
293 else if (!ctx.sharedFiles.empty())
294 existing = ctx.sharedFiles[0];
295 else if (!ctx.bitcodeFiles.empty())
296 existing = ctx.bitcodeFiles[0];
297 auto diag = Err(ctx);
298 diag << file << " is incompatible";
299 if (existing)
300 diag << " with " << existing;
301 return false;
304 template <class ELFT> static void doParseFile(Ctx &ctx, InputFile *file) {
305 if (!isCompatible(ctx, file))
306 return;
308 // Lazy object file
309 if (file->lazy) {
310 if (auto *f = dyn_cast<BitcodeFile>(file)) {
311 ctx.lazyBitcodeFiles.push_back(f);
312 f->parseLazy();
313 } else {
314 cast<ObjFile<ELFT>>(file)->parseLazy();
316 return;
319 if (ctx.arg.trace)
320 Msg(ctx) << file;
322 if (file->kind() == InputFile::ObjKind) {
323 ctx.objectFiles.push_back(cast<ELFFileBase>(file));
324 cast<ObjFile<ELFT>>(file)->parse();
325 } else if (auto *f = dyn_cast<SharedFile>(file)) {
326 f->parse<ELFT>();
327 } else if (auto *f = dyn_cast<BitcodeFile>(file)) {
328 ctx.bitcodeFiles.push_back(f);
329 f->parse();
330 } else {
331 ctx.binaryFiles.push_back(cast<BinaryFile>(file));
332 cast<BinaryFile>(file)->parse();
336 // Add symbols in File to the symbol table.
337 void elf::parseFile(Ctx &ctx, InputFile *file) {
338 invokeELFT(doParseFile, ctx, file);
341 // This function is explicitly instantiated in ARM.cpp. Mark it extern here,
342 // to avoid warnings when building with MSVC.
343 extern template void ObjFile<ELF32LE>::importCmseSymbols();
344 extern template void ObjFile<ELF32BE>::importCmseSymbols();
345 extern template void ObjFile<ELF64LE>::importCmseSymbols();
346 extern template void ObjFile<ELF64BE>::importCmseSymbols();
348 template <class ELFT>
349 static void
350 doParseFiles(Ctx &ctx,
351 const SmallVector<std::unique_ptr<InputFile>, 0> &files) {
352 // Add all files to the symbol table. This will add almost all symbols that we
353 // need to the symbol table. This process might add files to the link due to
354 // addDependentLibrary.
355 for (size_t i = 0; i < files.size(); ++i) {
356 llvm::TimeTraceScope timeScope("Parse input files", files[i]->getName());
357 doParseFile<ELFT>(ctx, files[i].get());
359 if (ctx.driver.armCmseImpLib)
360 cast<ObjFile<ELFT>>(*ctx.driver.armCmseImpLib).importCmseSymbols();
363 void elf::parseFiles(Ctx &ctx,
364 const SmallVector<std::unique_ptr<InputFile>, 0> &files) {
365 llvm::TimeTraceScope timeScope("Parse input files");
366 invokeELFT(doParseFiles, ctx, files);
369 // Concatenates arguments to construct a string representing an error location.
370 StringRef InputFile::getNameForScript() const {
371 if (archiveName.empty())
372 return getName();
374 if (nameForScriptCache.empty())
375 nameForScriptCache = (archiveName + Twine(':') + getName()).str();
377 return nameForScriptCache;
380 // An ELF object file may contain a `.deplibs` section. If it exists, the
381 // section contains a list of library specifiers such as `m` for libm. This
382 // function resolves a given name by finding the first matching library checking
383 // the various ways that a library can be specified to LLD. This ELF extension
384 // is a form of autolinking and is called `dependent libraries`. It is currently
385 // unique to LLVM and lld.
386 static void addDependentLibrary(Ctx &ctx, StringRef specifier,
387 const InputFile *f) {
388 if (!ctx.arg.dependentLibraries)
389 return;
390 if (std::optional<std::string> s = searchLibraryBaseName(ctx, specifier))
391 ctx.driver.addFile(ctx.saver.save(*s), /*withLOption=*/true);
392 else if (std::optional<std::string> s = findFromSearchPaths(ctx, specifier))
393 ctx.driver.addFile(ctx.saver.save(*s), /*withLOption=*/true);
394 else if (fs::exists(specifier))
395 ctx.driver.addFile(specifier, /*withLOption=*/false);
396 else
397 ErrAlways(ctx)
398 << f << ": unable to find library from dependent library specifier: "
399 << specifier;
402 // Record the membership of a section group so that in the garbage collection
403 // pass, section group members are kept or discarded as a unit.
404 template <class ELFT>
405 static void handleSectionGroup(ArrayRef<InputSectionBase *> sections,
406 ArrayRef<typename ELFT::Word> entries) {
407 bool hasAlloc = false;
408 for (uint32_t index : entries.slice(1)) {
409 if (index >= sections.size())
410 return;
411 if (InputSectionBase *s = sections[index])
412 if (s != &InputSection::discarded && s->flags & SHF_ALLOC)
413 hasAlloc = true;
416 // If any member has the SHF_ALLOC flag, the whole group is subject to garbage
417 // collection. See the comment in markLive(). This rule retains .debug_types
418 // and .rela.debug_types.
419 if (!hasAlloc)
420 return;
422 // Connect the members in a circular doubly-linked list via
423 // nextInSectionGroup.
424 InputSectionBase *head;
425 InputSectionBase *prev = nullptr;
426 for (uint32_t index : entries.slice(1)) {
427 InputSectionBase *s = sections[index];
428 if (!s || s == &InputSection::discarded)
429 continue;
430 if (prev)
431 prev->nextInSectionGroup = s;
432 else
433 head = s;
434 prev = s;
436 if (prev)
437 prev->nextInSectionGroup = head;
440 template <class ELFT> void ObjFile<ELFT>::initDwarf() {
441 dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
442 std::make_unique<LLDDwarfObj<ELFT>>(this), "",
443 [&](Error err) { Warn(ctx) << getName() + ": " << std::move(err); },
444 [&](Error warning) {
445 Warn(ctx) << getName() << ": " << std::move(warning);
446 }));
449 DWARFCache *ELFFileBase::getDwarf() {
450 assert(fileKind == ObjKind);
451 llvm::call_once(initDwarf, [this]() {
452 switch (ekind) {
453 default:
454 llvm_unreachable("");
455 case ELF32LEKind:
456 return cast<ObjFile<ELF32LE>>(this)->initDwarf();
457 case ELF32BEKind:
458 return cast<ObjFile<ELF32BE>>(this)->initDwarf();
459 case ELF64LEKind:
460 return cast<ObjFile<ELF64LE>>(this)->initDwarf();
461 case ELF64BEKind:
462 return cast<ObjFile<ELF64BE>>(this)->initDwarf();
465 return dwarf.get();
468 ELFFileBase::ELFFileBase(Ctx &ctx, Kind k, ELFKind ekind, MemoryBufferRef mb)
469 : InputFile(ctx, k, mb) {
470 this->ekind = ekind;
473 ELFFileBase::~ELFFileBase() {}
475 template <typename Elf_Shdr>
476 static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
477 for (const Elf_Shdr &sec : sections)
478 if (sec.sh_type == type)
479 return &sec;
480 return nullptr;
483 void ELFFileBase::init() {
484 switch (ekind) {
485 case ELF32LEKind:
486 init<ELF32LE>(fileKind);
487 break;
488 case ELF32BEKind:
489 init<ELF32BE>(fileKind);
490 break;
491 case ELF64LEKind:
492 init<ELF64LE>(fileKind);
493 break;
494 case ELF64BEKind:
495 init<ELF64BE>(fileKind);
496 break;
497 default:
498 llvm_unreachable("getELFKind");
502 template <class ELFT> void ELFFileBase::init(InputFile::Kind k) {
503 using Elf_Shdr = typename ELFT::Shdr;
504 using Elf_Sym = typename ELFT::Sym;
506 // Initialize trivial attributes.
507 const ELFFile<ELFT> &obj = getObj<ELFT>();
508 emachine = obj.getHeader().e_machine;
509 osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI];
510 abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION];
512 ArrayRef<Elf_Shdr> sections = CHECK2(obj.sections(), this);
513 elfShdrs = sections.data();
514 numELFShdrs = sections.size();
516 // Find a symbol table.
517 const Elf_Shdr *symtabSec =
518 findSection(sections, k == SharedKind ? SHT_DYNSYM : SHT_SYMTAB);
520 if (!symtabSec)
521 return;
523 // Initialize members corresponding to a symbol table.
524 firstGlobal = symtabSec->sh_info;
526 ArrayRef<Elf_Sym> eSyms = CHECK2(obj.symbols(symtabSec), this);
527 if (firstGlobal == 0 || firstGlobal > eSyms.size())
528 Fatal(ctx) << this << ": invalid sh_info in symbol table";
530 elfSyms = reinterpret_cast<const void *>(eSyms.data());
531 numELFSyms = uint32_t(eSyms.size());
532 stringTable = CHECK2(obj.getStringTableForSymtab(*symtabSec, sections), this);
535 template <class ELFT>
536 uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
537 return CHECK2(
538 this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable),
539 this);
542 template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
543 object::ELFFile<ELFT> obj = this->getObj();
544 // Read a section table. justSymbols is usually false.
545 if (this->justSymbols) {
546 initializeJustSymbols();
547 initializeSymbols(obj);
548 return;
551 // Handle dependent libraries and selection of section groups as these are not
552 // done in parallel.
553 ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
554 StringRef shstrtab = CHECK2(obj.getSectionStringTable(objSections), this);
555 uint64_t size = objSections.size();
556 sections.resize(size);
557 for (size_t i = 0; i != size; ++i) {
558 const Elf_Shdr &sec = objSections[i];
559 if (sec.sh_type == SHT_LLVM_DEPENDENT_LIBRARIES && !ctx.arg.relocatable) {
560 StringRef name = check(obj.getSectionName(sec, shstrtab));
561 ArrayRef<char> data = CHECK2(
562 this->getObj().template getSectionContentsAsArray<char>(sec), this);
563 if (!data.empty() && data.back() != '\0') {
564 ErrAlways(ctx)
565 << this
566 << ": corrupted dependent libraries section (unterminated string): "
567 << name;
568 } else {
569 for (const char *d = data.begin(), *e = data.end(); d < e;) {
570 StringRef s(d);
571 addDependentLibrary(ctx, s, this);
572 d += s.size() + 1;
575 this->sections[i] = &InputSection::discarded;
576 continue;
579 if (sec.sh_type == SHT_ARM_ATTRIBUTES && ctx.arg.emachine == EM_ARM) {
580 ARMAttributeParser attributes;
581 ArrayRef<uint8_t> contents =
582 check(this->getObj().getSectionContents(sec));
583 StringRef name = check(obj.getSectionName(sec, shstrtab));
584 this->sections[i] = &InputSection::discarded;
585 if (Error e = attributes.parse(contents, ekind == ELF32LEKind
586 ? llvm::endianness::little
587 : llvm::endianness::big)) {
588 InputSection isec(*this, sec, name);
589 Warn(ctx) << &isec << ": " << std::move(e);
590 } else {
591 updateSupportedARMFeatures(ctx, attributes);
592 updateARMVFPArgs(ctx, attributes, this);
594 // FIXME: Retain the first attribute section we see. The eglibc ARM
595 // dynamic loaders require the presence of an attribute section for
596 // dlopen to work. In a full implementation we would merge all attribute
597 // sections.
598 if (ctx.in.attributes == nullptr) {
599 ctx.in.attributes = std::make_unique<InputSection>(*this, sec, name);
600 this->sections[i] = ctx.in.attributes.get();
605 // Producing a static binary with MTE globals is not currently supported,
606 // remove all SHT_AARCH64_MEMTAG_GLOBALS_STATIC sections as they're unused
607 // medatada, and we don't want them to end up in the output file for static
608 // executables.
609 if (sec.sh_type == SHT_AARCH64_MEMTAG_GLOBALS_STATIC &&
610 !canHaveMemtagGlobals(ctx)) {
611 this->sections[i] = &InputSection::discarded;
612 continue;
615 if (sec.sh_type != SHT_GROUP)
616 continue;
617 StringRef signature = getShtGroupSignature(objSections, sec);
618 ArrayRef<Elf_Word> entries =
619 CHECK2(obj.template getSectionContentsAsArray<Elf_Word>(sec), this);
620 if (entries.empty())
621 Fatal(ctx) << this << ": empty SHT_GROUP";
623 Elf_Word flag = entries[0];
624 if (flag && flag != GRP_COMDAT)
625 Fatal(ctx) << this << ": unsupported SHT_GROUP format";
627 bool keepGroup = (flag & GRP_COMDAT) == 0 || ignoreComdats ||
628 ctx.symtab->comdatGroups
629 .try_emplace(CachedHashStringRef(signature), this)
630 .second;
631 if (keepGroup) {
632 if (!ctx.arg.resolveGroups)
633 this->sections[i] = createInputSection(
634 i, sec, check(obj.getSectionName(sec, shstrtab)));
635 continue;
638 // Otherwise, discard group members.
639 for (uint32_t secIndex : entries.slice(1)) {
640 if (secIndex >= size)
641 Fatal(ctx) << this << ": invalid section index in group: " << secIndex;
642 this->sections[secIndex] = &InputSection::discarded;
646 // Read a symbol table.
647 initializeSymbols(obj);
650 // Sections with SHT_GROUP and comdat bits define comdat section groups.
651 // They are identified and deduplicated by group name. This function
652 // returns a group name.
653 template <class ELFT>
654 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
655 const Elf_Shdr &sec) {
656 typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
657 if (sec.sh_info >= symbols.size())
658 Fatal(ctx) << this << ": invalid symbol index";
659 const typename ELFT::Sym &sym = symbols[sec.sh_info];
660 return CHECK2(sym.getName(this->stringTable), this);
663 template <class ELFT>
664 bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
665 // On a regular link we don't merge sections if -O0 (default is -O1). This
666 // sometimes makes the linker significantly faster, although the output will
667 // be bigger.
669 // Doing the same for -r would create a problem as it would combine sections
670 // with different sh_entsize. One option would be to just copy every SHF_MERGE
671 // section as is to the output. While this would produce a valid ELF file with
672 // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
673 // they see two .debug_str. We could have separate logic for combining
674 // SHF_MERGE sections based both on their name and sh_entsize, but that seems
675 // to be more trouble than it is worth. Instead, we just use the regular (-O1)
676 // logic for -r.
677 if (ctx.arg.optimize == 0 && !ctx.arg.relocatable)
678 return false;
680 // A mergeable section with size 0 is useless because they don't have
681 // any data to merge. A mergeable string section with size 0 can be
682 // argued as invalid because it doesn't end with a null character.
683 // We'll avoid a mess by handling them as if they were non-mergeable.
684 if (sec.sh_size == 0)
685 return false;
687 // Check for sh_entsize. The ELF spec is not clear about the zero
688 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
689 // the section does not hold a table of fixed-size entries". We know
690 // that Rust 1.13 produces a string mergeable section with a zero
691 // sh_entsize. Here we just accept it rather than being picky about it.
692 uint64_t entSize = sec.sh_entsize;
693 if (entSize == 0)
694 return false;
695 if (sec.sh_size % entSize)
696 Fatal(ctx) << this << ":(" << name << "): SHF_MERGE section size ("
697 << uint64_t(sec.sh_size)
698 << ") must be a multiple of sh_entsize (" << entSize << ")";
700 if (sec.sh_flags & SHF_WRITE)
701 Fatal(ctx) << this << ":(" << name
702 << "): writable SHF_MERGE section is not supported";
704 return true;
707 // This is for --just-symbols.
709 // --just-symbols is a very minor feature that allows you to link your
710 // output against other existing program, so that if you load both your
711 // program and the other program into memory, your output can refer the
712 // other program's symbols.
714 // When the option is given, we link "just symbols". The section table is
715 // initialized with null pointers.
716 template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
717 sections.resize(numELFShdrs);
720 static bool isKnownSpecificSectionType(uint32_t t, uint32_t flags) {
721 if (SHT_LOUSER <= t && t <= SHT_HIUSER && !(flags & SHF_ALLOC))
722 return true;
723 if (SHT_LOOS <= t && t <= SHT_HIOS && !(flags & SHF_OS_NONCONFORMING))
724 return true;
725 // Allow all processor-specific types. This is different from GNU ld.
726 return SHT_LOPROC <= t && t <= SHT_HIPROC;
729 template <class ELFT>
730 void ObjFile<ELFT>::initializeSections(bool ignoreComdats,
731 const llvm::object::ELFFile<ELFT> &obj) {
732 ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
733 StringRef shstrtab = CHECK2(obj.getSectionStringTable(objSections), this);
734 uint64_t size = objSections.size();
735 SmallVector<ArrayRef<Elf_Word>, 0> selectedGroups;
736 for (size_t i = 0; i != size; ++i) {
737 if (this->sections[i] == &InputSection::discarded)
738 continue;
739 const Elf_Shdr &sec = objSections[i];
740 const uint32_t type = sec.sh_type;
742 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
743 // if -r is given, we'll let the final link discard such sections.
744 // This is compatible with GNU.
745 if ((sec.sh_flags & SHF_EXCLUDE) && !ctx.arg.relocatable) {
746 if (type == SHT_LLVM_CALL_GRAPH_PROFILE)
747 cgProfileSectionIndex = i;
748 if (type == SHT_LLVM_ADDRSIG) {
749 // We ignore the address-significance table if we know that the object
750 // file was created by objcopy or ld -r. This is because these tools
751 // will reorder the symbols in the symbol table, invalidating the data
752 // in the address-significance table, which refers to symbols by index.
753 if (sec.sh_link != 0)
754 this->addrsigSec = &sec;
755 else if (ctx.arg.icf == ICFLevel::Safe)
756 Warn(ctx) << this
757 << ": --icf=safe conservatively ignores "
758 "SHT_LLVM_ADDRSIG [index "
759 << i
760 << "] with sh_link=0 "
761 "(likely created using objcopy or ld -r)";
763 this->sections[i] = &InputSection::discarded;
764 continue;
767 switch (type) {
768 case SHT_GROUP: {
769 if (!ctx.arg.relocatable)
770 sections[i] = &InputSection::discarded;
771 StringRef signature =
772 cantFail(this->getELFSyms<ELFT>()[sec.sh_info].getName(stringTable));
773 ArrayRef<Elf_Word> entries =
774 cantFail(obj.template getSectionContentsAsArray<Elf_Word>(sec));
775 if ((entries[0] & GRP_COMDAT) == 0 || ignoreComdats ||
776 ctx.symtab->comdatGroups.find(CachedHashStringRef(signature))
777 ->second == this)
778 selectedGroups.push_back(entries);
779 break;
781 case SHT_SYMTAB_SHNDX:
782 shndxTable = CHECK2(obj.getSHNDXTable(sec, objSections), this);
783 break;
784 case SHT_SYMTAB:
785 case SHT_STRTAB:
786 case SHT_REL:
787 case SHT_RELA:
788 case SHT_CREL:
789 case SHT_NULL:
790 break;
791 case SHT_PROGBITS:
792 case SHT_NOTE:
793 case SHT_NOBITS:
794 case SHT_INIT_ARRAY:
795 case SHT_FINI_ARRAY:
796 case SHT_PREINIT_ARRAY:
797 this->sections[i] =
798 createInputSection(i, sec, check(obj.getSectionName(sec, shstrtab)));
799 break;
800 case SHT_LLVM_LTO:
801 // Discard .llvm.lto in a relocatable link that does not use the bitcode.
802 // The concatenated output does not properly reflect the linking
803 // semantics. In addition, since we do not use the bitcode wrapper format,
804 // the concatenated raw bitcode would be invalid.
805 if (ctx.arg.relocatable && !ctx.arg.fatLTOObjects) {
806 sections[i] = &InputSection::discarded;
807 break;
809 [[fallthrough]];
810 default:
811 this->sections[i] =
812 createInputSection(i, sec, check(obj.getSectionName(sec, shstrtab)));
813 if (type == SHT_LLVM_SYMPART)
814 ctx.hasSympart.store(true, std::memory_order_relaxed);
815 else if (ctx.arg.rejectMismatch &&
816 !isKnownSpecificSectionType(type, sec.sh_flags))
817 Err(ctx) << this->sections[i] << ": unknown section type 0x"
818 << Twine::utohexstr(type);
819 break;
823 // We have a second loop. It is used to:
824 // 1) handle SHF_LINK_ORDER sections.
825 // 2) create relocation sections. In some cases the section header index of a
826 // relocation section may be smaller than that of the relocated section. In
827 // such cases, the relocation section would attempt to reference a target
828 // section that has not yet been created. For simplicity, delay creation of
829 // relocation sections until now.
830 for (size_t i = 0; i != size; ++i) {
831 if (this->sections[i] == &InputSection::discarded)
832 continue;
833 const Elf_Shdr &sec = objSections[i];
835 if (isStaticRelSecType(sec.sh_type)) {
836 // Find a relocation target section and associate this section with that.
837 // Target may have been discarded if it is in a different section group
838 // and the group is discarded, even though it's a violation of the spec.
839 // We handle that situation gracefully by discarding dangling relocation
840 // sections.
841 const uint32_t info = sec.sh_info;
842 InputSectionBase *s = getRelocTarget(i, info);
843 if (!s)
844 continue;
846 // ELF spec allows mergeable sections with relocations, but they are rare,
847 // and it is in practice hard to merge such sections by contents, because
848 // applying relocations at end of linking changes section contents. So, we
849 // simply handle such sections as non-mergeable ones. Degrading like this
850 // is acceptable because section merging is optional.
851 if (auto *ms = dyn_cast<MergeInputSection>(s)) {
852 s = makeThreadLocal<InputSection>(ms->file, ms->name, ms->type,
853 ms->flags, ms->addralign, ms->entsize,
854 ms->contentMaybeDecompress());
855 sections[info] = s;
858 if (s->relSecIdx != 0)
859 ErrAlways(ctx) << s
860 << ": multiple relocation sections to one section are "
861 "not supported";
862 s->relSecIdx = i;
864 // Relocation sections are usually removed from the output, so return
865 // `nullptr` for the normal case. However, if -r or --emit-relocs is
866 // specified, we need to copy them to the output. (Some post link analysis
867 // tools specify --emit-relocs to obtain the information.)
868 if (ctx.arg.copyRelocs) {
869 auto *isec = makeThreadLocal<InputSection>(
870 *this, sec, check(obj.getSectionName(sec, shstrtab)));
871 // If the relocated section is discarded (due to /DISCARD/ or
872 // --gc-sections), the relocation section should be discarded as well.
873 s->dependentSections.push_back(isec);
874 sections[i] = isec;
876 continue;
879 // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have
880 // the flag.
881 if (!sec.sh_link || !(sec.sh_flags & SHF_LINK_ORDER))
882 continue;
884 InputSectionBase *linkSec = nullptr;
885 if (sec.sh_link < size)
886 linkSec = this->sections[sec.sh_link];
887 if (!linkSec)
888 Fatal(ctx) << this
889 << ": invalid sh_link index: " << uint32_t(sec.sh_link);
891 // A SHF_LINK_ORDER section is discarded if its linked-to section is
892 // discarded.
893 InputSection *isec = cast<InputSection>(this->sections[i]);
894 linkSec->dependentSections.push_back(isec);
895 if (!isa<InputSection>(linkSec))
896 ErrAlways(ctx)
897 << "a section " << isec->name
898 << " with SHF_LINK_ORDER should not refer a non-regular section: "
899 << linkSec;
902 for (ArrayRef<Elf_Word> entries : selectedGroups)
903 handleSectionGroup<ELFT>(this->sections, entries);
906 // Read the following info from the .note.gnu.property section and write it to
907 // the corresponding fields in `ObjFile`:
908 // - Feature flags (32 bits) representing x86 or AArch64 features for
909 // hardware-assisted call flow control;
910 // - AArch64 PAuth ABI core info (16 bytes).
911 template <class ELFT>
912 static void readGnuProperty(Ctx &ctx, const InputSection &sec,
913 ObjFile<ELFT> &f) {
914 using Elf_Nhdr = typename ELFT::Nhdr;
915 using Elf_Note = typename ELFT::Note;
917 ArrayRef<uint8_t> data = sec.content();
918 auto reportFatal = [&](const uint8_t *place, const Twine &msg) {
919 Fatal(ctx) << sec.file << ":(" << sec.name << "+0x"
920 << Twine::utohexstr(place - sec.content().data())
921 << "): " << msg;
923 while (!data.empty()) {
924 // Read one NOTE record.
925 auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
926 if (data.size() < sizeof(Elf_Nhdr) ||
927 data.size() < nhdr->getSize(sec.addralign))
928 reportFatal(data.data(), "data is too short");
930 Elf_Note note(*nhdr);
931 if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
932 data = data.slice(nhdr->getSize(sec.addralign));
933 continue;
936 uint32_t featureAndType = ctx.arg.emachine == EM_AARCH64
937 ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
938 : GNU_PROPERTY_X86_FEATURE_1_AND;
940 // Read a body of a NOTE record, which consists of type-length-value fields.
941 ArrayRef<uint8_t> desc = note.getDesc(sec.addralign);
942 while (!desc.empty()) {
943 const uint8_t *place = desc.data();
944 if (desc.size() < 8)
945 reportFatal(place, "program property is too short");
946 uint32_t type = read32<ELFT::Endianness>(desc.data());
947 uint32_t size = read32<ELFT::Endianness>(desc.data() + 4);
948 desc = desc.slice(8);
949 if (desc.size() < size)
950 reportFatal(place, "program property is too short");
952 if (type == featureAndType) {
953 // We found a FEATURE_1_AND field. There may be more than one of these
954 // in a .note.gnu.property section, for a relocatable object we
955 // accumulate the bits set.
956 if (size < 4)
957 reportFatal(place, "FEATURE_1_AND entry is too short");
958 f.andFeatures |= read32<ELFT::Endianness>(desc.data());
959 } else if (ctx.arg.emachine == EM_AARCH64 &&
960 type == GNU_PROPERTY_AARCH64_FEATURE_PAUTH) {
961 if (!f.aarch64PauthAbiCoreInfo.empty()) {
962 reportFatal(data.data(),
963 "multiple GNU_PROPERTY_AARCH64_FEATURE_PAUTH entries are "
964 "not supported");
965 } else if (size != 16) {
966 reportFatal(data.data(), "GNU_PROPERTY_AARCH64_FEATURE_PAUTH entry "
967 "is invalid: expected 16 bytes, but got " +
968 Twine(size));
970 f.aarch64PauthAbiCoreInfo = desc;
973 // Padding is present in the note descriptor, if necessary.
974 desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size));
977 // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
978 data = data.slice(nhdr->getSize(sec.addralign));
982 template <class ELFT>
983 InputSectionBase *ObjFile<ELFT>::getRelocTarget(uint32_t idx, uint32_t info) {
984 if (info < this->sections.size()) {
985 InputSectionBase *target = this->sections[info];
987 // Strictly speaking, a relocation section must be included in the
988 // group of the section it relocates. However, LLVM 3.3 and earlier
989 // would fail to do so, so we gracefully handle that case.
990 if (target == &InputSection::discarded)
991 return nullptr;
993 if (target != nullptr)
994 return target;
997 Err(ctx) << this << ": relocation section (index " << idx
998 << ") has invalid sh_info (" << info << ')';
999 return nullptr;
1002 // The function may be called concurrently for different input files. For
1003 // allocation, prefer makeThreadLocal which does not require holding a lock.
1004 template <class ELFT>
1005 InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx,
1006 const Elf_Shdr &sec,
1007 StringRef name) {
1008 if (name.starts_with(".n")) {
1009 // The GNU linker uses .note.GNU-stack section as a marker indicating
1010 // that the code in the object file does not expect that the stack is
1011 // executable (in terms of NX bit). If all input files have the marker,
1012 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
1013 // make the stack non-executable. Most object files have this section as
1014 // of 2017.
1016 // But making the stack non-executable is a norm today for security
1017 // reasons. Failure to do so may result in a serious security issue.
1018 // Therefore, we make LLD always add PT_GNU_STACK unless it is
1019 // explicitly told to do otherwise (by -z execstack). Because the stack
1020 // executable-ness is controlled solely by command line options,
1021 // .note.GNU-stack sections are simply ignored.
1022 if (name == ".note.GNU-stack")
1023 return &InputSection::discarded;
1025 // Object files that use processor features such as Intel Control-Flow
1026 // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
1027 // .note.gnu.property section containing a bitfield of feature bits like the
1028 // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
1030 // Since we merge bitmaps from multiple object files to create a new
1031 // .note.gnu.property containing a single AND'ed bitmap, we discard an input
1032 // file's .note.gnu.property section.
1033 if (name == ".note.gnu.property") {
1034 readGnuProperty<ELFT>(ctx, InputSection(*this, sec, name), *this);
1035 return &InputSection::discarded;
1038 // Split stacks is a feature to support a discontiguous stack,
1039 // commonly used in the programming language Go. For the details,
1040 // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
1041 // for split stack will include a .note.GNU-split-stack section.
1042 if (name == ".note.GNU-split-stack") {
1043 if (ctx.arg.relocatable) {
1044 ErrAlways(ctx) << "cannot mix split-stack and non-split-stack in a "
1045 "relocatable link";
1046 return &InputSection::discarded;
1048 this->splitStack = true;
1049 return &InputSection::discarded;
1052 // An object file compiled for split stack, but where some of the
1053 // functions were compiled with the no_split_stack_attribute will
1054 // include a .note.GNU-no-split-stack section.
1055 if (name == ".note.GNU-no-split-stack") {
1056 this->someNoSplitStack = true;
1057 return &InputSection::discarded;
1060 // Strip existing .note.gnu.build-id sections so that the output won't have
1061 // more than one build-id. This is not usually a problem because input
1062 // object files normally don't have .build-id sections, but you can create
1063 // such files by "ld.{bfd,gold,lld} -r --build-id", and we want to guard
1064 // against it.
1065 if (name == ".note.gnu.build-id")
1066 return &InputSection::discarded;
1069 // The linker merges EH (exception handling) frames and creates a
1070 // .eh_frame_hdr section for runtime. So we handle them with a special
1071 // class. For relocatable outputs, they are just passed through.
1072 if (name == ".eh_frame" && !ctx.arg.relocatable)
1073 return makeThreadLocal<EhInputSection>(*this, sec, name);
1075 if ((sec.sh_flags & SHF_MERGE) && shouldMerge(sec, name))
1076 return makeThreadLocal<MergeInputSection>(*this, sec, name);
1077 return makeThreadLocal<InputSection>(*this, sec, name);
1080 // Initialize symbols. symbols is a parallel array to the corresponding ELF
1081 // symbol table.
1082 template <class ELFT>
1083 void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) {
1084 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1085 if (numSymbols == 0) {
1086 numSymbols = eSyms.size();
1087 symbols = std::make_unique<Symbol *[]>(numSymbols);
1090 // Some entries have been filled by LazyObjFile.
1091 auto *symtab = ctx.symtab.get();
1092 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
1093 if (!symbols[i])
1094 symbols[i] = symtab->insert(CHECK2(eSyms[i].getName(stringTable), this));
1096 // Perform symbol resolution on non-local symbols.
1097 SmallVector<unsigned, 32> undefineds;
1098 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1099 const Elf_Sym &eSym = eSyms[i];
1100 uint32_t secIdx = eSym.st_shndx;
1101 if (secIdx == SHN_UNDEF) {
1102 undefineds.push_back(i);
1103 continue;
1106 uint8_t binding = eSym.getBinding();
1107 uint8_t stOther = eSym.st_other;
1108 uint8_t type = eSym.getType();
1109 uint64_t value = eSym.st_value;
1110 uint64_t size = eSym.st_size;
1112 Symbol *sym = symbols[i];
1113 sym->isUsedInRegularObj = true;
1114 if (LLVM_UNLIKELY(eSym.st_shndx == SHN_COMMON)) {
1115 if (value == 0 || value >= UINT32_MAX)
1116 Fatal(ctx) << this << ": common symbol '" << sym->getName()
1117 << "' has invalid alignment: " << value;
1118 hasCommonSyms = true;
1119 sym->resolve(ctx, CommonSymbol{ctx, this, StringRef(), binding, stOther,
1120 type, value, size});
1121 continue;
1124 // Handle global defined symbols. Defined::section will be set in postParse.
1125 sym->resolve(ctx, Defined{ctx, this, StringRef(), binding, stOther, type,
1126 value, size, nullptr});
1129 // Undefined symbols (excluding those defined relative to non-prevailing
1130 // sections) can trigger recursive extract. Process defined symbols first so
1131 // that the relative order between a defined symbol and an undefined symbol
1132 // does not change the symbol resolution behavior. In addition, a set of
1133 // interconnected symbols will all be resolved to the same file, instead of
1134 // being resolved to different files.
1135 for (unsigned i : undefineds) {
1136 const Elf_Sym &eSym = eSyms[i];
1137 Symbol *sym = symbols[i];
1138 sym->resolve(ctx, Undefined{this, StringRef(), eSym.getBinding(),
1139 eSym.st_other, eSym.getType()});
1140 sym->isUsedInRegularObj = true;
1141 sym->referenced = true;
1145 template <class ELFT>
1146 void ObjFile<ELFT>::initSectionsAndLocalSyms(bool ignoreComdats) {
1147 if (!justSymbols)
1148 initializeSections(ignoreComdats, getObj());
1150 if (!firstGlobal)
1151 return;
1152 SymbolUnion *locals = makeThreadLocalN<SymbolUnion>(firstGlobal);
1153 memset(locals, 0, sizeof(SymbolUnion) * firstGlobal);
1155 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1156 for (size_t i = 0, end = firstGlobal; i != end; ++i) {
1157 const Elf_Sym &eSym = eSyms[i];
1158 uint32_t secIdx = eSym.st_shndx;
1159 if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
1160 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
1161 else if (secIdx >= SHN_LORESERVE)
1162 secIdx = 0;
1163 if (LLVM_UNLIKELY(secIdx >= sections.size()))
1164 Fatal(ctx) << this << ": invalid section index: " << secIdx;
1165 if (LLVM_UNLIKELY(eSym.getBinding() != STB_LOCAL))
1166 ErrAlways(ctx) << this << ": non-local symbol (" << i
1167 << ") found at index < .symtab's sh_info (" << end << ")";
1169 InputSectionBase *sec = sections[secIdx];
1170 uint8_t type = eSym.getType();
1171 if (type == STT_FILE)
1172 sourceFile = CHECK2(eSym.getName(stringTable), this);
1173 if (LLVM_UNLIKELY(stringTable.size() <= eSym.st_name))
1174 Fatal(ctx) << this << ": invalid symbol name offset";
1175 StringRef name(stringTable.data() + eSym.st_name);
1177 symbols[i] = reinterpret_cast<Symbol *>(locals + i);
1178 if (eSym.st_shndx == SHN_UNDEF || sec == &InputSection::discarded)
1179 new (symbols[i]) Undefined(this, name, STB_LOCAL, eSym.st_other, type,
1180 /*discardedSecIdx=*/secIdx);
1181 else
1182 new (symbols[i]) Defined(ctx, this, name, STB_LOCAL, eSym.st_other, type,
1183 eSym.st_value, eSym.st_size, sec);
1184 symbols[i]->partition = 1;
1185 symbols[i]->isUsedInRegularObj = true;
1189 // Called after all ObjFile::parse is called for all ObjFiles. This checks
1190 // duplicate symbols and may do symbol property merge in the future.
1191 template <class ELFT> void ObjFile<ELFT>::postParse() {
1192 static std::mutex mu;
1193 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1194 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1195 const Elf_Sym &eSym = eSyms[i];
1196 Symbol &sym = *symbols[i];
1197 uint32_t secIdx = eSym.st_shndx;
1198 uint8_t binding = eSym.getBinding();
1199 if (LLVM_UNLIKELY(binding != STB_GLOBAL && binding != STB_WEAK &&
1200 binding != STB_GNU_UNIQUE))
1201 Err(ctx) << this << ": symbol (" << i
1202 << ") has invalid binding: " << (int)binding;
1204 // st_value of STT_TLS represents the assigned offset, not the actual
1205 // address which is used by STT_FUNC and STT_OBJECT. STT_TLS symbols can
1206 // only be referenced by special TLS relocations. It is usually an error if
1207 // a STT_TLS symbol is replaced by a non-STT_TLS symbol, vice versa.
1208 if (LLVM_UNLIKELY(sym.isTls()) && eSym.getType() != STT_TLS &&
1209 eSym.getType() != STT_NOTYPE)
1210 Err(ctx) << "TLS attribute mismatch: " << &sym << "\n>>> in " << sym.file
1211 << "\n>>> in " << this;
1213 // Handle non-COMMON defined symbol below. !sym.file allows a symbol
1214 // assignment to redefine a symbol without an error.
1215 if (!sym.file || !sym.isDefined() || secIdx == SHN_UNDEF ||
1216 secIdx == SHN_COMMON)
1217 continue;
1219 if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
1220 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
1221 else if (secIdx >= SHN_LORESERVE)
1222 secIdx = 0;
1223 if (LLVM_UNLIKELY(secIdx >= sections.size()))
1224 Fatal(ctx) << this << ": invalid section index: " << secIdx;
1225 InputSectionBase *sec = sections[secIdx];
1226 if (sec == &InputSection::discarded) {
1227 if (sym.traced) {
1228 printTraceSymbol(Undefined{this, sym.getName(), sym.binding,
1229 sym.stOther, sym.type, secIdx},
1230 sym.getName());
1232 if (sym.file == this) {
1233 std::lock_guard<std::mutex> lock(mu);
1234 ctx.nonPrevailingSyms.emplace_back(&sym, secIdx);
1236 continue;
1239 if (sym.file == this) {
1240 cast<Defined>(sym).section = sec;
1241 continue;
1244 if (sym.binding == STB_WEAK || binding == STB_WEAK)
1245 continue;
1246 std::lock_guard<std::mutex> lock(mu);
1247 ctx.duplicates.push_back({&sym, this, sec, eSym.st_value});
1251 // The handling of tentative definitions (COMMON symbols) in archives is murky.
1252 // A tentative definition will be promoted to a global definition if there are
1253 // no non-tentative definitions to dominate it. When we hold a tentative
1254 // definition to a symbol and are inspecting archive members for inclusion
1255 // there are 2 ways we can proceed:
1257 // 1) Consider the tentative definition a 'real' definition (ie promotion from
1258 // tentative to real definition has already happened) and not inspect
1259 // archive members for Global/Weak definitions to replace the tentative
1260 // definition. An archive member would only be included if it satisfies some
1261 // other undefined symbol. This is the behavior Gold uses.
1263 // 2) Consider the tentative definition as still undefined (ie the promotion to
1264 // a real definition happens only after all symbol resolution is done).
1265 // The linker searches archive members for STB_GLOBAL definitions to
1266 // replace the tentative definition with. This is the behavior used by
1267 // GNU ld.
1269 // The second behavior is inherited from SysVR4, which based it on the FORTRAN
1270 // COMMON BLOCK model. This behavior is needed for proper initialization in old
1271 // (pre F90) FORTRAN code that is packaged into an archive.
1273 // The following functions search archive members for definitions to replace
1274 // tentative definitions (implementing behavior 2).
1275 static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName,
1276 StringRef archiveName) {
1277 IRSymtabFile symtabFile = check(readIRSymtab(mb));
1278 for (const irsymtab::Reader::SymbolRef &sym :
1279 symtabFile.TheReader.symbols()) {
1280 if (sym.isGlobal() && sym.getName() == symName)
1281 return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon();
1283 return false;
1286 template <class ELFT>
1287 static bool isNonCommonDef(Ctx &ctx, ELFKind ekind, MemoryBufferRef mb,
1288 StringRef symName, StringRef archiveName) {
1289 ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(ctx, ekind, mb, archiveName);
1290 obj->init();
1291 StringRef stringtable = obj->getStringTable();
1293 for (auto sym : obj->template getGlobalELFSyms<ELFT>()) {
1294 Expected<StringRef> name = sym.getName(stringtable);
1295 if (name && name.get() == symName)
1296 return sym.isDefined() && sym.getBinding() == STB_GLOBAL &&
1297 !sym.isCommon();
1299 return false;
1302 static bool isNonCommonDef(Ctx &ctx, MemoryBufferRef mb, StringRef symName,
1303 StringRef archiveName) {
1304 switch (getELFKind(ctx, mb, archiveName)) {
1305 case ELF32LEKind:
1306 return isNonCommonDef<ELF32LE>(ctx, ELF32LEKind, mb, symName, archiveName);
1307 case ELF32BEKind:
1308 return isNonCommonDef<ELF32BE>(ctx, ELF32BEKind, mb, symName, archiveName);
1309 case ELF64LEKind:
1310 return isNonCommonDef<ELF64LE>(ctx, ELF64LEKind, mb, symName, archiveName);
1311 case ELF64BEKind:
1312 return isNonCommonDef<ELF64BE>(ctx, ELF64BEKind, mb, symName, archiveName);
1313 default:
1314 llvm_unreachable("getELFKind");
1318 SharedFile::SharedFile(Ctx &ctx, MemoryBufferRef m, StringRef defaultSoName)
1319 : ELFFileBase(ctx, SharedKind, getELFKind(ctx, m, ""), m),
1320 soName(defaultSoName), isNeeded(!ctx.arg.asNeeded) {}
1322 // Parse the version definitions in the object file if present, and return a
1323 // vector whose nth element contains a pointer to the Elf_Verdef for version
1324 // identifier n. Version identifiers that are not definitions map to nullptr.
1325 template <typename ELFT>
1326 static SmallVector<const void *, 0>
1327 parseVerdefs(const uint8_t *base, const typename ELFT::Shdr *sec) {
1328 if (!sec)
1329 return {};
1331 // Build the Verdefs array by following the chain of Elf_Verdef objects
1332 // from the start of the .gnu.version_d section.
1333 SmallVector<const void *, 0> verdefs;
1334 const uint8_t *verdef = base + sec->sh_offset;
1335 for (unsigned i = 0, e = sec->sh_info; i != e; ++i) {
1336 auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1337 verdef += curVerdef->vd_next;
1338 unsigned verdefIndex = curVerdef->vd_ndx;
1339 if (verdefIndex >= verdefs.size())
1340 verdefs.resize(verdefIndex + 1);
1341 verdefs[verdefIndex] = curVerdef;
1343 return verdefs;
1346 // Parse SHT_GNU_verneed to properly set the name of a versioned undefined
1347 // symbol. We detect fatal issues which would cause vulnerabilities, but do not
1348 // implement sophisticated error checking like in llvm-readobj because the value
1349 // of such diagnostics is low.
1350 template <typename ELFT>
1351 std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
1352 const typename ELFT::Shdr *sec) {
1353 if (!sec)
1354 return {};
1355 std::vector<uint32_t> verneeds;
1356 ArrayRef<uint8_t> data = CHECK2(obj.getSectionContents(*sec), this);
1357 const uint8_t *verneedBuf = data.begin();
1358 for (unsigned i = 0; i != sec->sh_info; ++i) {
1359 if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end())
1360 Fatal(ctx) << this << " has an invalid Verneed";
1361 auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
1362 const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
1363 for (unsigned j = 0; j != vn->vn_cnt; ++j) {
1364 if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end())
1365 Fatal(ctx) << this << " has an invalid Vernaux";
1366 auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
1367 if (aux->vna_name >= this->stringTable.size())
1368 Fatal(ctx) << this << " has a Vernaux with an invalid vna_name";
1369 uint16_t version = aux->vna_other & VERSYM_VERSION;
1370 if (version >= verneeds.size())
1371 verneeds.resize(version + 1);
1372 verneeds[version] = aux->vna_name;
1373 vernauxBuf += aux->vna_next;
1375 verneedBuf += vn->vn_next;
1377 return verneeds;
1380 // We do not usually care about alignments of data in shared object
1381 // files because the loader takes care of it. However, if we promote a
1382 // DSO symbol to point to .bss due to copy relocation, we need to keep
1383 // the original alignment requirements. We infer it in this function.
1384 template <typename ELFT>
1385 static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
1386 const typename ELFT::Sym &sym) {
1387 uint64_t ret = UINT64_MAX;
1388 if (sym.st_value)
1389 ret = 1ULL << llvm::countr_zero((uint64_t)sym.st_value);
1390 if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1391 ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1392 return (ret > UINT32_MAX) ? 0 : ret;
1395 // Fully parse the shared object file.
1397 // This function parses symbol versions. If a DSO has version information,
1398 // the file has a ".gnu.version_d" section which contains symbol version
1399 // definitions. Each symbol is associated to one version through a table in
1400 // ".gnu.version" section. That table is a parallel array for the symbol
1401 // table, and each table entry contains an index in ".gnu.version_d".
1403 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
1404 // VER_NDX_GLOBAL. There's no table entry for these special versions in
1405 // ".gnu.version_d".
1407 // The file format for symbol versioning is perhaps a bit more complicated
1408 // than necessary, but you can easily understand the code if you wrap your
1409 // head around the data structure described above.
1410 template <class ELFT> void SharedFile::parse() {
1411 using Elf_Dyn = typename ELFT::Dyn;
1412 using Elf_Shdr = typename ELFT::Shdr;
1413 using Elf_Sym = typename ELFT::Sym;
1414 using Elf_Verdef = typename ELFT::Verdef;
1415 using Elf_Versym = typename ELFT::Versym;
1417 ArrayRef<Elf_Dyn> dynamicTags;
1418 const ELFFile<ELFT> obj = this->getObj<ELFT>();
1419 ArrayRef<Elf_Shdr> sections = getELFShdrs<ELFT>();
1421 const Elf_Shdr *versymSec = nullptr;
1422 const Elf_Shdr *verdefSec = nullptr;
1423 const Elf_Shdr *verneedSec = nullptr;
1425 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1426 for (const Elf_Shdr &sec : sections) {
1427 switch (sec.sh_type) {
1428 default:
1429 continue;
1430 case SHT_DYNAMIC:
1431 dynamicTags =
1432 CHECK2(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this);
1433 break;
1434 case SHT_GNU_versym:
1435 versymSec = &sec;
1436 break;
1437 case SHT_GNU_verdef:
1438 verdefSec = &sec;
1439 break;
1440 case SHT_GNU_verneed:
1441 verneedSec = &sec;
1442 break;
1446 if (versymSec && numELFSyms == 0) {
1447 ErrAlways(ctx) << "SHT_GNU_versym should be associated with symbol table";
1448 return;
1451 // Search for a DT_SONAME tag to initialize this->soName.
1452 for (const Elf_Dyn &dyn : dynamicTags) {
1453 if (dyn.d_tag == DT_NEEDED) {
1454 uint64_t val = dyn.getVal();
1455 if (val >= this->stringTable.size())
1456 Fatal(ctx) << this << ": invalid DT_NEEDED entry";
1457 dtNeeded.push_back(this->stringTable.data() + val);
1458 } else if (dyn.d_tag == DT_SONAME) {
1459 uint64_t val = dyn.getVal();
1460 if (val >= this->stringTable.size())
1461 Fatal(ctx) << this << ": invalid DT_SONAME entry";
1462 soName = this->stringTable.data() + val;
1466 // DSOs are uniquified not by filename but by soname.
1467 StringSaver &ss = ctx.saver;
1468 DenseMap<CachedHashStringRef, SharedFile *>::iterator it;
1469 bool wasInserted;
1470 std::tie(it, wasInserted) =
1471 ctx.symtab->soNames.try_emplace(CachedHashStringRef(soName), this);
1473 // If a DSO appears more than once on the command line with and without
1474 // --as-needed, --no-as-needed takes precedence over --as-needed because a
1475 // user can add an extra DSO with --no-as-needed to force it to be added to
1476 // the dependency list.
1477 it->second->isNeeded |= isNeeded;
1478 if (!wasInserted)
1479 return;
1481 ctx.sharedFiles.push_back(this);
1483 verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1484 std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
1486 // Parse ".gnu.version" section which is a parallel array for the symbol
1487 // table. If a given file doesn't have a ".gnu.version" section, we use
1488 // VER_NDX_GLOBAL.
1489 size_t size = numELFSyms - firstGlobal;
1490 std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
1491 if (versymSec) {
1492 ArrayRef<Elf_Versym> versym =
1493 CHECK2(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec),
1494 this)
1495 .slice(firstGlobal);
1496 for (size_t i = 0; i < size; ++i)
1497 versyms[i] = versym[i].vs_index;
1500 // System libraries can have a lot of symbols with versions. Using a
1501 // fixed buffer for computing the versions name (foo@ver) can save a
1502 // lot of allocations.
1503 SmallString<0> versionedNameBuffer;
1505 // Add symbols to the symbol table.
1506 ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1507 for (size_t i = 0, e = syms.size(); i != e; ++i) {
1508 const Elf_Sym &sym = syms[i];
1510 // ELF spec requires that all local symbols precede weak or global
1511 // symbols in each symbol table, and the index of first non-local symbol
1512 // is stored to sh_info. If a local symbol appears after some non-local
1513 // symbol, that's a violation of the spec.
1514 StringRef name = CHECK2(sym.getName(stringTable), this);
1515 if (sym.getBinding() == STB_LOCAL) {
1516 Err(ctx) << this << ": invalid local symbol '" << name
1517 << "' in global part of symbol table";
1518 continue;
1521 const uint16_t ver = versyms[i], idx = ver & ~VERSYM_HIDDEN;
1522 if (sym.isUndefined()) {
1523 // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but
1524 // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL.
1525 if (ver != VER_NDX_LOCAL && ver != VER_NDX_GLOBAL) {
1526 if (idx >= verneeds.size()) {
1527 ErrAlways(ctx) << "corrupt input file: version need index " << idx
1528 << " for symbol " << name
1529 << " is out of bounds\n>>> defined in " << this;
1530 continue;
1532 StringRef verName = stringTable.data() + verneeds[idx];
1533 versionedNameBuffer.clear();
1534 name = ss.save((name + "@" + verName).toStringRef(versionedNameBuffer));
1536 Symbol *s = ctx.symtab->addSymbol(
1537 Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1538 s->exportDynamic = true;
1539 if (sym.getBinding() != STB_WEAK &&
1540 ctx.arg.unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore)
1541 requiredSymbols.push_back(s);
1542 continue;
1545 if (ver == VER_NDX_LOCAL ||
1546 (ver != VER_NDX_GLOBAL && idx >= verdefs.size())) {
1547 // In GNU ld < 2.31 (before 3be08ea4728b56d35e136af4e6fd3086ade17764), the
1548 // MIPS port puts _gp_disp symbol into DSO files and incorrectly assigns
1549 // VER_NDX_LOCAL. Workaround this bug.
1550 if (ctx.arg.emachine == EM_MIPS && name == "_gp_disp")
1551 continue;
1552 ErrAlways(ctx) << "corrupt input file: version definition index " << idx
1553 << " for symbol " << name
1554 << " is out of bounds\n>>> defined in " << this;
1555 continue;
1558 uint32_t alignment = getAlignment<ELFT>(sections, sym);
1559 if (ver == idx) {
1560 auto *s = ctx.symtab->addSymbol(
1561 SharedSymbol{*this, name, sym.getBinding(), sym.st_other,
1562 sym.getType(), sym.st_value, sym.st_size, alignment});
1563 s->dsoDefined = true;
1564 if (s->file == this)
1565 s->versionId = ver;
1568 // Also add the symbol with the versioned name to handle undefined symbols
1569 // with explicit versions.
1570 if (ver == VER_NDX_GLOBAL)
1571 continue;
1573 StringRef verName =
1574 stringTable.data() +
1575 reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1576 versionedNameBuffer.clear();
1577 name = (name + "@" + verName).toStringRef(versionedNameBuffer);
1578 auto *s = ctx.symtab->addSymbol(
1579 SharedSymbol{*this, ss.save(name), sym.getBinding(), sym.st_other,
1580 sym.getType(), sym.st_value, sym.st_size, alignment});
1581 s->dsoDefined = true;
1582 if (s->file == this)
1583 s->versionId = idx;
1587 static ELFKind getBitcodeELFKind(const Triple &t) {
1588 if (t.isLittleEndian())
1589 return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
1590 return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
1593 static uint16_t getBitcodeMachineKind(Ctx &ctx, StringRef path,
1594 const Triple &t) {
1595 switch (t.getArch()) {
1596 case Triple::aarch64:
1597 case Triple::aarch64_be:
1598 return EM_AARCH64;
1599 case Triple::amdgcn:
1600 case Triple::r600:
1601 return EM_AMDGPU;
1602 case Triple::arm:
1603 case Triple::armeb:
1604 case Triple::thumb:
1605 case Triple::thumbeb:
1606 return EM_ARM;
1607 case Triple::avr:
1608 return EM_AVR;
1609 case Triple::hexagon:
1610 return EM_HEXAGON;
1611 case Triple::loongarch32:
1612 case Triple::loongarch64:
1613 return EM_LOONGARCH;
1614 case Triple::mips:
1615 case Triple::mipsel:
1616 case Triple::mips64:
1617 case Triple::mips64el:
1618 return EM_MIPS;
1619 case Triple::msp430:
1620 return EM_MSP430;
1621 case Triple::ppc:
1622 case Triple::ppcle:
1623 return EM_PPC;
1624 case Triple::ppc64:
1625 case Triple::ppc64le:
1626 return EM_PPC64;
1627 case Triple::riscv32:
1628 case Triple::riscv64:
1629 return EM_RISCV;
1630 case Triple::sparcv9:
1631 return EM_SPARCV9;
1632 case Triple::systemz:
1633 return EM_S390;
1634 case Triple::x86:
1635 return t.isOSIAMCU() ? EM_IAMCU : EM_386;
1636 case Triple::x86_64:
1637 return EM_X86_64;
1638 default:
1639 ErrAlways(ctx) << path
1640 << ": could not infer e_machine from bitcode target triple "
1641 << t.str();
1642 return EM_NONE;
1646 static uint8_t getOsAbi(const Triple &t) {
1647 switch (t.getOS()) {
1648 case Triple::AMDHSA:
1649 return ELF::ELFOSABI_AMDGPU_HSA;
1650 case Triple::AMDPAL:
1651 return ELF::ELFOSABI_AMDGPU_PAL;
1652 case Triple::Mesa3D:
1653 return ELF::ELFOSABI_AMDGPU_MESA3D;
1654 default:
1655 return ELF::ELFOSABI_NONE;
1659 BitcodeFile::BitcodeFile(Ctx &ctx, MemoryBufferRef mb, StringRef archiveName,
1660 uint64_t offsetInArchive, bool lazy)
1661 : InputFile(ctx, BitcodeKind, mb) {
1662 this->archiveName = archiveName;
1663 this->lazy = lazy;
1665 std::string path = mb.getBufferIdentifier().str();
1666 if (ctx.arg.thinLTOIndexOnly)
1667 path = replaceThinLTOSuffix(ctx, mb.getBufferIdentifier());
1669 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1670 // name. If two archives define two members with the same name, this
1671 // causes a collision which result in only one of the objects being taken
1672 // into consideration at LTO time (which very likely causes undefined
1673 // symbols later in the link stage). So we append file offset to make
1674 // filename unique.
1675 StringSaver &ss = ctx.saver;
1676 StringRef name = archiveName.empty()
1677 ? ss.save(path)
1678 : ss.save(archiveName + "(" + path::filename(path) +
1679 " at " + utostr(offsetInArchive) + ")");
1680 MemoryBufferRef mbref(mb.getBuffer(), name);
1682 obj = CHECK2(lto::InputFile::create(mbref), this);
1684 Triple t(obj->getTargetTriple());
1685 ekind = getBitcodeELFKind(t);
1686 emachine = getBitcodeMachineKind(ctx, mb.getBufferIdentifier(), t);
1687 osabi = getOsAbi(t);
1690 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
1691 switch (gvVisibility) {
1692 case GlobalValue::DefaultVisibility:
1693 return STV_DEFAULT;
1694 case GlobalValue::HiddenVisibility:
1695 return STV_HIDDEN;
1696 case GlobalValue::ProtectedVisibility:
1697 return STV_PROTECTED;
1699 llvm_unreachable("unknown visibility");
1702 static void createBitcodeSymbol(Ctx &ctx, Symbol *&sym,
1703 const std::vector<bool> &keptComdats,
1704 const lto::InputFile::Symbol &objSym,
1705 BitcodeFile &f) {
1706 uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1707 uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
1708 uint8_t visibility = mapVisibility(objSym.getVisibility());
1710 if (!sym) {
1711 // Symbols can be duplicated in bitcode files because of '#include' and
1712 // linkonce_odr. Use uniqueSaver to save symbol names for de-duplication.
1713 // Update objSym.Name to reference (via StringRef) the string saver's copy;
1714 // this way LTO can reference the same string saver's copy rather than
1715 // keeping copies of its own.
1716 objSym.Name = ctx.uniqueSaver.save(objSym.getName());
1717 sym = ctx.symtab->insert(objSym.getName());
1720 int c = objSym.getComdatIndex();
1721 if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) {
1722 Undefined newSym(&f, StringRef(), binding, visibility, type);
1723 sym->resolve(ctx, newSym);
1724 sym->referenced = true;
1725 return;
1728 if (objSym.isCommon()) {
1729 sym->resolve(ctx, CommonSymbol{ctx, &f, StringRef(), binding, visibility,
1730 STT_OBJECT, objSym.getCommonAlignment(),
1731 objSym.getCommonSize()});
1732 } else {
1733 Defined newSym(ctx, &f, StringRef(), binding, visibility, type, 0, 0,
1734 nullptr);
1735 if (objSym.canBeOmittedFromSymbolTable())
1736 newSym.exportDynamic = false;
1737 sym->resolve(ctx, newSym);
1741 void BitcodeFile::parse() {
1742 for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) {
1743 keptComdats.push_back(
1744 s.second == Comdat::NoDeduplicate ||
1745 ctx.symtab->comdatGroups.try_emplace(CachedHashStringRef(s.first), this)
1746 .second);
1749 if (numSymbols == 0) {
1750 numSymbols = obj->symbols().size();
1751 symbols = std::make_unique<Symbol *[]>(numSymbols);
1753 // Process defined symbols first. See the comment in
1754 // ObjFile<ELFT>::initializeSymbols.
1755 for (auto [i, irSym] : llvm::enumerate(obj->symbols()))
1756 if (!irSym.isUndefined())
1757 createBitcodeSymbol(ctx, symbols[i], keptComdats, irSym, *this);
1758 for (auto [i, irSym] : llvm::enumerate(obj->symbols()))
1759 if (irSym.isUndefined())
1760 createBitcodeSymbol(ctx, symbols[i], keptComdats, irSym, *this);
1762 for (auto l : obj->getDependentLibraries())
1763 addDependentLibrary(ctx, l, this);
1766 void BitcodeFile::parseLazy() {
1767 numSymbols = obj->symbols().size();
1768 symbols = std::make_unique<Symbol *[]>(numSymbols);
1769 for (auto [i, irSym] : llvm::enumerate(obj->symbols())) {
1770 // Symbols can be duplicated in bitcode files because of '#include' and
1771 // linkonce_odr. Use uniqueSaver to save symbol names for de-duplication.
1772 // Update objSym.Name to reference (via StringRef) the string saver's copy;
1773 // this way LTO can reference the same string saver's copy rather than
1774 // keeping copies of its own.
1775 irSym.Name = ctx.uniqueSaver.save(irSym.getName());
1776 if (!irSym.isUndefined()) {
1777 auto *sym = ctx.symtab->insert(irSym.getName());
1778 sym->resolve(ctx, LazySymbol{*this});
1779 symbols[i] = sym;
1784 void BitcodeFile::postParse() {
1785 for (auto [i, irSym] : llvm::enumerate(obj->symbols())) {
1786 const Symbol &sym = *symbols[i];
1787 if (sym.file == this || !sym.isDefined() || irSym.isUndefined() ||
1788 irSym.isCommon() || irSym.isWeak())
1789 continue;
1790 int c = irSym.getComdatIndex();
1791 if (c != -1 && !keptComdats[c])
1792 continue;
1793 reportDuplicate(ctx, sym, this, nullptr, 0);
1797 void BinaryFile::parse() {
1798 ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
1799 auto *section =
1800 make<InputSection>(this, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE,
1801 /*addralign=*/8, /*entsize=*/0, data);
1802 sections.push_back(section);
1804 // For each input file foo that is embedded to a result as a binary
1805 // blob, we define _binary_foo_{start,end,size} symbols, so that
1806 // user programs can access blobs by name. Non-alphanumeric
1807 // characters in a filename are replaced with underscore.
1808 std::string s = "_binary_" + mb.getBufferIdentifier().str();
1809 for (char &c : s)
1810 if (!isAlnum(c))
1811 c = '_';
1813 llvm::StringSaver &ss = ctx.saver;
1814 ctx.symtab->addAndCheckDuplicate(
1815 ctx, Defined{ctx, this, ss.save(s + "_start"), STB_GLOBAL, STV_DEFAULT,
1816 STT_OBJECT, 0, 0, section});
1817 ctx.symtab->addAndCheckDuplicate(
1818 ctx, Defined{ctx, this, ss.save(s + "_end"), STB_GLOBAL, STV_DEFAULT,
1819 STT_OBJECT, data.size(), 0, section});
1820 ctx.symtab->addAndCheckDuplicate(
1821 ctx, Defined{ctx, this, ss.save(s + "_size"), STB_GLOBAL, STV_DEFAULT,
1822 STT_OBJECT, data.size(), 0, nullptr});
1825 InputFile *elf::createInternalFile(Ctx &ctx, StringRef name) {
1826 auto *file =
1827 make<InputFile>(ctx, InputFile::InternalKind, MemoryBufferRef("", name));
1828 // References from an internal file do not lead to --warn-backrefs
1829 // diagnostics.
1830 file->groupId = 0;
1831 return file;
1834 std::unique_ptr<ELFFileBase> elf::createObjFile(Ctx &ctx, MemoryBufferRef mb,
1835 StringRef archiveName,
1836 bool lazy) {
1837 std::unique_ptr<ELFFileBase> f;
1838 switch (getELFKind(ctx, mb, archiveName)) {
1839 case ELF32LEKind:
1840 f = std::make_unique<ObjFile<ELF32LE>>(ctx, ELF32LEKind, mb, archiveName);
1841 break;
1842 case ELF32BEKind:
1843 f = std::make_unique<ObjFile<ELF32BE>>(ctx, ELF32BEKind, mb, archiveName);
1844 break;
1845 case ELF64LEKind:
1846 f = std::make_unique<ObjFile<ELF64LE>>(ctx, ELF64LEKind, mb, archiveName);
1847 break;
1848 case ELF64BEKind:
1849 f = std::make_unique<ObjFile<ELF64BE>>(ctx, ELF64BEKind, mb, archiveName);
1850 break;
1851 default:
1852 llvm_unreachable("getELFKind");
1854 f->init();
1855 f->lazy = lazy;
1856 return f;
1859 template <class ELFT> void ObjFile<ELFT>::parseLazy() {
1860 const ArrayRef<typename ELFT::Sym> eSyms = this->getELFSyms<ELFT>();
1861 numSymbols = eSyms.size();
1862 symbols = std::make_unique<Symbol *[]>(numSymbols);
1864 // resolve() may trigger this->extract() if an existing symbol is an undefined
1865 // symbol. If that happens, this function has served its purpose, and we can
1866 // exit from the loop early.
1867 auto *symtab = ctx.symtab.get();
1868 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1869 if (eSyms[i].st_shndx == SHN_UNDEF)
1870 continue;
1871 symbols[i] = symtab->insert(CHECK2(eSyms[i].getName(stringTable), this));
1872 symbols[i]->resolve(ctx, LazySymbol{*this});
1873 if (!lazy)
1874 break;
1878 bool InputFile::shouldExtractForCommon(StringRef name) const {
1879 if (isa<BitcodeFile>(this))
1880 return isBitcodeNonCommonDef(mb, name, archiveName);
1882 return isNonCommonDef(ctx, mb, name, archiveName);
1885 std::string elf::replaceThinLTOSuffix(Ctx &ctx, StringRef path) {
1886 auto [suffix, repl] = ctx.arg.thinLTOObjectSuffixReplace;
1887 if (path.consume_back(suffix))
1888 return (path + repl).str();
1889 return std::string(path);
1892 template class elf::ObjFile<ELF32LE>;
1893 template class elf::ObjFile<ELF32BE>;
1894 template class elf::ObjFile<ELF64LE>;
1895 template class elf::ObjFile<ELF64BE>;
1897 template void SharedFile::parse<ELF32LE>();
1898 template void SharedFile::parse<ELF32BE>();
1899 template void SharedFile::parse<ELF64LE>();
1900 template void SharedFile::parse<ELF64BE>();