Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / lld / ELF / InputFiles.cpp
bloba0d4be8ff9885b0420382a3cae44d3ebbf723dd7
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/TarWriter.h"
32 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm;
35 using namespace llvm::ELF;
36 using namespace llvm::object;
37 using namespace llvm::sys;
38 using namespace llvm::sys::fs;
39 using namespace llvm::support::endian;
40 using namespace lld;
41 using namespace lld::elf;
43 // This function is explicity instantiated in ARM.cpp, don't do it here to avoid
44 // warnings with MSVC.
45 extern template void ObjFile<ELF32LE>::importCmseSymbols();
46 extern template void ObjFile<ELF32BE>::importCmseSymbols();
47 extern template void ObjFile<ELF64LE>::importCmseSymbols();
48 extern template void ObjFile<ELF64BE>::importCmseSymbols();
50 bool InputFile::isInGroup;
51 uint32_t InputFile::nextGroupId;
53 std::unique_ptr<TarWriter> elf::tar;
55 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
56 std::string lld::toString(const InputFile *f) {
57 static std::mutex mu;
58 if (!f)
59 return "<internal>";
62 std::lock_guard<std::mutex> lock(mu);
63 if (f->toStringCache.empty()) {
64 if (f->archiveName.empty())
65 f->toStringCache = f->getName();
66 else
67 (f->archiveName + "(" + f->getName() + ")").toVector(f->toStringCache);
70 return std::string(f->toStringCache);
73 static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) {
74 unsigned char size;
75 unsigned char endian;
76 std::tie(size, endian) = getElfArchType(mb.getBuffer());
78 auto report = [&](StringRef msg) {
79 StringRef filename = mb.getBufferIdentifier();
80 if (archiveName.empty())
81 fatal(filename + ": " + msg);
82 else
83 fatal(archiveName + "(" + filename + "): " + msg);
86 if (!mb.getBuffer().starts_with(ElfMagic))
87 report("not an ELF file");
88 if (endian != ELFDATA2LSB && endian != ELFDATA2MSB)
89 report("corrupted ELF file: invalid data encoding");
90 if (size != ELFCLASS32 && size != ELFCLASS64)
91 report("corrupted ELF file: invalid file class");
93 size_t bufSize = mb.getBuffer().size();
94 if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) ||
95 (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr)))
96 report("corrupted ELF file: file is too short");
98 if (size == ELFCLASS32)
99 return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
100 return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
103 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
104 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
105 // the input objects have been compiled.
106 static void updateARMVFPArgs(const ARMAttributeParser &attributes,
107 const InputFile *f) {
108 std::optional<unsigned> attr =
109 attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
110 if (!attr)
111 // If an ABI tag isn't present then it is implicitly given the value of 0
112 // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
113 // including some in glibc that don't use FP args (and should have value 3)
114 // don't have the attribute so we do not consider an implicit value of 0
115 // as a clash.
116 return;
118 unsigned vfpArgs = *attr;
119 ARMVFPArgKind arg;
120 switch (vfpArgs) {
121 case ARMBuildAttrs::BaseAAPCS:
122 arg = ARMVFPArgKind::Base;
123 break;
124 case ARMBuildAttrs::HardFPAAPCS:
125 arg = ARMVFPArgKind::VFP;
126 break;
127 case ARMBuildAttrs::ToolChainFPPCS:
128 // Tool chain specific convention that conforms to neither AAPCS variant.
129 arg = ARMVFPArgKind::ToolChain;
130 break;
131 case ARMBuildAttrs::CompatibleFPAAPCS:
132 // Object compatible with all conventions.
133 return;
134 default:
135 error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs));
136 return;
138 // Follow ld.bfd and error if there is a mix of calling conventions.
139 if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default)
140 error(toString(f) + ": incompatible Tag_ABI_VFP_args");
141 else
142 config->armVFPArgs = arg;
145 // The ARM support in lld makes some use of instructions that are not available
146 // on all ARM architectures. Namely:
147 // - Use of BLX instruction for interworking between ARM and Thumb state.
148 // - Use of the extended Thumb branch encoding in relocation.
149 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
150 // The ARM Attributes section contains information about the architecture chosen
151 // at compile time. We follow the convention that if at least one input object
152 // is compiled with an architecture that supports these features then lld is
153 // permitted to use them.
154 static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
155 std::optional<unsigned> attr =
156 attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
157 if (!attr)
158 return;
159 auto arch = *attr;
160 switch (arch) {
161 case ARMBuildAttrs::Pre_v4:
162 case ARMBuildAttrs::v4:
163 case ARMBuildAttrs::v4T:
164 // Architectures prior to v5 do not support BLX instruction
165 break;
166 case ARMBuildAttrs::v5T:
167 case ARMBuildAttrs::v5TE:
168 case ARMBuildAttrs::v5TEJ:
169 case ARMBuildAttrs::v6:
170 case ARMBuildAttrs::v6KZ:
171 case ARMBuildAttrs::v6K:
172 config->armHasBlx = true;
173 // Architectures used in pre-Cortex processors do not support
174 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
175 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
176 break;
177 default:
178 // All other Architectures have BLX and extended branch encoding
179 config->armHasBlx = true;
180 config->armJ1J2BranchEncoding = true;
181 if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
182 // All Architectures used in Cortex processors with the exception
183 // of v6-M and v6S-M have the MOVT and MOVW instructions.
184 config->armHasMovtMovw = true;
185 break;
188 // Only ARMv8-M or later architectures have CMSE support.
189 std::optional<unsigned> profile =
190 attributes.getAttributeValue(ARMBuildAttrs::CPU_arch_profile);
191 if (!profile)
192 return;
193 if (arch >= ARMBuildAttrs::CPUArch::v8_M_Base &&
194 profile == ARMBuildAttrs::MicroControllerProfile)
195 config->armCMSESupport = true;
198 InputFile::InputFile(Kind k, MemoryBufferRef m)
199 : mb(m), groupId(nextGroupId), fileKind(k) {
200 // All files within the same --{start,end}-group get the same group ID.
201 // Otherwise, a new file will get a new group ID.
202 if (!isInGroup)
203 ++nextGroupId;
206 std::optional<MemoryBufferRef> elf::readFile(StringRef path) {
207 llvm::TimeTraceScope timeScope("Load input files", path);
209 // The --chroot option changes our virtual root directory.
210 // This is useful when you are dealing with files created by --reproduce.
211 if (!config->chroot.empty() && path.starts_with("/"))
212 path = saver().save(config->chroot + path);
214 bool remapped = false;
215 auto it = config->remapInputs.find(path);
216 if (it != config->remapInputs.end()) {
217 path = it->second;
218 remapped = true;
219 } else {
220 for (const auto &[pat, toFile] : config->remapInputsWildcards) {
221 if (pat.match(path)) {
222 path = toFile;
223 remapped = true;
224 break;
228 if (remapped) {
229 // Use /dev/null to indicate an input file that should be ignored. Change
230 // the path to NUL on Windows.
231 #ifdef _WIN32
232 if (path == "/dev/null")
233 path = "NUL";
234 #endif
237 log(path);
238 config->dependencyFiles.insert(llvm::CachedHashString(path));
240 auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
241 /*RequiresNullTerminator=*/false);
242 if (auto ec = mbOrErr.getError()) {
243 error("cannot open " + path + ": " + ec.message());
244 return std::nullopt;
247 MemoryBufferRef mbref = (*mbOrErr)->getMemBufferRef();
248 ctx.memoryBuffers.push_back(std::move(*mbOrErr)); // take MB ownership
250 if (tar)
251 tar->append(relativeToRoot(path), mbref.getBuffer());
252 return mbref;
255 // All input object files must be for the same architecture
256 // (e.g. it does not make sense to link x86 object files with
257 // MIPS object files.) This function checks for that error.
258 static bool isCompatible(InputFile *file) {
259 if (!file->isElf() && !isa<BitcodeFile>(file))
260 return true;
262 if (file->ekind == config->ekind && file->emachine == config->emachine) {
263 if (config->emachine != EM_MIPS)
264 return true;
265 if (isMipsN32Abi(file) == config->mipsN32Abi)
266 return true;
269 StringRef target =
270 !config->bfdname.empty() ? config->bfdname : config->emulation;
271 if (!target.empty()) {
272 error(toString(file) + " is incompatible with " + target);
273 return false;
276 InputFile *existing = nullptr;
277 if (!ctx.objectFiles.empty())
278 existing = ctx.objectFiles[0];
279 else if (!ctx.sharedFiles.empty())
280 existing = ctx.sharedFiles[0];
281 else if (!ctx.bitcodeFiles.empty())
282 existing = ctx.bitcodeFiles[0];
283 std::string with;
284 if (existing)
285 with = " with " + toString(existing);
286 error(toString(file) + " is incompatible" + with);
287 return false;
290 template <class ELFT> static void doParseFile(InputFile *file) {
291 if (!isCompatible(file))
292 return;
294 // Lazy object file
295 if (file->lazy) {
296 if (auto *f = dyn_cast<BitcodeFile>(file)) {
297 ctx.lazyBitcodeFiles.push_back(f);
298 f->parseLazy();
299 } else {
300 cast<ObjFile<ELFT>>(file)->parseLazy();
302 return;
305 if (config->trace)
306 message(toString(file));
308 if (file->kind() == InputFile::ObjKind) {
309 ctx.objectFiles.push_back(cast<ELFFileBase>(file));
310 cast<ObjFile<ELFT>>(file)->parse();
311 } else if (auto *f = dyn_cast<SharedFile>(file)) {
312 f->parse<ELFT>();
313 } else if (auto *f = dyn_cast<BitcodeFile>(file)) {
314 ctx.bitcodeFiles.push_back(f);
315 f->parse();
316 } else {
317 ctx.binaryFiles.push_back(cast<BinaryFile>(file));
318 cast<BinaryFile>(file)->parse();
322 // Add symbols in File to the symbol table.
323 void elf::parseFile(InputFile *file) { invokeELFT(doParseFile, file); }
325 // This function is explicity instantiated in ARM.cpp. Mark it extern here,
326 // to avoid warnings when building with MSVC.
327 extern template void ObjFile<ELF32LE>::importCmseSymbols();
328 extern template void ObjFile<ELF32BE>::importCmseSymbols();
329 extern template void ObjFile<ELF64LE>::importCmseSymbols();
330 extern template void ObjFile<ELF64BE>::importCmseSymbols();
332 template <class ELFT> static void doParseArmCMSEImportLib(InputFile *file) {
333 cast<ObjFile<ELFT>>(file)->importCmseSymbols();
336 void elf::parseArmCMSEImportLib(InputFile *file) {
337 invokeELFT(doParseArmCMSEImportLib, file);
340 // Concatenates arguments to construct a string representing an error location.
341 static std::string createFileLineMsg(StringRef path, unsigned line) {
342 std::string filename = std::string(path::filename(path));
343 std::string lineno = ":" + std::to_string(line);
344 if (filename == path)
345 return filename + lineno;
346 return filename + lineno + " (" + path.str() + lineno + ")";
349 template <class ELFT>
350 static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym,
351 InputSectionBase &sec, uint64_t offset) {
352 // In DWARF, functions and variables are stored to different places.
353 // First, look up a function for a given offset.
354 if (std::optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
355 return createFileLineMsg(info->FileName, info->Line);
357 // If it failed, look up again as a variable.
358 if (std::optional<std::pair<std::string, unsigned>> fileLine =
359 file.getVariableLoc(sym.getName()))
360 return createFileLineMsg(fileLine->first, fileLine->second);
362 // File.sourceFile contains STT_FILE symbol, and that is a last resort.
363 return std::string(file.sourceFile);
366 std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec,
367 uint64_t offset) {
368 if (kind() != ObjKind)
369 return "";
370 switch (ekind) {
371 default:
372 llvm_unreachable("Invalid kind");
373 case ELF32LEKind:
374 return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset);
375 case ELF32BEKind:
376 return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset);
377 case ELF64LEKind:
378 return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset);
379 case ELF64BEKind:
380 return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset);
384 StringRef InputFile::getNameForScript() const {
385 if (archiveName.empty())
386 return getName();
388 if (nameForScriptCache.empty())
389 nameForScriptCache = (archiveName + Twine(':') + getName()).str();
391 return nameForScriptCache;
394 // An ELF object file may contain a `.deplibs` section. If it exists, the
395 // section contains a list of library specifiers such as `m` for libm. This
396 // function resolves a given name by finding the first matching library checking
397 // the various ways that a library can be specified to LLD. This ELF extension
398 // is a form of autolinking and is called `dependent libraries`. It is currently
399 // unique to LLVM and lld.
400 static void addDependentLibrary(StringRef specifier, const InputFile *f) {
401 if (!config->dependentLibraries)
402 return;
403 if (std::optional<std::string> s = searchLibraryBaseName(specifier))
404 ctx.driver.addFile(saver().save(*s), /*withLOption=*/true);
405 else if (std::optional<std::string> s = findFromSearchPaths(specifier))
406 ctx.driver.addFile(saver().save(*s), /*withLOption=*/true);
407 else if (fs::exists(specifier))
408 ctx.driver.addFile(specifier, /*withLOption=*/false);
409 else
410 error(toString(f) +
411 ": unable to find library from dependent library specifier: " +
412 specifier);
415 // Record the membership of a section group so that in the garbage collection
416 // pass, section group members are kept or discarded as a unit.
417 template <class ELFT>
418 static void handleSectionGroup(ArrayRef<InputSectionBase *> sections,
419 ArrayRef<typename ELFT::Word> entries) {
420 bool hasAlloc = false;
421 for (uint32_t index : entries.slice(1)) {
422 if (index >= sections.size())
423 return;
424 if (InputSectionBase *s = sections[index])
425 if (s != &InputSection::discarded && s->flags & SHF_ALLOC)
426 hasAlloc = true;
429 // If any member has the SHF_ALLOC flag, the whole group is subject to garbage
430 // collection. See the comment in markLive(). This rule retains .debug_types
431 // and .rela.debug_types.
432 if (!hasAlloc)
433 return;
435 // Connect the members in a circular doubly-linked list via
436 // nextInSectionGroup.
437 InputSectionBase *head;
438 InputSectionBase *prev = nullptr;
439 for (uint32_t index : entries.slice(1)) {
440 InputSectionBase *s = sections[index];
441 if (!s || s == &InputSection::discarded)
442 continue;
443 if (prev)
444 prev->nextInSectionGroup = s;
445 else
446 head = s;
447 prev = s;
449 if (prev)
450 prev->nextInSectionGroup = head;
453 template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() {
454 llvm::call_once(initDwarf, [this]() {
455 dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
456 std::make_unique<LLDDwarfObj<ELFT>>(this), "",
457 [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
458 [&](Error warning) {
459 warn(getName() + ": " + toString(std::move(warning)));
460 }));
463 return dwarf.get();
466 // Returns the pair of file name and line number describing location of data
467 // object (variable, array, etc) definition.
468 template <class ELFT>
469 std::optional<std::pair<std::string, unsigned>>
470 ObjFile<ELFT>::getVariableLoc(StringRef name) {
471 return getDwarf()->getVariableLoc(name);
474 // Returns source line information for a given offset
475 // using DWARF debug info.
476 template <class ELFT>
477 std::optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s,
478 uint64_t offset) {
479 // Detect SectionIndex for specified section.
480 uint64_t sectionIndex = object::SectionedAddress::UndefSection;
481 ArrayRef<InputSectionBase *> sections = s->file->getSections();
482 for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) {
483 if (s == sections[curIndex]) {
484 sectionIndex = curIndex;
485 break;
489 return getDwarf()->getDILineInfo(offset, sectionIndex);
492 ELFFileBase::ELFFileBase(Kind k, ELFKind ekind, MemoryBufferRef mb)
493 : InputFile(k, mb) {
494 this->ekind = ekind;
497 template <typename Elf_Shdr>
498 static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
499 for (const Elf_Shdr &sec : sections)
500 if (sec.sh_type == type)
501 return &sec;
502 return nullptr;
505 void ELFFileBase::init() {
506 switch (ekind) {
507 case ELF32LEKind:
508 init<ELF32LE>(fileKind);
509 break;
510 case ELF32BEKind:
511 init<ELF32BE>(fileKind);
512 break;
513 case ELF64LEKind:
514 init<ELF64LE>(fileKind);
515 break;
516 case ELF64BEKind:
517 init<ELF64BE>(fileKind);
518 break;
519 default:
520 llvm_unreachable("getELFKind");
524 template <class ELFT> void ELFFileBase::init(InputFile::Kind k) {
525 using Elf_Shdr = typename ELFT::Shdr;
526 using Elf_Sym = typename ELFT::Sym;
528 // Initialize trivial attributes.
529 const ELFFile<ELFT> &obj = getObj<ELFT>();
530 emachine = obj.getHeader().e_machine;
531 osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI];
532 abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION];
534 ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
535 elfShdrs = sections.data();
536 numELFShdrs = sections.size();
538 // Find a symbol table.
539 const Elf_Shdr *symtabSec =
540 findSection(sections, k == SharedKind ? SHT_DYNSYM : SHT_SYMTAB);
542 if (!symtabSec)
543 return;
545 // Initialize members corresponding to a symbol table.
546 firstGlobal = symtabSec->sh_info;
548 ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
549 if (firstGlobal == 0 || firstGlobal > eSyms.size())
550 fatal(toString(this) + ": invalid sh_info in symbol table");
552 elfSyms = reinterpret_cast<const void *>(eSyms.data());
553 numELFSyms = uint32_t(eSyms.size());
554 stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
557 template <class ELFT>
558 uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
559 return CHECK(
560 this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable),
561 this);
564 template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
565 object::ELFFile<ELFT> obj = this->getObj();
566 // Read a section table. justSymbols is usually false.
567 if (this->justSymbols) {
568 initializeJustSymbols();
569 initializeSymbols(obj);
570 return;
573 // Handle dependent libraries and selection of section groups as these are not
574 // done in parallel.
575 ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
576 StringRef shstrtab = CHECK(obj.getSectionStringTable(objSections), this);
577 uint64_t size = objSections.size();
578 sections.resize(size);
579 for (size_t i = 0; i != size; ++i) {
580 const Elf_Shdr &sec = objSections[i];
581 if (sec.sh_type == SHT_LLVM_DEPENDENT_LIBRARIES && !config->relocatable) {
582 StringRef name = check(obj.getSectionName(sec, shstrtab));
583 ArrayRef<char> data = CHECK(
584 this->getObj().template getSectionContentsAsArray<char>(sec), this);
585 if (!data.empty() && data.back() != '\0') {
586 error(
587 toString(this) +
588 ": corrupted dependent libraries section (unterminated string): " +
589 name);
590 } else {
591 for (const char *d = data.begin(), *e = data.end(); d < e;) {
592 StringRef s(d);
593 addDependentLibrary(s, this);
594 d += s.size() + 1;
597 this->sections[i] = &InputSection::discarded;
598 continue;
601 if (sec.sh_type == SHT_ARM_ATTRIBUTES && config->emachine == EM_ARM) {
602 ARMAttributeParser attributes;
603 ArrayRef<uint8_t> contents =
604 check(this->getObj().getSectionContents(sec));
605 StringRef name = check(obj.getSectionName(sec, shstrtab));
606 this->sections[i] = &InputSection::discarded;
607 if (Error e = attributes.parse(contents, ekind == ELF32LEKind
608 ? llvm::endianness::little
609 : llvm::endianness::big)) {
610 InputSection isec(*this, sec, name);
611 warn(toString(&isec) + ": " + llvm::toString(std::move(e)));
612 } else {
613 updateSupportedARMFeatures(attributes);
614 updateARMVFPArgs(attributes, this);
616 // FIXME: Retain the first attribute section we see. The eglibc ARM
617 // dynamic loaders require the presence of an attribute section for
618 // dlopen to work. In a full implementation we would merge all attribute
619 // sections.
620 if (in.attributes == nullptr) {
621 in.attributes = std::make_unique<InputSection>(*this, sec, name);
622 this->sections[i] = in.attributes.get();
627 // Producing a static binary with MTE globals is not currently supported,
628 // remove all SHT_AARCH64_MEMTAG_GLOBALS_STATIC sections as they're unused
629 // medatada, and we don't want them to end up in the output file for static
630 // executables.
631 if (sec.sh_type == SHT_AARCH64_MEMTAG_GLOBALS_STATIC &&
632 !canHaveMemtagGlobals()) {
633 this->sections[i] = &InputSection::discarded;
634 continue;
637 if (sec.sh_type != SHT_GROUP)
638 continue;
639 StringRef signature = getShtGroupSignature(objSections, sec);
640 ArrayRef<Elf_Word> entries =
641 CHECK(obj.template getSectionContentsAsArray<Elf_Word>(sec), this);
642 if (entries.empty())
643 fatal(toString(this) + ": empty SHT_GROUP");
645 Elf_Word flag = entries[0];
646 if (flag && flag != GRP_COMDAT)
647 fatal(toString(this) + ": unsupported SHT_GROUP format");
649 bool keepGroup =
650 (flag & GRP_COMDAT) == 0 || ignoreComdats ||
651 symtab.comdatGroups.try_emplace(CachedHashStringRef(signature), this)
652 .second;
653 if (keepGroup) {
654 if (config->relocatable)
655 this->sections[i] = createInputSection(
656 i, sec, check(obj.getSectionName(sec, shstrtab)));
657 continue;
660 // Otherwise, discard group members.
661 for (uint32_t secIndex : entries.slice(1)) {
662 if (secIndex >= size)
663 fatal(toString(this) +
664 ": invalid section index in group: " + Twine(secIndex));
665 this->sections[secIndex] = &InputSection::discarded;
669 // Read a symbol table.
670 initializeSymbols(obj);
673 // Sections with SHT_GROUP and comdat bits define comdat section groups.
674 // They are identified and deduplicated by group name. This function
675 // returns a group name.
676 template <class ELFT>
677 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
678 const Elf_Shdr &sec) {
679 typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
680 if (sec.sh_info >= symbols.size())
681 fatal(toString(this) + ": invalid symbol index");
682 const typename ELFT::Sym &sym = symbols[sec.sh_info];
683 return CHECK(sym.getName(this->stringTable), this);
686 template <class ELFT>
687 bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
688 // On a regular link we don't merge sections if -O0 (default is -O1). This
689 // sometimes makes the linker significantly faster, although the output will
690 // be bigger.
692 // Doing the same for -r would create a problem as it would combine sections
693 // with different sh_entsize. One option would be to just copy every SHF_MERGE
694 // section as is to the output. While this would produce a valid ELF file with
695 // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
696 // they see two .debug_str. We could have separate logic for combining
697 // SHF_MERGE sections based both on their name and sh_entsize, but that seems
698 // to be more trouble than it is worth. Instead, we just use the regular (-O1)
699 // logic for -r.
700 if (config->optimize == 0 && !config->relocatable)
701 return false;
703 // A mergeable section with size 0 is useless because they don't have
704 // any data to merge. A mergeable string section with size 0 can be
705 // argued as invalid because it doesn't end with a null character.
706 // We'll avoid a mess by handling them as if they were non-mergeable.
707 if (sec.sh_size == 0)
708 return false;
710 // Check for sh_entsize. The ELF spec is not clear about the zero
711 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
712 // the section does not hold a table of fixed-size entries". We know
713 // that Rust 1.13 produces a string mergeable section with a zero
714 // sh_entsize. Here we just accept it rather than being picky about it.
715 uint64_t entSize = sec.sh_entsize;
716 if (entSize == 0)
717 return false;
718 if (sec.sh_size % entSize)
719 fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" +
720 Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" +
721 Twine(entSize) + ")");
723 if (sec.sh_flags & SHF_WRITE)
724 fatal(toString(this) + ":(" + name +
725 "): writable SHF_MERGE section is not supported");
727 return true;
730 // This is for --just-symbols.
732 // --just-symbols is a very minor feature that allows you to link your
733 // output against other existing program, so that if you load both your
734 // program and the other program into memory, your output can refer the
735 // other program's symbols.
737 // When the option is given, we link "just symbols". The section table is
738 // initialized with null pointers.
739 template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
740 sections.resize(numELFShdrs);
743 template <class ELFT>
744 void ObjFile<ELFT>::initializeSections(bool ignoreComdats,
745 const llvm::object::ELFFile<ELFT> &obj) {
746 ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
747 StringRef shstrtab = CHECK(obj.getSectionStringTable(objSections), this);
748 uint64_t size = objSections.size();
749 SmallVector<ArrayRef<Elf_Word>, 0> selectedGroups;
750 for (size_t i = 0; i != size; ++i) {
751 if (this->sections[i] == &InputSection::discarded)
752 continue;
753 const Elf_Shdr &sec = objSections[i];
755 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
756 // if -r is given, we'll let the final link discard such sections.
757 // This is compatible with GNU.
758 if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) {
759 if (sec.sh_type == SHT_LLVM_CALL_GRAPH_PROFILE)
760 cgProfileSectionIndex = i;
761 if (sec.sh_type == SHT_LLVM_ADDRSIG) {
762 // We ignore the address-significance table if we know that the object
763 // file was created by objcopy or ld -r. This is because these tools
764 // will reorder the symbols in the symbol table, invalidating the data
765 // in the address-significance table, which refers to symbols by index.
766 if (sec.sh_link != 0)
767 this->addrsigSec = &sec;
768 else if (config->icf == ICFLevel::Safe)
769 warn(toString(this) +
770 ": --icf=safe conservatively ignores "
771 "SHT_LLVM_ADDRSIG [index " +
772 Twine(i) +
773 "] with sh_link=0 "
774 "(likely created using objcopy or ld -r)");
776 this->sections[i] = &InputSection::discarded;
777 continue;
780 switch (sec.sh_type) {
781 case SHT_GROUP: {
782 if (!config->relocatable)
783 sections[i] = &InputSection::discarded;
784 StringRef signature =
785 cantFail(this->getELFSyms<ELFT>()[sec.sh_info].getName(stringTable));
786 ArrayRef<Elf_Word> entries =
787 cantFail(obj.template getSectionContentsAsArray<Elf_Word>(sec));
788 if ((entries[0] & GRP_COMDAT) == 0 || ignoreComdats ||
789 symtab.comdatGroups.find(CachedHashStringRef(signature))->second ==
790 this)
791 selectedGroups.push_back(entries);
792 break;
794 case SHT_SYMTAB_SHNDX:
795 shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
796 break;
797 case SHT_SYMTAB:
798 case SHT_STRTAB:
799 case SHT_REL:
800 case SHT_RELA:
801 case SHT_NULL:
802 break;
803 case SHT_LLVM_SYMPART:
804 ctx.hasSympart.store(true, std::memory_order_relaxed);
805 [[fallthrough]];
806 default:
807 this->sections[i] =
808 createInputSection(i, sec, check(obj.getSectionName(sec, shstrtab)));
812 // We have a second loop. It is used to:
813 // 1) handle SHF_LINK_ORDER sections.
814 // 2) create SHT_REL[A] sections. In some cases the section header index of a
815 // relocation section may be smaller than that of the relocated section. In
816 // such cases, the relocation section would attempt to reference a target
817 // section that has not yet been created. For simplicity, delay creation of
818 // relocation sections until now.
819 for (size_t i = 0; i != size; ++i) {
820 if (this->sections[i] == &InputSection::discarded)
821 continue;
822 const Elf_Shdr &sec = objSections[i];
824 if (sec.sh_type == SHT_REL || sec.sh_type == SHT_RELA) {
825 // Find a relocation target section and associate this section with that.
826 // Target may have been discarded if it is in a different section group
827 // and the group is discarded, even though it's a violation of the spec.
828 // We handle that situation gracefully by discarding dangling relocation
829 // sections.
830 const uint32_t info = sec.sh_info;
831 InputSectionBase *s = getRelocTarget(i, sec, info);
832 if (!s)
833 continue;
835 // ELF spec allows mergeable sections with relocations, but they are rare,
836 // and it is in practice hard to merge such sections by contents, because
837 // applying relocations at end of linking changes section contents. So, we
838 // simply handle such sections as non-mergeable ones. Degrading like this
839 // is acceptable because section merging is optional.
840 if (auto *ms = dyn_cast<MergeInputSection>(s)) {
841 s = makeThreadLocal<InputSection>(
842 ms->file, ms->flags, ms->type, ms->addralign,
843 ms->contentMaybeDecompress(), ms->name);
844 sections[info] = s;
847 if (s->relSecIdx != 0)
848 error(
849 toString(s) +
850 ": multiple relocation sections to one section are not supported");
851 s->relSecIdx = i;
853 // Relocation sections are usually removed from the output, so return
854 // `nullptr` for the normal case. However, if -r or --emit-relocs is
855 // specified, we need to copy them to the output. (Some post link analysis
856 // tools specify --emit-relocs to obtain the information.)
857 if (config->copyRelocs) {
858 auto *isec = makeThreadLocal<InputSection>(
859 *this, sec, check(obj.getSectionName(sec, shstrtab)));
860 // If the relocated section is discarded (due to /DISCARD/ or
861 // --gc-sections), the relocation section should be discarded as well.
862 s->dependentSections.push_back(isec);
863 sections[i] = isec;
865 continue;
868 // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have
869 // the flag.
870 if (!sec.sh_link || !(sec.sh_flags & SHF_LINK_ORDER))
871 continue;
873 InputSectionBase *linkSec = nullptr;
874 if (sec.sh_link < size)
875 linkSec = this->sections[sec.sh_link];
876 if (!linkSec)
877 fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
879 // A SHF_LINK_ORDER section is discarded if its linked-to section is
880 // discarded.
881 InputSection *isec = cast<InputSection>(this->sections[i]);
882 linkSec->dependentSections.push_back(isec);
883 if (!isa<InputSection>(linkSec))
884 error("a section " + isec->name +
885 " with SHF_LINK_ORDER should not refer a non-regular section: " +
886 toString(linkSec));
889 for (ArrayRef<Elf_Word> entries : selectedGroups)
890 handleSectionGroup<ELFT>(this->sections, entries);
893 // If a source file is compiled with x86 hardware-assisted call flow control
894 // enabled, the generated object file contains feature flags indicating that
895 // fact. This function reads the feature flags and returns it.
897 // Essentially we want to read a single 32-bit value in this function, but this
898 // function is rather complicated because the value is buried deep inside a
899 // .note.gnu.property section.
901 // The section consists of one or more NOTE records. Each NOTE record consists
902 // of zero or more type-length-value fields. We want to find a field of a
903 // certain type. It seems a bit too much to just store a 32-bit value, perhaps
904 // the ABI is unnecessarily complicated.
905 template <class ELFT> static uint32_t readAndFeatures(const InputSection &sec) {
906 using Elf_Nhdr = typename ELFT::Nhdr;
907 using Elf_Note = typename ELFT::Note;
909 uint32_t featuresSet = 0;
910 ArrayRef<uint8_t> data = sec.content();
911 auto reportFatal = [&](const uint8_t *place, const char *msg) {
912 fatal(toString(sec.file) + ":(" + sec.name + "+0x" +
913 Twine::utohexstr(place - sec.content().data()) + "): " + msg);
915 while (!data.empty()) {
916 // Read one NOTE record.
917 auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
918 if (data.size() < sizeof(Elf_Nhdr) ||
919 data.size() < nhdr->getSize(sec.addralign))
920 reportFatal(data.data(), "data is too short");
922 Elf_Note note(*nhdr);
923 if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
924 data = data.slice(nhdr->getSize(sec.addralign));
925 continue;
928 uint32_t featureAndType = config->emachine == EM_AARCH64
929 ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
930 : GNU_PROPERTY_X86_FEATURE_1_AND;
932 // Read a body of a NOTE record, which consists of type-length-value fields.
933 ArrayRef<uint8_t> desc = note.getDesc(sec.addralign);
934 while (!desc.empty()) {
935 const uint8_t *place = desc.data();
936 if (desc.size() < 8)
937 reportFatal(place, "program property is too short");
938 uint32_t type = read32<ELFT::TargetEndianness>(desc.data());
939 uint32_t size = read32<ELFT::TargetEndianness>(desc.data() + 4);
940 desc = desc.slice(8);
941 if (desc.size() < size)
942 reportFatal(place, "program property is too short");
944 if (type == featureAndType) {
945 // We found a FEATURE_1_AND field. There may be more than one of these
946 // in a .note.gnu.property section, for a relocatable object we
947 // accumulate the bits set.
948 if (size < 4)
949 reportFatal(place, "FEATURE_1_AND entry is too short");
950 featuresSet |= read32<ELFT::TargetEndianness>(desc.data());
953 // Padding is present in the note descriptor, if necessary.
954 desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size));
957 // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
958 data = data.slice(nhdr->getSize(sec.addralign));
961 return featuresSet;
964 template <class ELFT>
965 InputSectionBase *ObjFile<ELFT>::getRelocTarget(uint32_t idx,
966 const Elf_Shdr &sec,
967 uint32_t info) {
968 if (info < this->sections.size()) {
969 InputSectionBase *target = this->sections[info];
971 // Strictly speaking, a relocation section must be included in the
972 // group of the section it relocates. However, LLVM 3.3 and earlier
973 // would fail to do so, so we gracefully handle that case.
974 if (target == &InputSection::discarded)
975 return nullptr;
977 if (target != nullptr)
978 return target;
981 error(toString(this) + Twine(": relocation section (index ") + Twine(idx) +
982 ") has invalid sh_info (" + Twine(info) + ")");
983 return nullptr;
986 // The function may be called concurrently for different input files. For
987 // allocation, prefer makeThreadLocal which does not require holding a lock.
988 template <class ELFT>
989 InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx,
990 const Elf_Shdr &sec,
991 StringRef name) {
992 if (name.starts_with(".n")) {
993 // The GNU linker uses .note.GNU-stack section as a marker indicating
994 // that the code in the object file does not expect that the stack is
995 // executable (in terms of NX bit). If all input files have the marker,
996 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
997 // make the stack non-executable. Most object files have this section as
998 // of 2017.
1000 // But making the stack non-executable is a norm today for security
1001 // reasons. Failure to do so may result in a serious security issue.
1002 // Therefore, we make LLD always add PT_GNU_STACK unless it is
1003 // explicitly told to do otherwise (by -z execstack). Because the stack
1004 // executable-ness is controlled solely by command line options,
1005 // .note.GNU-stack sections are simply ignored.
1006 if (name == ".note.GNU-stack")
1007 return &InputSection::discarded;
1009 // Object files that use processor features such as Intel Control-Flow
1010 // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
1011 // .note.gnu.property section containing a bitfield of feature bits like the
1012 // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
1014 // Since we merge bitmaps from multiple object files to create a new
1015 // .note.gnu.property containing a single AND'ed bitmap, we discard an input
1016 // file's .note.gnu.property section.
1017 if (name == ".note.gnu.property") {
1018 this->andFeatures = readAndFeatures<ELFT>(InputSection(*this, sec, name));
1019 return &InputSection::discarded;
1022 // Split stacks is a feature to support a discontiguous stack,
1023 // commonly used in the programming language Go. For the details,
1024 // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
1025 // for split stack will include a .note.GNU-split-stack section.
1026 if (name == ".note.GNU-split-stack") {
1027 if (config->relocatable) {
1028 error(
1029 "cannot mix split-stack and non-split-stack in a relocatable link");
1030 return &InputSection::discarded;
1032 this->splitStack = true;
1033 return &InputSection::discarded;
1036 // An object file compiled for split stack, but where some of the
1037 // functions were compiled with the no_split_stack_attribute will
1038 // include a .note.GNU-no-split-stack section.
1039 if (name == ".note.GNU-no-split-stack") {
1040 this->someNoSplitStack = true;
1041 return &InputSection::discarded;
1044 // Strip existing .note.gnu.build-id sections so that the output won't have
1045 // more than one build-id. This is not usually a problem because input
1046 // object files normally don't have .build-id sections, but you can create
1047 // such files by "ld.{bfd,gold,lld} -r --build-id", and we want to guard
1048 // against it.
1049 if (name == ".note.gnu.build-id")
1050 return &InputSection::discarded;
1053 // The linker merges EH (exception handling) frames and creates a
1054 // .eh_frame_hdr section for runtime. So we handle them with a special
1055 // class. For relocatable outputs, they are just passed through.
1056 if (name == ".eh_frame" && !config->relocatable)
1057 return makeThreadLocal<EhInputSection>(*this, sec, name);
1059 if ((sec.sh_flags & SHF_MERGE) && shouldMerge(sec, name))
1060 return makeThreadLocal<MergeInputSection>(*this, sec, name);
1061 return makeThreadLocal<InputSection>(*this, sec, name);
1064 // Initialize symbols. symbols is a parallel array to the corresponding ELF
1065 // symbol table.
1066 template <class ELFT>
1067 void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) {
1068 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1069 if (numSymbols == 0) {
1070 numSymbols = eSyms.size();
1071 symbols = std::make_unique<Symbol *[]>(numSymbols);
1074 // Some entries have been filled by LazyObjFile.
1075 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
1076 if (!symbols[i])
1077 symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this));
1079 // Perform symbol resolution on non-local symbols.
1080 SmallVector<unsigned, 32> undefineds;
1081 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1082 const Elf_Sym &eSym = eSyms[i];
1083 uint32_t secIdx = eSym.st_shndx;
1084 if (secIdx == SHN_UNDEF) {
1085 undefineds.push_back(i);
1086 continue;
1089 uint8_t binding = eSym.getBinding();
1090 uint8_t stOther = eSym.st_other;
1091 uint8_t type = eSym.getType();
1092 uint64_t value = eSym.st_value;
1093 uint64_t size = eSym.st_size;
1095 Symbol *sym = symbols[i];
1096 sym->isUsedInRegularObj = true;
1097 if (LLVM_UNLIKELY(eSym.st_shndx == SHN_COMMON)) {
1098 if (value == 0 || value >= UINT32_MAX)
1099 fatal(toString(this) + ": common symbol '" + sym->getName() +
1100 "' has invalid alignment: " + Twine(value));
1101 hasCommonSyms = true;
1102 sym->resolve(
1103 CommonSymbol{this, StringRef(), binding, stOther, type, value, size});
1104 continue;
1107 // Handle global defined symbols. Defined::section will be set in postParse.
1108 sym->resolve(Defined{this, StringRef(), binding, stOther, type, value, size,
1109 nullptr});
1112 // Undefined symbols (excluding those defined relative to non-prevailing
1113 // sections) can trigger recursive extract. Process defined symbols first so
1114 // that the relative order between a defined symbol and an undefined symbol
1115 // does not change the symbol resolution behavior. In addition, a set of
1116 // interconnected symbols will all be resolved to the same file, instead of
1117 // being resolved to different files.
1118 for (unsigned i : undefineds) {
1119 const Elf_Sym &eSym = eSyms[i];
1120 Symbol *sym = symbols[i];
1121 sym->resolve(Undefined{this, StringRef(), eSym.getBinding(), eSym.st_other,
1122 eSym.getType()});
1123 sym->isUsedInRegularObj = true;
1124 sym->referenced = true;
1128 template <class ELFT>
1129 void ObjFile<ELFT>::initSectionsAndLocalSyms(bool ignoreComdats) {
1130 if (!justSymbols)
1131 initializeSections(ignoreComdats, getObj());
1133 if (!firstGlobal)
1134 return;
1135 SymbolUnion *locals = makeThreadLocalN<SymbolUnion>(firstGlobal);
1136 memset(locals, 0, sizeof(SymbolUnion) * firstGlobal);
1138 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1139 for (size_t i = 0, end = firstGlobal; i != end; ++i) {
1140 const Elf_Sym &eSym = eSyms[i];
1141 uint32_t secIdx = eSym.st_shndx;
1142 if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
1143 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
1144 else if (secIdx >= SHN_LORESERVE)
1145 secIdx = 0;
1146 if (LLVM_UNLIKELY(secIdx >= sections.size()))
1147 fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1148 if (LLVM_UNLIKELY(eSym.getBinding() != STB_LOCAL))
1149 error(toString(this) + ": non-local symbol (" + Twine(i) +
1150 ") found at index < .symtab's sh_info (" + Twine(end) + ")");
1152 InputSectionBase *sec = sections[secIdx];
1153 uint8_t type = eSym.getType();
1154 if (type == STT_FILE)
1155 sourceFile = CHECK(eSym.getName(stringTable), this);
1156 if (LLVM_UNLIKELY(stringTable.size() <= eSym.st_name))
1157 fatal(toString(this) + ": invalid symbol name offset");
1158 StringRef name(stringTable.data() + eSym.st_name);
1160 symbols[i] = reinterpret_cast<Symbol *>(locals + i);
1161 if (eSym.st_shndx == SHN_UNDEF || sec == &InputSection::discarded)
1162 new (symbols[i]) Undefined(this, name, STB_LOCAL, eSym.st_other, type,
1163 /*discardedSecIdx=*/secIdx);
1164 else
1165 new (symbols[i]) Defined(this, name, STB_LOCAL, eSym.st_other, type,
1166 eSym.st_value, eSym.st_size, sec);
1167 symbols[i]->partition = 1;
1168 symbols[i]->isUsedInRegularObj = true;
1172 // Called after all ObjFile::parse is called for all ObjFiles. This checks
1173 // duplicate symbols and may do symbol property merge in the future.
1174 template <class ELFT> void ObjFile<ELFT>::postParse() {
1175 static std::mutex mu;
1176 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1177 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1178 const Elf_Sym &eSym = eSyms[i];
1179 Symbol &sym = *symbols[i];
1180 uint32_t secIdx = eSym.st_shndx;
1181 uint8_t binding = eSym.getBinding();
1182 if (LLVM_UNLIKELY(binding != STB_GLOBAL && binding != STB_WEAK &&
1183 binding != STB_GNU_UNIQUE))
1184 errorOrWarn(toString(this) + ": symbol (" + Twine(i) +
1185 ") has invalid binding: " + Twine((int)binding));
1187 // st_value of STT_TLS represents the assigned offset, not the actual
1188 // address which is used by STT_FUNC and STT_OBJECT. STT_TLS symbols can
1189 // only be referenced by special TLS relocations. It is usually an error if
1190 // a STT_TLS symbol is replaced by a non-STT_TLS symbol, vice versa.
1191 if (LLVM_UNLIKELY(sym.isTls()) && eSym.getType() != STT_TLS &&
1192 eSym.getType() != STT_NOTYPE)
1193 errorOrWarn("TLS attribute mismatch: " + toString(sym) + "\n>>> in " +
1194 toString(sym.file) + "\n>>> in " + toString(this));
1196 // Handle non-COMMON defined symbol below. !sym.file allows a symbol
1197 // assignment to redefine a symbol without an error.
1198 if (!sym.file || !sym.isDefined() || secIdx == SHN_UNDEF ||
1199 secIdx == SHN_COMMON)
1200 continue;
1202 if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
1203 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
1204 else if (secIdx >= SHN_LORESERVE)
1205 secIdx = 0;
1206 if (LLVM_UNLIKELY(secIdx >= sections.size()))
1207 fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1208 InputSectionBase *sec = sections[secIdx];
1209 if (sec == &InputSection::discarded) {
1210 if (sym.traced) {
1211 printTraceSymbol(Undefined{this, sym.getName(), sym.binding,
1212 sym.stOther, sym.type, secIdx},
1213 sym.getName());
1215 if (sym.file == this) {
1216 std::lock_guard<std::mutex> lock(mu);
1217 ctx.nonPrevailingSyms.emplace_back(&sym, secIdx);
1219 continue;
1222 if (sym.file == this) {
1223 cast<Defined>(sym).section = sec;
1224 continue;
1227 if (sym.binding == STB_WEAK || binding == STB_WEAK)
1228 continue;
1229 std::lock_guard<std::mutex> lock(mu);
1230 ctx.duplicates.push_back({&sym, this, sec, eSym.st_value});
1234 // The handling of tentative definitions (COMMON symbols) in archives is murky.
1235 // A tentative definition will be promoted to a global definition if there are
1236 // no non-tentative definitions to dominate it. When we hold a tentative
1237 // definition to a symbol and are inspecting archive members for inclusion
1238 // there are 2 ways we can proceed:
1240 // 1) Consider the tentative definition a 'real' definition (ie promotion from
1241 // tentative to real definition has already happened) and not inspect
1242 // archive members for Global/Weak definitions to replace the tentative
1243 // definition. An archive member would only be included if it satisfies some
1244 // other undefined symbol. This is the behavior Gold uses.
1246 // 2) Consider the tentative definition as still undefined (ie the promotion to
1247 // a real definition happens only after all symbol resolution is done).
1248 // The linker searches archive members for STB_GLOBAL definitions to
1249 // replace the tentative definition with. This is the behavior used by
1250 // GNU ld.
1252 // The second behavior is inherited from SysVR4, which based it on the FORTRAN
1253 // COMMON BLOCK model. This behavior is needed for proper initialization in old
1254 // (pre F90) FORTRAN code that is packaged into an archive.
1256 // The following functions search archive members for definitions to replace
1257 // tentative definitions (implementing behavior 2).
1258 static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName,
1259 StringRef archiveName) {
1260 IRSymtabFile symtabFile = check(readIRSymtab(mb));
1261 for (const irsymtab::Reader::SymbolRef &sym :
1262 symtabFile.TheReader.symbols()) {
1263 if (sym.isGlobal() && sym.getName() == symName)
1264 return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon();
1266 return false;
1269 template <class ELFT>
1270 static bool isNonCommonDef(ELFKind ekind, MemoryBufferRef mb, StringRef symName,
1271 StringRef archiveName) {
1272 ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(ekind, mb, archiveName);
1273 obj->init();
1274 StringRef stringtable = obj->getStringTable();
1276 for (auto sym : obj->template getGlobalELFSyms<ELFT>()) {
1277 Expected<StringRef> name = sym.getName(stringtable);
1278 if (name && name.get() == symName)
1279 return sym.isDefined() && sym.getBinding() == STB_GLOBAL &&
1280 !sym.isCommon();
1282 return false;
1285 static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName,
1286 StringRef archiveName) {
1287 switch (getELFKind(mb, archiveName)) {
1288 case ELF32LEKind:
1289 return isNonCommonDef<ELF32LE>(ELF32LEKind, mb, symName, archiveName);
1290 case ELF32BEKind:
1291 return isNonCommonDef<ELF32BE>(ELF32BEKind, mb, symName, archiveName);
1292 case ELF64LEKind:
1293 return isNonCommonDef<ELF64LE>(ELF64LEKind, mb, symName, archiveName);
1294 case ELF64BEKind:
1295 return isNonCommonDef<ELF64BE>(ELF64BEKind, mb, symName, archiveName);
1296 default:
1297 llvm_unreachable("getELFKind");
1301 unsigned SharedFile::vernauxNum;
1303 SharedFile::SharedFile(MemoryBufferRef m, StringRef defaultSoName)
1304 : ELFFileBase(SharedKind, getELFKind(m, ""), m), soName(defaultSoName),
1305 isNeeded(!config->asNeeded) {}
1307 // Parse the version definitions in the object file if present, and return a
1308 // vector whose nth element contains a pointer to the Elf_Verdef for version
1309 // identifier n. Version identifiers that are not definitions map to nullptr.
1310 template <typename ELFT>
1311 static SmallVector<const void *, 0>
1312 parseVerdefs(const uint8_t *base, const typename ELFT::Shdr *sec) {
1313 if (!sec)
1314 return {};
1316 // Build the Verdefs array by following the chain of Elf_Verdef objects
1317 // from the start of the .gnu.version_d section.
1318 SmallVector<const void *, 0> verdefs;
1319 const uint8_t *verdef = base + sec->sh_offset;
1320 for (unsigned i = 0, e = sec->sh_info; i != e; ++i) {
1321 auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1322 verdef += curVerdef->vd_next;
1323 unsigned verdefIndex = curVerdef->vd_ndx;
1324 if (verdefIndex >= verdefs.size())
1325 verdefs.resize(verdefIndex + 1);
1326 verdefs[verdefIndex] = curVerdef;
1328 return verdefs;
1331 // Parse SHT_GNU_verneed to properly set the name of a versioned undefined
1332 // symbol. We detect fatal issues which would cause vulnerabilities, but do not
1333 // implement sophisticated error checking like in llvm-readobj because the value
1334 // of such diagnostics is low.
1335 template <typename ELFT>
1336 std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
1337 const typename ELFT::Shdr *sec) {
1338 if (!sec)
1339 return {};
1340 std::vector<uint32_t> verneeds;
1341 ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(*sec), this);
1342 const uint8_t *verneedBuf = data.begin();
1343 for (unsigned i = 0; i != sec->sh_info; ++i) {
1344 if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end())
1345 fatal(toString(this) + " has an invalid Verneed");
1346 auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
1347 const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
1348 for (unsigned j = 0; j != vn->vn_cnt; ++j) {
1349 if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end())
1350 fatal(toString(this) + " has an invalid Vernaux");
1351 auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
1352 if (aux->vna_name >= this->stringTable.size())
1353 fatal(toString(this) + " has a Vernaux with an invalid vna_name");
1354 uint16_t version = aux->vna_other & VERSYM_VERSION;
1355 if (version >= verneeds.size())
1356 verneeds.resize(version + 1);
1357 verneeds[version] = aux->vna_name;
1358 vernauxBuf += aux->vna_next;
1360 verneedBuf += vn->vn_next;
1362 return verneeds;
1365 // We do not usually care about alignments of data in shared object
1366 // files because the loader takes care of it. However, if we promote a
1367 // DSO symbol to point to .bss due to copy relocation, we need to keep
1368 // the original alignment requirements. We infer it in this function.
1369 template <typename ELFT>
1370 static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
1371 const typename ELFT::Sym &sym) {
1372 uint64_t ret = UINT64_MAX;
1373 if (sym.st_value)
1374 ret = 1ULL << llvm::countr_zero((uint64_t)sym.st_value);
1375 if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1376 ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1377 return (ret > UINT32_MAX) ? 0 : ret;
1380 // Fully parse the shared object file.
1382 // This function parses symbol versions. If a DSO has version information,
1383 // the file has a ".gnu.version_d" section which contains symbol version
1384 // definitions. Each symbol is associated to one version through a table in
1385 // ".gnu.version" section. That table is a parallel array for the symbol
1386 // table, and each table entry contains an index in ".gnu.version_d".
1388 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
1389 // VER_NDX_GLOBAL. There's no table entry for these special versions in
1390 // ".gnu.version_d".
1392 // The file format for symbol versioning is perhaps a bit more complicated
1393 // than necessary, but you can easily understand the code if you wrap your
1394 // head around the data structure described above.
1395 template <class ELFT> void SharedFile::parse() {
1396 using Elf_Dyn = typename ELFT::Dyn;
1397 using Elf_Shdr = typename ELFT::Shdr;
1398 using Elf_Sym = typename ELFT::Sym;
1399 using Elf_Verdef = typename ELFT::Verdef;
1400 using Elf_Versym = typename ELFT::Versym;
1402 ArrayRef<Elf_Dyn> dynamicTags;
1403 const ELFFile<ELFT> obj = this->getObj<ELFT>();
1404 ArrayRef<Elf_Shdr> sections = getELFShdrs<ELFT>();
1406 const Elf_Shdr *versymSec = nullptr;
1407 const Elf_Shdr *verdefSec = nullptr;
1408 const Elf_Shdr *verneedSec = nullptr;
1410 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1411 for (const Elf_Shdr &sec : sections) {
1412 switch (sec.sh_type) {
1413 default:
1414 continue;
1415 case SHT_DYNAMIC:
1416 dynamicTags =
1417 CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this);
1418 break;
1419 case SHT_GNU_versym:
1420 versymSec = &sec;
1421 break;
1422 case SHT_GNU_verdef:
1423 verdefSec = &sec;
1424 break;
1425 case SHT_GNU_verneed:
1426 verneedSec = &sec;
1427 break;
1431 if (versymSec && numELFSyms == 0) {
1432 error("SHT_GNU_versym should be associated with symbol table");
1433 return;
1436 // Search for a DT_SONAME tag to initialize this->soName.
1437 for (const Elf_Dyn &dyn : dynamicTags) {
1438 if (dyn.d_tag == DT_NEEDED) {
1439 uint64_t val = dyn.getVal();
1440 if (val >= this->stringTable.size())
1441 fatal(toString(this) + ": invalid DT_NEEDED entry");
1442 dtNeeded.push_back(this->stringTable.data() + val);
1443 } else if (dyn.d_tag == DT_SONAME) {
1444 uint64_t val = dyn.getVal();
1445 if (val >= this->stringTable.size())
1446 fatal(toString(this) + ": invalid DT_SONAME entry");
1447 soName = this->stringTable.data() + val;
1451 // DSOs are uniquified not by filename but by soname.
1452 DenseMap<CachedHashStringRef, SharedFile *>::iterator it;
1453 bool wasInserted;
1454 std::tie(it, wasInserted) =
1455 symtab.soNames.try_emplace(CachedHashStringRef(soName), this);
1457 // If a DSO appears more than once on the command line with and without
1458 // --as-needed, --no-as-needed takes precedence over --as-needed because a
1459 // user can add an extra DSO with --no-as-needed to force it to be added to
1460 // the dependency list.
1461 it->second->isNeeded |= isNeeded;
1462 if (!wasInserted)
1463 return;
1465 ctx.sharedFiles.push_back(this);
1467 verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1468 std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
1470 // Parse ".gnu.version" section which is a parallel array for the symbol
1471 // table. If a given file doesn't have a ".gnu.version" section, we use
1472 // VER_NDX_GLOBAL.
1473 size_t size = numELFSyms - firstGlobal;
1474 std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
1475 if (versymSec) {
1476 ArrayRef<Elf_Versym> versym =
1477 CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec),
1478 this)
1479 .slice(firstGlobal);
1480 for (size_t i = 0; i < size; ++i)
1481 versyms[i] = versym[i].vs_index;
1484 // System libraries can have a lot of symbols with versions. Using a
1485 // fixed buffer for computing the versions name (foo@ver) can save a
1486 // lot of allocations.
1487 SmallString<0> versionedNameBuffer;
1489 // Add symbols to the symbol table.
1490 ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1491 for (size_t i = 0, e = syms.size(); i != e; ++i) {
1492 const Elf_Sym &sym = syms[i];
1494 // ELF spec requires that all local symbols precede weak or global
1495 // symbols in each symbol table, and the index of first non-local symbol
1496 // is stored to sh_info. If a local symbol appears after some non-local
1497 // symbol, that's a violation of the spec.
1498 StringRef name = CHECK(sym.getName(stringTable), this);
1499 if (sym.getBinding() == STB_LOCAL) {
1500 errorOrWarn(toString(this) + ": invalid local symbol '" + name +
1501 "' in global part of symbol table");
1502 continue;
1505 const uint16_t ver = versyms[i], idx = ver & ~VERSYM_HIDDEN;
1506 if (sym.isUndefined()) {
1507 // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but
1508 // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL.
1509 if (ver != VER_NDX_LOCAL && ver != VER_NDX_GLOBAL) {
1510 if (idx >= verneeds.size()) {
1511 error("corrupt input file: version need index " + Twine(idx) +
1512 " for symbol " + name + " is out of bounds\n>>> defined in " +
1513 toString(this));
1514 continue;
1516 StringRef verName = stringTable.data() + verneeds[idx];
1517 versionedNameBuffer.clear();
1518 name = saver().save(
1519 (name + "@" + verName).toStringRef(versionedNameBuffer));
1521 Symbol *s = symtab.addSymbol(
1522 Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1523 s->exportDynamic = true;
1524 if (s->isUndefined() && sym.getBinding() != STB_WEAK &&
1525 config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore)
1526 requiredSymbols.push_back(s);
1527 continue;
1530 if (ver == VER_NDX_LOCAL ||
1531 (ver != VER_NDX_GLOBAL && idx >= verdefs.size())) {
1532 // In GNU ld < 2.31 (before 3be08ea4728b56d35e136af4e6fd3086ade17764), the
1533 // MIPS port puts _gp_disp symbol into DSO files and incorrectly assigns
1534 // VER_NDX_LOCAL. Workaround this bug.
1535 if (config->emachine == EM_MIPS && name == "_gp_disp")
1536 continue;
1537 error("corrupt input file: version definition index " + Twine(idx) +
1538 " for symbol " + name + " is out of bounds\n>>> defined in " +
1539 toString(this));
1540 continue;
1543 uint32_t alignment = getAlignment<ELFT>(sections, sym);
1544 if (ver == idx) {
1545 auto *s = symtab.addSymbol(
1546 SharedSymbol{*this, name, sym.getBinding(), sym.st_other,
1547 sym.getType(), sym.st_value, sym.st_size, alignment});
1548 if (s->file == this)
1549 s->verdefIndex = ver;
1552 // Also add the symbol with the versioned name to handle undefined symbols
1553 // with explicit versions.
1554 if (ver == VER_NDX_GLOBAL)
1555 continue;
1557 StringRef verName =
1558 stringTable.data() +
1559 reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1560 versionedNameBuffer.clear();
1561 name = (name + "@" + verName).toStringRef(versionedNameBuffer);
1562 auto *s = symtab.addSymbol(
1563 SharedSymbol{*this, saver().save(name), sym.getBinding(), sym.st_other,
1564 sym.getType(), sym.st_value, sym.st_size, alignment});
1565 if (s->file == this)
1566 s->verdefIndex = idx;
1570 static ELFKind getBitcodeELFKind(const Triple &t) {
1571 if (t.isLittleEndian())
1572 return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
1573 return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
1576 static uint16_t getBitcodeMachineKind(StringRef path, const Triple &t) {
1577 switch (t.getArch()) {
1578 case Triple::aarch64:
1579 case Triple::aarch64_be:
1580 return EM_AARCH64;
1581 case Triple::amdgcn:
1582 case Triple::r600:
1583 return EM_AMDGPU;
1584 case Triple::arm:
1585 case Triple::thumb:
1586 return EM_ARM;
1587 case Triple::avr:
1588 return EM_AVR;
1589 case Triple::hexagon:
1590 return EM_HEXAGON;
1591 case Triple::loongarch32:
1592 case Triple::loongarch64:
1593 return EM_LOONGARCH;
1594 case Triple::mips:
1595 case Triple::mipsel:
1596 case Triple::mips64:
1597 case Triple::mips64el:
1598 return EM_MIPS;
1599 case Triple::msp430:
1600 return EM_MSP430;
1601 case Triple::ppc:
1602 case Triple::ppcle:
1603 return EM_PPC;
1604 case Triple::ppc64:
1605 case Triple::ppc64le:
1606 return EM_PPC64;
1607 case Triple::riscv32:
1608 case Triple::riscv64:
1609 return EM_RISCV;
1610 case Triple::x86:
1611 return t.isOSIAMCU() ? EM_IAMCU : EM_386;
1612 case Triple::x86_64:
1613 return EM_X86_64;
1614 default:
1615 error(path + ": could not infer e_machine from bitcode target triple " +
1616 t.str());
1617 return EM_NONE;
1621 static uint8_t getOsAbi(const Triple &t) {
1622 switch (t.getOS()) {
1623 case Triple::AMDHSA:
1624 return ELF::ELFOSABI_AMDGPU_HSA;
1625 case Triple::AMDPAL:
1626 return ELF::ELFOSABI_AMDGPU_PAL;
1627 case Triple::Mesa3D:
1628 return ELF::ELFOSABI_AMDGPU_MESA3D;
1629 default:
1630 return ELF::ELFOSABI_NONE;
1634 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
1635 uint64_t offsetInArchive, bool lazy)
1636 : InputFile(BitcodeKind, mb) {
1637 this->archiveName = archiveName;
1638 this->lazy = lazy;
1640 std::string path = mb.getBufferIdentifier().str();
1641 if (config->thinLTOIndexOnly)
1642 path = replaceThinLTOSuffix(mb.getBufferIdentifier());
1644 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1645 // name. If two archives define two members with the same name, this
1646 // causes a collision which result in only one of the objects being taken
1647 // into consideration at LTO time (which very likely causes undefined
1648 // symbols later in the link stage). So we append file offset to make
1649 // filename unique.
1650 StringRef name = archiveName.empty()
1651 ? saver().save(path)
1652 : saver().save(archiveName + "(" + path::filename(path) +
1653 " at " + utostr(offsetInArchive) + ")");
1654 MemoryBufferRef mbref(mb.getBuffer(), name);
1656 obj = CHECK(lto::InputFile::create(mbref), this);
1658 Triple t(obj->getTargetTriple());
1659 ekind = getBitcodeELFKind(t);
1660 emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t);
1661 osabi = getOsAbi(t);
1664 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
1665 switch (gvVisibility) {
1666 case GlobalValue::DefaultVisibility:
1667 return STV_DEFAULT;
1668 case GlobalValue::HiddenVisibility:
1669 return STV_HIDDEN;
1670 case GlobalValue::ProtectedVisibility:
1671 return STV_PROTECTED;
1673 llvm_unreachable("unknown visibility");
1676 static void
1677 createBitcodeSymbol(Symbol *&sym, const std::vector<bool> &keptComdats,
1678 const lto::InputFile::Symbol &objSym, BitcodeFile &f) {
1679 uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1680 uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
1681 uint8_t visibility = mapVisibility(objSym.getVisibility());
1683 if (!sym)
1684 sym = symtab.insert(saver().save(objSym.getName()));
1686 int c = objSym.getComdatIndex();
1687 if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) {
1688 Undefined newSym(&f, StringRef(), binding, visibility, type);
1689 sym->resolve(newSym);
1690 sym->referenced = true;
1691 return;
1694 if (objSym.isCommon()) {
1695 sym->resolve(CommonSymbol{&f, StringRef(), binding, visibility, STT_OBJECT,
1696 objSym.getCommonAlignment(),
1697 objSym.getCommonSize()});
1698 } else {
1699 Defined newSym(&f, StringRef(), binding, visibility, type, 0, 0, nullptr);
1700 if (objSym.canBeOmittedFromSymbolTable())
1701 newSym.exportDynamic = false;
1702 sym->resolve(newSym);
1706 void BitcodeFile::parse() {
1707 for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) {
1708 keptComdats.push_back(
1709 s.second == Comdat::NoDeduplicate ||
1710 symtab.comdatGroups.try_emplace(CachedHashStringRef(s.first), this)
1711 .second);
1714 if (numSymbols == 0) {
1715 numSymbols = obj->symbols().size();
1716 symbols = std::make_unique<Symbol *[]>(numSymbols);
1718 // Process defined symbols first. See the comment in
1719 // ObjFile<ELFT>::initializeSymbols.
1720 for (auto [i, irSym] : llvm::enumerate(obj->symbols()))
1721 if (!irSym.isUndefined())
1722 createBitcodeSymbol(symbols[i], keptComdats, irSym, *this);
1723 for (auto [i, irSym] : llvm::enumerate(obj->symbols()))
1724 if (irSym.isUndefined())
1725 createBitcodeSymbol(symbols[i], keptComdats, irSym, *this);
1727 for (auto l : obj->getDependentLibraries())
1728 addDependentLibrary(l, this);
1731 void BitcodeFile::parseLazy() {
1732 numSymbols = obj->symbols().size();
1733 symbols = std::make_unique<Symbol *[]>(numSymbols);
1734 for (auto [i, irSym] : llvm::enumerate(obj->symbols()))
1735 if (!irSym.isUndefined()) {
1736 auto *sym = symtab.insert(saver().save(irSym.getName()));
1737 sym->resolve(LazyObject{*this});
1738 symbols[i] = sym;
1742 void BitcodeFile::postParse() {
1743 for (auto [i, irSym] : llvm::enumerate(obj->symbols())) {
1744 const Symbol &sym = *symbols[i];
1745 if (sym.file == this || !sym.isDefined() || irSym.isUndefined() ||
1746 irSym.isCommon() || irSym.isWeak())
1747 continue;
1748 int c = irSym.getComdatIndex();
1749 if (c != -1 && !keptComdats[c])
1750 continue;
1751 reportDuplicate(sym, this, nullptr, 0);
1755 void BinaryFile::parse() {
1756 ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
1757 auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1758 8, data, ".data");
1759 sections.push_back(section);
1761 // For each input file foo that is embedded to a result as a binary
1762 // blob, we define _binary_foo_{start,end,size} symbols, so that
1763 // user programs can access blobs by name. Non-alphanumeric
1764 // characters in a filename are replaced with underscore.
1765 std::string s = "_binary_" + mb.getBufferIdentifier().str();
1766 for (char &c : s)
1767 if (!isAlnum(c))
1768 c = '_';
1770 llvm::StringSaver &saver = lld::saver();
1772 symtab.addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_start"),
1773 STB_GLOBAL, STV_DEFAULT, STT_OBJECT, 0, 0,
1774 section});
1775 symtab.addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_end"),
1776 STB_GLOBAL, STV_DEFAULT, STT_OBJECT,
1777 data.size(), 0, section});
1778 symtab.addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_size"),
1779 STB_GLOBAL, STV_DEFAULT, STT_OBJECT,
1780 data.size(), 0, nullptr});
1783 ELFFileBase *elf::createObjFile(MemoryBufferRef mb, StringRef archiveName,
1784 bool lazy) {
1785 ELFFileBase *f;
1786 switch (getELFKind(mb, archiveName)) {
1787 case ELF32LEKind:
1788 f = make<ObjFile<ELF32LE>>(ELF32LEKind, mb, archiveName);
1789 break;
1790 case ELF32BEKind:
1791 f = make<ObjFile<ELF32BE>>(ELF32BEKind, mb, archiveName);
1792 break;
1793 case ELF64LEKind:
1794 f = make<ObjFile<ELF64LE>>(ELF64LEKind, mb, archiveName);
1795 break;
1796 case ELF64BEKind:
1797 f = make<ObjFile<ELF64BE>>(ELF64BEKind, mb, archiveName);
1798 break;
1799 default:
1800 llvm_unreachable("getELFKind");
1802 f->init();
1803 f->lazy = lazy;
1804 return f;
1807 template <class ELFT> void ObjFile<ELFT>::parseLazy() {
1808 const ArrayRef<typename ELFT::Sym> eSyms = this->getELFSyms<ELFT>();
1809 numSymbols = eSyms.size();
1810 symbols = std::make_unique<Symbol *[]>(numSymbols);
1812 // resolve() may trigger this->extract() if an existing symbol is an undefined
1813 // symbol. If that happens, this function has served its purpose, and we can
1814 // exit from the loop early.
1815 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1816 if (eSyms[i].st_shndx == SHN_UNDEF)
1817 continue;
1818 symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this));
1819 symbols[i]->resolve(LazyObject{*this});
1820 if (!lazy)
1821 break;
1825 bool InputFile::shouldExtractForCommon(StringRef name) {
1826 if (isa<BitcodeFile>(this))
1827 return isBitcodeNonCommonDef(mb, name, archiveName);
1829 return isNonCommonDef(mb, name, archiveName);
1832 std::string elf::replaceThinLTOSuffix(StringRef path) {
1833 auto [suffix, repl] = config->thinLTOObjectSuffixReplace;
1834 if (path.consume_back(suffix))
1835 return (path + repl).str();
1836 return std::string(path);
1839 template class elf::ObjFile<ELF32LE>;
1840 template class elf::ObjFile<ELF32BE>;
1841 template class elf::ObjFile<ELF64LE>;
1842 template class elf::ObjFile<ELF64BE>;
1844 template void SharedFile::parse<ELF32LE>();
1845 template void SharedFile::parse<ELF32BE>();
1846 template void SharedFile::parse<ELF64LE>();
1847 template void SharedFile::parse<ELF64BE>();