[cmake] Fix ms-compat version in WinMsvc.cmake
[llvm-project.git] / lld / ELF / InputFiles.cpp
bloba2f95238b12a4fc9cbeac1da01e17299e0e01e9f
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 bool InputFile::isInGroup;
44 uint32_t InputFile::nextGroupId;
46 std::unique_ptr<TarWriter> elf::tar;
48 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
49 std::string lld::toString(const InputFile *f) {
50 static std::mutex mu;
51 if (!f)
52 return "<internal>";
55 std::lock_guard<std::mutex> lock(mu);
56 if (f->toStringCache.empty()) {
57 if (f->archiveName.empty())
58 f->toStringCache = f->getName();
59 else
60 (f->archiveName + "(" + f->getName() + ")").toVector(f->toStringCache);
63 return std::string(f->toStringCache);
66 static ELFKind getELFKind(MemoryBufferRef mb, StringRef archiveName) {
67 unsigned char size;
68 unsigned char endian;
69 std::tie(size, endian) = getElfArchType(mb.getBuffer());
71 auto report = [&](StringRef msg) {
72 StringRef filename = mb.getBufferIdentifier();
73 if (archiveName.empty())
74 fatal(filename + ": " + msg);
75 else
76 fatal(archiveName + "(" + filename + "): " + msg);
79 if (!mb.getBuffer().startswith(ElfMagic))
80 report("not an ELF file");
81 if (endian != ELFDATA2LSB && endian != ELFDATA2MSB)
82 report("corrupted ELF file: invalid data encoding");
83 if (size != ELFCLASS32 && size != ELFCLASS64)
84 report("corrupted ELF file: invalid file class");
86 size_t bufSize = mb.getBuffer().size();
87 if ((size == ELFCLASS32 && bufSize < sizeof(Elf32_Ehdr)) ||
88 (size == ELFCLASS64 && bufSize < sizeof(Elf64_Ehdr)))
89 report("corrupted ELF file: file is too short");
91 if (size == ELFCLASS32)
92 return (endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
93 return (endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
96 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
97 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
98 // the input objects have been compiled.
99 static void updateARMVFPArgs(const ARMAttributeParser &attributes,
100 const InputFile *f) {
101 Optional<unsigned> attr =
102 attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
103 if (!attr)
104 // If an ABI tag isn't present then it is implicitly given the value of 0
105 // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
106 // including some in glibc that don't use FP args (and should have value 3)
107 // don't have the attribute so we do not consider an implicit value of 0
108 // as a clash.
109 return;
111 unsigned vfpArgs = *attr;
112 ARMVFPArgKind arg;
113 switch (vfpArgs) {
114 case ARMBuildAttrs::BaseAAPCS:
115 arg = ARMVFPArgKind::Base;
116 break;
117 case ARMBuildAttrs::HardFPAAPCS:
118 arg = ARMVFPArgKind::VFP;
119 break;
120 case ARMBuildAttrs::ToolChainFPPCS:
121 // Tool chain specific convention that conforms to neither AAPCS variant.
122 arg = ARMVFPArgKind::ToolChain;
123 break;
124 case ARMBuildAttrs::CompatibleFPAAPCS:
125 // Object compatible with all conventions.
126 return;
127 default:
128 error(toString(f) + ": unknown Tag_ABI_VFP_args value: " + Twine(vfpArgs));
129 return;
131 // Follow ld.bfd and error if there is a mix of calling conventions.
132 if (config->armVFPArgs != arg && config->armVFPArgs != ARMVFPArgKind::Default)
133 error(toString(f) + ": incompatible Tag_ABI_VFP_args");
134 else
135 config->armVFPArgs = arg;
138 // The ARM support in lld makes some use of instructions that are not available
139 // on all ARM architectures. Namely:
140 // - Use of BLX instruction for interworking between ARM and Thumb state.
141 // - Use of the extended Thumb branch encoding in relocation.
142 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
143 // The ARM Attributes section contains information about the architecture chosen
144 // at compile time. We follow the convention that if at least one input object
145 // is compiled with an architecture that supports these features then lld is
146 // permitted to use them.
147 static void updateSupportedARMFeatures(const ARMAttributeParser &attributes) {
148 Optional<unsigned> attr =
149 attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
150 if (!attr)
151 return;
152 auto arch = attr.value();
153 switch (arch) {
154 case ARMBuildAttrs::Pre_v4:
155 case ARMBuildAttrs::v4:
156 case ARMBuildAttrs::v4T:
157 // Architectures prior to v5 do not support BLX instruction
158 break;
159 case ARMBuildAttrs::v5T:
160 case ARMBuildAttrs::v5TE:
161 case ARMBuildAttrs::v5TEJ:
162 case ARMBuildAttrs::v6:
163 case ARMBuildAttrs::v6KZ:
164 case ARMBuildAttrs::v6K:
165 config->armHasBlx = true;
166 // Architectures used in pre-Cortex processors do not support
167 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
168 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
169 break;
170 default:
171 // All other Architectures have BLX and extended branch encoding
172 config->armHasBlx = true;
173 config->armJ1J2BranchEncoding = true;
174 if (arch != ARMBuildAttrs::v6_M && arch != ARMBuildAttrs::v6S_M)
175 // All Architectures used in Cortex processors with the exception
176 // of v6-M and v6S-M have the MOVT and MOVW instructions.
177 config->armHasMovtMovw = true;
178 break;
182 InputFile::InputFile(Kind k, MemoryBufferRef m)
183 : mb(m), groupId(nextGroupId), fileKind(k) {
184 // All files within the same --{start,end}-group get the same group ID.
185 // Otherwise, a new file will get a new group ID.
186 if (!isInGroup)
187 ++nextGroupId;
190 Optional<MemoryBufferRef> elf::readFile(StringRef path) {
191 llvm::TimeTraceScope timeScope("Load input files", path);
193 // The --chroot option changes our virtual root directory.
194 // This is useful when you are dealing with files created by --reproduce.
195 if (!config->chroot.empty() && path.startswith("/"))
196 path = saver().save(config->chroot + path);
198 log(path);
199 config->dependencyFiles.insert(llvm::CachedHashString(path));
201 auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
202 /*RequiresNullTerminator=*/false);
203 if (auto ec = mbOrErr.getError()) {
204 error("cannot open " + path + ": " + ec.message());
205 return None;
208 MemoryBufferRef mbref = (*mbOrErr)->getMemBufferRef();
209 ctx->memoryBuffers.push_back(std::move(*mbOrErr)); // take MB ownership
211 if (tar)
212 tar->append(relativeToRoot(path), mbref.getBuffer());
213 return mbref;
216 // All input object files must be for the same architecture
217 // (e.g. it does not make sense to link x86 object files with
218 // MIPS object files.) This function checks for that error.
219 static bool isCompatible(InputFile *file) {
220 if (!file->isElf() && !isa<BitcodeFile>(file))
221 return true;
223 if (file->ekind == config->ekind && file->emachine == config->emachine) {
224 if (config->emachine != EM_MIPS)
225 return true;
226 if (isMipsN32Abi(file) == config->mipsN32Abi)
227 return true;
230 StringRef target =
231 !config->bfdname.empty() ? config->bfdname : config->emulation;
232 if (!target.empty()) {
233 error(toString(file) + " is incompatible with " + target);
234 return false;
237 InputFile *existing = nullptr;
238 if (!ctx->objectFiles.empty())
239 existing = ctx->objectFiles[0];
240 else if (!ctx->sharedFiles.empty())
241 existing = ctx->sharedFiles[0];
242 else if (!ctx->bitcodeFiles.empty())
243 existing = ctx->bitcodeFiles[0];
244 std::string with;
245 if (existing)
246 with = " with " + toString(existing);
247 error(toString(file) + " is incompatible" + with);
248 return false;
251 template <class ELFT> static void doParseFile(InputFile *file) {
252 if (!isCompatible(file))
253 return;
255 // Binary file
256 if (auto *f = dyn_cast<BinaryFile>(file)) {
257 ctx->binaryFiles.push_back(f);
258 f->parse();
259 return;
262 // Lazy object file
263 if (file->lazy) {
264 if (auto *f = dyn_cast<BitcodeFile>(file)) {
265 ctx->lazyBitcodeFiles.push_back(f);
266 f->parseLazy();
267 } else {
268 cast<ObjFile<ELFT>>(file)->parseLazy();
270 return;
273 if (config->trace)
274 message(toString(file));
276 // .so file
277 if (auto *f = dyn_cast<SharedFile>(file)) {
278 f->parse<ELFT>();
279 return;
282 // LLVM bitcode file
283 if (auto *f = dyn_cast<BitcodeFile>(file)) {
284 ctx->bitcodeFiles.push_back(f);
285 f->parse<ELFT>();
286 return;
289 // Regular object file
290 ctx->objectFiles.push_back(cast<ELFFileBase>(file));
291 cast<ObjFile<ELFT>>(file)->parse();
294 // Add symbols in File to the symbol table.
295 void elf::parseFile(InputFile *file) { invokeELFT(doParseFile, file); }
297 // Concatenates arguments to construct a string representing an error location.
298 static std::string createFileLineMsg(StringRef path, unsigned line) {
299 std::string filename = std::string(path::filename(path));
300 std::string lineno = ":" + std::to_string(line);
301 if (filename == path)
302 return filename + lineno;
303 return filename + lineno + " (" + path.str() + lineno + ")";
306 template <class ELFT>
307 static std::string getSrcMsgAux(ObjFile<ELFT> &file, const Symbol &sym,
308 InputSectionBase &sec, uint64_t offset) {
309 // In DWARF, functions and variables are stored to different places.
310 // First, look up a function for a given offset.
311 if (Optional<DILineInfo> info = file.getDILineInfo(&sec, offset))
312 return createFileLineMsg(info->FileName, info->Line);
314 // If it failed, look up again as a variable.
315 if (Optional<std::pair<std::string, unsigned>> fileLine =
316 file.getVariableLoc(sym.getName()))
317 return createFileLineMsg(fileLine->first, fileLine->second);
319 // File.sourceFile contains STT_FILE symbol, and that is a last resort.
320 return std::string(file.sourceFile);
323 std::string InputFile::getSrcMsg(const Symbol &sym, InputSectionBase &sec,
324 uint64_t offset) {
325 if (kind() != ObjKind)
326 return "";
327 switch (config->ekind) {
328 default:
329 llvm_unreachable("Invalid kind");
330 case ELF32LEKind:
331 return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), sym, sec, offset);
332 case ELF32BEKind:
333 return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), sym, sec, offset);
334 case ELF64LEKind:
335 return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), sym, sec, offset);
336 case ELF64BEKind:
337 return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), sym, sec, offset);
341 StringRef InputFile::getNameForScript() const {
342 if (archiveName.empty())
343 return getName();
345 if (nameForScriptCache.empty())
346 nameForScriptCache = (archiveName + Twine(':') + getName()).str();
348 return nameForScriptCache;
351 // An ELF object file may contain a `.deplibs` section. If it exists, the
352 // section contains a list of library specifiers such as `m` for libm. This
353 // function resolves a given name by finding the first matching library checking
354 // the various ways that a library can be specified to LLD. This ELF extension
355 // is a form of autolinking and is called `dependent libraries`. It is currently
356 // unique to LLVM and lld.
357 static void addDependentLibrary(StringRef specifier, const InputFile *f) {
358 if (!config->dependentLibraries)
359 return;
360 if (Optional<std::string> s = searchLibraryBaseName(specifier))
361 driver->addFile(saver().save(*s), /*withLOption=*/true);
362 else if (Optional<std::string> s = findFromSearchPaths(specifier))
363 driver->addFile(saver().save(*s), /*withLOption=*/true);
364 else if (fs::exists(specifier))
365 driver->addFile(specifier, /*withLOption=*/false);
366 else
367 error(toString(f) +
368 ": unable to find library from dependent library specifier: " +
369 specifier);
372 // Record the membership of a section group so that in the garbage collection
373 // pass, section group members are kept or discarded as a unit.
374 template <class ELFT>
375 static void handleSectionGroup(ArrayRef<InputSectionBase *> sections,
376 ArrayRef<typename ELFT::Word> entries) {
377 bool hasAlloc = false;
378 for (uint32_t index : entries.slice(1)) {
379 if (index >= sections.size())
380 return;
381 if (InputSectionBase *s = sections[index])
382 if (s != &InputSection::discarded && s->flags & SHF_ALLOC)
383 hasAlloc = true;
386 // If any member has the SHF_ALLOC flag, the whole group is subject to garbage
387 // collection. See the comment in markLive(). This rule retains .debug_types
388 // and .rela.debug_types.
389 if (!hasAlloc)
390 return;
392 // Connect the members in a circular doubly-linked list via
393 // nextInSectionGroup.
394 InputSectionBase *head;
395 InputSectionBase *prev = nullptr;
396 for (uint32_t index : entries.slice(1)) {
397 InputSectionBase *s = sections[index];
398 if (!s || s == &InputSection::discarded)
399 continue;
400 if (prev)
401 prev->nextInSectionGroup = s;
402 else
403 head = s;
404 prev = s;
406 if (prev)
407 prev->nextInSectionGroup = head;
410 template <class ELFT> DWARFCache *ObjFile<ELFT>::getDwarf() {
411 llvm::call_once(initDwarf, [this]() {
412 dwarf = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
413 std::make_unique<LLDDwarfObj<ELFT>>(this), "",
414 [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
415 [&](Error warning) {
416 warn(getName() + ": " + toString(std::move(warning)));
417 }));
420 return dwarf.get();
423 // Returns the pair of file name and line number describing location of data
424 // object (variable, array, etc) definition.
425 template <class ELFT>
426 Optional<std::pair<std::string, unsigned>>
427 ObjFile<ELFT>::getVariableLoc(StringRef name) {
428 return getDwarf()->getVariableLoc(name);
431 // Returns source line information for a given offset
432 // using DWARF debug info.
433 template <class ELFT>
434 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *s,
435 uint64_t offset) {
436 // Detect SectionIndex for specified section.
437 uint64_t sectionIndex = object::SectionedAddress::UndefSection;
438 ArrayRef<InputSectionBase *> sections = s->file->getSections();
439 for (uint64_t curIndex = 0; curIndex < sections.size(); ++curIndex) {
440 if (s == sections[curIndex]) {
441 sectionIndex = curIndex;
442 break;
446 return getDwarf()->getDILineInfo(offset, sectionIndex);
449 ELFFileBase::ELFFileBase(Kind k, MemoryBufferRef mb) : InputFile(k, mb) {
450 ekind = getELFKind(mb, "");
452 switch (ekind) {
453 case ELF32LEKind:
454 init<ELF32LE>();
455 break;
456 case ELF32BEKind:
457 init<ELF32BE>();
458 break;
459 case ELF64LEKind:
460 init<ELF64LE>();
461 break;
462 case ELF64BEKind:
463 init<ELF64BE>();
464 break;
465 default:
466 llvm_unreachable("getELFKind");
470 template <typename Elf_Shdr>
471 static const Elf_Shdr *findSection(ArrayRef<Elf_Shdr> sections, uint32_t type) {
472 for (const Elf_Shdr &sec : sections)
473 if (sec.sh_type == type)
474 return &sec;
475 return nullptr;
478 template <class ELFT> void ELFFileBase::init() {
479 using Elf_Shdr = typename ELFT::Shdr;
480 using Elf_Sym = typename ELFT::Sym;
482 // Initialize trivial attributes.
483 const ELFFile<ELFT> &obj = getObj<ELFT>();
484 emachine = obj.getHeader().e_machine;
485 osabi = obj.getHeader().e_ident[llvm::ELF::EI_OSABI];
486 abiVersion = obj.getHeader().e_ident[llvm::ELF::EI_ABIVERSION];
488 ArrayRef<Elf_Shdr> sections = CHECK(obj.sections(), this);
489 elfShdrs = sections.data();
490 numELFShdrs = sections.size();
492 // Find a symbol table.
493 bool isDSO =
494 (identify_magic(mb.getBuffer()) == file_magic::elf_shared_object);
495 const Elf_Shdr *symtabSec =
496 findSection(sections, isDSO ? SHT_DYNSYM : SHT_SYMTAB);
498 if (!symtabSec)
499 return;
501 // Initialize members corresponding to a symbol table.
502 firstGlobal = symtabSec->sh_info;
504 ArrayRef<Elf_Sym> eSyms = CHECK(obj.symbols(symtabSec), this);
505 if (firstGlobal == 0 || firstGlobal > eSyms.size())
506 fatal(toString(this) + ": invalid sh_info in symbol table");
508 elfSyms = reinterpret_cast<const void *>(eSyms.data());
509 numELFSyms = uint32_t(eSyms.size());
510 stringTable = CHECK(obj.getStringTableForSymtab(*symtabSec, sections), this);
513 template <class ELFT>
514 uint32_t ObjFile<ELFT>::getSectionIndex(const Elf_Sym &sym) const {
515 return CHECK(
516 this->getObj().getSectionIndex(sym, getELFSyms<ELFT>(), shndxTable),
517 this);
520 template <class ELFT> void ObjFile<ELFT>::parse(bool ignoreComdats) {
521 object::ELFFile<ELFT> obj = this->getObj();
522 // Read a section table. justSymbols is usually false.
523 if (this->justSymbols) {
524 initializeJustSymbols();
525 initializeSymbols(obj);
526 return;
529 // Handle dependent libraries and selection of section groups as these are not
530 // done in parallel.
531 ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
532 StringRef shstrtab = CHECK(obj.getSectionStringTable(objSections), this);
533 uint64_t size = objSections.size();
534 sections.resize(size);
535 for (size_t i = 0; i != size; ++i) {
536 const Elf_Shdr &sec = objSections[i];
537 if (sec.sh_type == SHT_LLVM_DEPENDENT_LIBRARIES && !config->relocatable) {
538 StringRef name = check(obj.getSectionName(sec, shstrtab));
539 ArrayRef<char> data = CHECK(
540 this->getObj().template getSectionContentsAsArray<char>(sec), this);
541 if (!data.empty() && data.back() != '\0') {
542 error(
543 toString(this) +
544 ": corrupted dependent libraries section (unterminated string): " +
545 name);
546 } else {
547 for (const char *d = data.begin(), *e = data.end(); d < e;) {
548 StringRef s(d);
549 addDependentLibrary(s, this);
550 d += s.size() + 1;
553 this->sections[i] = &InputSection::discarded;
554 continue;
557 if (sec.sh_type == SHT_ARM_ATTRIBUTES && config->emachine == EM_ARM) {
558 ARMAttributeParser attributes;
559 ArrayRef<uint8_t> contents =
560 check(this->getObj().getSectionContents(sec));
561 StringRef name = check(obj.getSectionName(sec, shstrtab));
562 this->sections[i] = &InputSection::discarded;
563 if (Error e = attributes.parse(contents, config->ekind == ELF32LEKind
564 ? support::little
565 : support::big)) {
566 InputSection isec(*this, sec, name);
567 warn(toString(&isec) + ": " + llvm::toString(std::move(e)));
568 } else {
569 updateSupportedARMFeatures(attributes);
570 updateARMVFPArgs(attributes, this);
572 // FIXME: Retain the first attribute section we see. The eglibc ARM
573 // dynamic loaders require the presence of an attribute section for
574 // dlopen to work. In a full implementation we would merge all attribute
575 // sections.
576 if (in.attributes == nullptr) {
577 in.attributes = std::make_unique<InputSection>(*this, sec, name);
578 this->sections[i] = in.attributes.get();
583 if (sec.sh_type == SHT_RISCV_ATTRIBUTES && config->emachine == EM_RISCV) {
584 RISCVAttributeParser attributes;
585 ArrayRef<uint8_t> contents =
586 check(this->getObj().getSectionContents(sec));
587 StringRef name = check(obj.getSectionName(sec, shstrtab));
588 this->sections[i] = &InputSection::discarded;
589 if (Error e = attributes.parse(contents, support::little)) {
590 InputSection isec(*this, sec, name);
591 warn(toString(&isec) + ": " + llvm::toString(std::move(e)));
592 } else {
593 // FIXME: Validate arch tag contains C if and only if EF_RISCV_RVC is
594 // present.
596 // FIXME: Retain the first attribute section we see. Tools such as
597 // llvm-objdump make use of the attribute section to determine which
598 // standard extensions to enable. In a full implementation we would
599 // merge all attribute sections.
600 if (in.attributes == nullptr) {
601 in.attributes = std::make_unique<InputSection>(*this, sec, name);
602 this->sections[i] = in.attributes.get();
607 if (sec.sh_type != SHT_GROUP)
608 continue;
609 StringRef signature = getShtGroupSignature(objSections, sec);
610 ArrayRef<Elf_Word> entries =
611 CHECK(obj.template getSectionContentsAsArray<Elf_Word>(sec), this);
612 if (entries.empty())
613 fatal(toString(this) + ": empty SHT_GROUP");
615 Elf_Word flag = entries[0];
616 if (flag && flag != GRP_COMDAT)
617 fatal(toString(this) + ": unsupported SHT_GROUP format");
619 bool keepGroup =
620 (flag & GRP_COMDAT) == 0 || ignoreComdats ||
621 symtab->comdatGroups.try_emplace(CachedHashStringRef(signature), this)
622 .second;
623 if (keepGroup) {
624 if (config->relocatable)
625 this->sections[i] = createInputSection(
626 i, sec, check(obj.getSectionName(sec, shstrtab)));
627 continue;
630 // Otherwise, discard group members.
631 for (uint32_t secIndex : entries.slice(1)) {
632 if (secIndex >= size)
633 fatal(toString(this) +
634 ": invalid section index in group: " + Twine(secIndex));
635 this->sections[secIndex] = &InputSection::discarded;
639 // Read a symbol table.
640 initializeSymbols(obj);
643 // Sections with SHT_GROUP and comdat bits define comdat section groups.
644 // They are identified and deduplicated by group name. This function
645 // returns a group name.
646 template <class ELFT>
647 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> sections,
648 const Elf_Shdr &sec) {
649 typename ELFT::SymRange symbols = this->getELFSyms<ELFT>();
650 if (sec.sh_info >= symbols.size())
651 fatal(toString(this) + ": invalid symbol index");
652 const typename ELFT::Sym &sym = symbols[sec.sh_info];
653 return CHECK(sym.getName(this->stringTable), this);
656 template <class ELFT>
657 bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &sec, StringRef name) {
658 // On a regular link we don't merge sections if -O0 (default is -O1). This
659 // sometimes makes the linker significantly faster, although the output will
660 // be bigger.
662 // Doing the same for -r would create a problem as it would combine sections
663 // with different sh_entsize. One option would be to just copy every SHF_MERGE
664 // section as is to the output. While this would produce a valid ELF file with
665 // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
666 // they see two .debug_str. We could have separate logic for combining
667 // SHF_MERGE sections based both on their name and sh_entsize, but that seems
668 // to be more trouble than it is worth. Instead, we just use the regular (-O1)
669 // logic for -r.
670 if (config->optimize == 0 && !config->relocatable)
671 return false;
673 // A mergeable section with size 0 is useless because they don't have
674 // any data to merge. A mergeable string section with size 0 can be
675 // argued as invalid because it doesn't end with a null character.
676 // We'll avoid a mess by handling them as if they were non-mergeable.
677 if (sec.sh_size == 0)
678 return false;
680 // Check for sh_entsize. The ELF spec is not clear about the zero
681 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
682 // the section does not hold a table of fixed-size entries". We know
683 // that Rust 1.13 produces a string mergeable section with a zero
684 // sh_entsize. Here we just accept it rather than being picky about it.
685 uint64_t entSize = sec.sh_entsize;
686 if (entSize == 0)
687 return false;
688 if (sec.sh_size % entSize)
689 fatal(toString(this) + ":(" + name + "): SHF_MERGE section size (" +
690 Twine(sec.sh_size) + ") must be a multiple of sh_entsize (" +
691 Twine(entSize) + ")");
693 if (sec.sh_flags & SHF_WRITE)
694 fatal(toString(this) + ":(" + name +
695 "): writable SHF_MERGE section is not supported");
697 return true;
700 // This is for --just-symbols.
702 // --just-symbols is a very minor feature that allows you to link your
703 // output against other existing program, so that if you load both your
704 // program and the other program into memory, your output can refer the
705 // other program's symbols.
707 // When the option is given, we link "just symbols". The section table is
708 // initialized with null pointers.
709 template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
710 sections.resize(numELFShdrs);
713 template <class ELFT>
714 void ObjFile<ELFT>::initializeSections(bool ignoreComdats,
715 const llvm::object::ELFFile<ELFT> &obj) {
716 ArrayRef<Elf_Shdr> objSections = getELFShdrs<ELFT>();
717 StringRef shstrtab = CHECK(obj.getSectionStringTable(objSections), this);
718 uint64_t size = objSections.size();
719 SmallVector<ArrayRef<Elf_Word>, 0> selectedGroups;
720 for (size_t i = 0; i != size; ++i) {
721 if (this->sections[i] == &InputSection::discarded)
722 continue;
723 const Elf_Shdr &sec = objSections[i];
725 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
726 // if -r is given, we'll let the final link discard such sections.
727 // This is compatible with GNU.
728 if ((sec.sh_flags & SHF_EXCLUDE) && !config->relocatable) {
729 if (sec.sh_type == SHT_LLVM_CALL_GRAPH_PROFILE)
730 cgProfileSectionIndex = i;
731 if (sec.sh_type == SHT_LLVM_ADDRSIG) {
732 // We ignore the address-significance table if we know that the object
733 // file was created by objcopy or ld -r. This is because these tools
734 // will reorder the symbols in the symbol table, invalidating the data
735 // in the address-significance table, which refers to symbols by index.
736 if (sec.sh_link != 0)
737 this->addrsigSec = &sec;
738 else if (config->icf == ICFLevel::Safe)
739 warn(toString(this) +
740 ": --icf=safe conservatively ignores "
741 "SHT_LLVM_ADDRSIG [index " +
742 Twine(i) +
743 "] with sh_link=0 "
744 "(likely created using objcopy or ld -r)");
746 this->sections[i] = &InputSection::discarded;
747 continue;
750 switch (sec.sh_type) {
751 case SHT_GROUP: {
752 if (!config->relocatable)
753 sections[i] = &InputSection::discarded;
754 StringRef signature =
755 cantFail(this->getELFSyms<ELFT>()[sec.sh_info].getName(stringTable));
756 ArrayRef<Elf_Word> entries =
757 cantFail(obj.template getSectionContentsAsArray<Elf_Word>(sec));
758 if ((entries[0] & GRP_COMDAT) == 0 || ignoreComdats ||
759 symtab->comdatGroups.find(CachedHashStringRef(signature))->second ==
760 this)
761 selectedGroups.push_back(entries);
762 break;
764 case SHT_SYMTAB_SHNDX:
765 shndxTable = CHECK(obj.getSHNDXTable(sec, objSections), this);
766 break;
767 case SHT_SYMTAB:
768 case SHT_STRTAB:
769 case SHT_REL:
770 case SHT_RELA:
771 case SHT_NULL:
772 break;
773 case SHT_LLVM_SYMPART:
774 ctx->hasSympart.store(true, std::memory_order_relaxed);
775 [[fallthrough]];
776 default:
777 this->sections[i] =
778 createInputSection(i, sec, check(obj.getSectionName(sec, shstrtab)));
782 // We have a second loop. It is used to:
783 // 1) handle SHF_LINK_ORDER sections.
784 // 2) create SHT_REL[A] sections. In some cases the section header index of a
785 // relocation section may be smaller than that of the relocated section. In
786 // such cases, the relocation section would attempt to reference a target
787 // section that has not yet been created. For simplicity, delay creation of
788 // relocation sections until now.
789 for (size_t i = 0; i != size; ++i) {
790 if (this->sections[i] == &InputSection::discarded)
791 continue;
792 const Elf_Shdr &sec = objSections[i];
794 if (sec.sh_type == SHT_REL || sec.sh_type == SHT_RELA) {
795 // Find a relocation target section and associate this section with that.
796 // Target may have been discarded if it is in a different section group
797 // and the group is discarded, even though it's a violation of the spec.
798 // We handle that situation gracefully by discarding dangling relocation
799 // sections.
800 const uint32_t info = sec.sh_info;
801 InputSectionBase *s = getRelocTarget(i, sec, info);
802 if (!s)
803 continue;
805 // ELF spec allows mergeable sections with relocations, but they are rare,
806 // and it is in practice hard to merge such sections by contents, because
807 // applying relocations at end of linking changes section contents. So, we
808 // simply handle such sections as non-mergeable ones. Degrading like this
809 // is acceptable because section merging is optional.
810 if (auto *ms = dyn_cast<MergeInputSection>(s)) {
811 s = makeThreadLocal<InputSection>(ms->file, ms->flags, ms->type,
812 ms->alignment, ms->data(), ms->name);
813 sections[info] = s;
816 if (s->relSecIdx != 0)
817 error(
818 toString(s) +
819 ": multiple relocation sections to one section are not supported");
820 s->relSecIdx = i;
822 // Relocation sections are usually removed from the output, so return
823 // `nullptr` for the normal case. However, if -r or --emit-relocs is
824 // specified, we need to copy them to the output. (Some post link analysis
825 // tools specify --emit-relocs to obtain the information.)
826 if (config->copyRelocs) {
827 auto *isec = makeThreadLocal<InputSection>(
828 *this, sec, check(obj.getSectionName(sec, shstrtab)));
829 // If the relocated section is discarded (due to /DISCARD/ or
830 // --gc-sections), the relocation section should be discarded as well.
831 s->dependentSections.push_back(isec);
832 sections[i] = isec;
834 continue;
837 // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have
838 // the flag.
839 if (!sec.sh_link || !(sec.sh_flags & SHF_LINK_ORDER))
840 continue;
842 InputSectionBase *linkSec = nullptr;
843 if (sec.sh_link < size)
844 linkSec = this->sections[sec.sh_link];
845 if (!linkSec)
846 fatal(toString(this) + ": invalid sh_link index: " + Twine(sec.sh_link));
848 // A SHF_LINK_ORDER section is discarded if its linked-to section is
849 // discarded.
850 InputSection *isec = cast<InputSection>(this->sections[i]);
851 linkSec->dependentSections.push_back(isec);
852 if (!isa<InputSection>(linkSec))
853 error("a section " + isec->name +
854 " with SHF_LINK_ORDER should not refer a non-regular section: " +
855 toString(linkSec));
858 for (ArrayRef<Elf_Word> entries : selectedGroups)
859 handleSectionGroup<ELFT>(this->sections, entries);
862 // If a source file is compiled with x86 hardware-assisted call flow control
863 // enabled, the generated object file contains feature flags indicating that
864 // fact. This function reads the feature flags and returns it.
866 // Essentially we want to read a single 32-bit value in this function, but this
867 // function is rather complicated because the value is buried deep inside a
868 // .note.gnu.property section.
870 // The section consists of one or more NOTE records. Each NOTE record consists
871 // of zero or more type-length-value fields. We want to find a field of a
872 // certain type. It seems a bit too much to just store a 32-bit value, perhaps
873 // the ABI is unnecessarily complicated.
874 template <class ELFT> static uint32_t readAndFeatures(const InputSection &sec) {
875 using Elf_Nhdr = typename ELFT::Nhdr;
876 using Elf_Note = typename ELFT::Note;
878 uint32_t featuresSet = 0;
879 ArrayRef<uint8_t> data = sec.rawData;
880 auto reportFatal = [&](const uint8_t *place, const char *msg) {
881 fatal(toString(sec.file) + ":(" + sec.name + "+0x" +
882 Twine::utohexstr(place - sec.rawData.data()) + "): " + msg);
884 while (!data.empty()) {
885 // Read one NOTE record.
886 auto *nhdr = reinterpret_cast<const Elf_Nhdr *>(data.data());
887 if (data.size() < sizeof(Elf_Nhdr) || data.size() < nhdr->getSize())
888 reportFatal(data.data(), "data is too short");
890 Elf_Note note(*nhdr);
891 if (nhdr->n_type != NT_GNU_PROPERTY_TYPE_0 || note.getName() != "GNU") {
892 data = data.slice(nhdr->getSize());
893 continue;
896 uint32_t featureAndType = config->emachine == EM_AARCH64
897 ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
898 : GNU_PROPERTY_X86_FEATURE_1_AND;
900 // Read a body of a NOTE record, which consists of type-length-value fields.
901 ArrayRef<uint8_t> desc = note.getDesc();
902 while (!desc.empty()) {
903 const uint8_t *place = desc.data();
904 if (desc.size() < 8)
905 reportFatal(place, "program property is too short");
906 uint32_t type = read32<ELFT::TargetEndianness>(desc.data());
907 uint32_t size = read32<ELFT::TargetEndianness>(desc.data() + 4);
908 desc = desc.slice(8);
909 if (desc.size() < size)
910 reportFatal(place, "program property is too short");
912 if (type == featureAndType) {
913 // We found a FEATURE_1_AND field. There may be more than one of these
914 // in a .note.gnu.property section, for a relocatable object we
915 // accumulate the bits set.
916 if (size < 4)
917 reportFatal(place, "FEATURE_1_AND entry is too short");
918 featuresSet |= read32<ELFT::TargetEndianness>(desc.data());
921 // Padding is present in the note descriptor, if necessary.
922 desc = desc.slice(alignTo<(ELFT::Is64Bits ? 8 : 4)>(size));
925 // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
926 data = data.slice(nhdr->getSize());
929 return featuresSet;
932 template <class ELFT>
933 InputSectionBase *ObjFile<ELFT>::getRelocTarget(uint32_t idx,
934 const Elf_Shdr &sec,
935 uint32_t info) {
936 if (info < this->sections.size()) {
937 InputSectionBase *target = this->sections[info];
939 // Strictly speaking, a relocation section must be included in the
940 // group of the section it relocates. However, LLVM 3.3 and earlier
941 // would fail to do so, so we gracefully handle that case.
942 if (target == &InputSection::discarded)
943 return nullptr;
945 if (target != nullptr)
946 return target;
949 error(toString(this) + Twine(": relocation section (index ") + Twine(idx) +
950 ") has invalid sh_info (" + Twine(info) + ")");
951 return nullptr;
954 // The function may be called concurrently for different input files. For
955 // allocation, prefer makeThreadLocal which does not require holding a lock.
956 template <class ELFT>
957 InputSectionBase *ObjFile<ELFT>::createInputSection(uint32_t idx,
958 const Elf_Shdr &sec,
959 StringRef name) {
960 if (name.startswith(".n")) {
961 // The GNU linker uses .note.GNU-stack section as a marker indicating
962 // that the code in the object file does not expect that the stack is
963 // executable (in terms of NX bit). If all input files have the marker,
964 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
965 // make the stack non-executable. Most object files have this section as
966 // of 2017.
968 // But making the stack non-executable is a norm today for security
969 // reasons. Failure to do so may result in a serious security issue.
970 // Therefore, we make LLD always add PT_GNU_STACK unless it is
971 // explicitly told to do otherwise (by -z execstack). Because the stack
972 // executable-ness is controlled solely by command line options,
973 // .note.GNU-stack sections are simply ignored.
974 if (name == ".note.GNU-stack")
975 return &InputSection::discarded;
977 // Object files that use processor features such as Intel Control-Flow
978 // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
979 // .note.gnu.property section containing a bitfield of feature bits like the
980 // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
982 // Since we merge bitmaps from multiple object files to create a new
983 // .note.gnu.property containing a single AND'ed bitmap, we discard an input
984 // file's .note.gnu.property section.
985 if (name == ".note.gnu.property") {
986 this->andFeatures = readAndFeatures<ELFT>(InputSection(*this, sec, name));
987 return &InputSection::discarded;
990 // Split stacks is a feature to support a discontiguous stack,
991 // commonly used in the programming language Go. For the details,
992 // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
993 // for split stack will include a .note.GNU-split-stack section.
994 if (name == ".note.GNU-split-stack") {
995 if (config->relocatable) {
996 error(
997 "cannot mix split-stack and non-split-stack in a relocatable link");
998 return &InputSection::discarded;
1000 this->splitStack = true;
1001 return &InputSection::discarded;
1004 // An object file compiled for split stack, but where some of the
1005 // functions were compiled with the no_split_stack_attribute will
1006 // include a .note.GNU-no-split-stack section.
1007 if (name == ".note.GNU-no-split-stack") {
1008 this->someNoSplitStack = true;
1009 return &InputSection::discarded;
1012 // Strip existing .note.gnu.build-id sections so that the output won't have
1013 // more than one build-id. This is not usually a problem because input
1014 // object files normally don't have .build-id sections, but you can create
1015 // such files by "ld.{bfd,gold,lld} -r --build-id", and we want to guard
1016 // against it.
1017 if (name == ".note.gnu.build-id")
1018 return &InputSection::discarded;
1021 // The linker merges EH (exception handling) frames and creates a
1022 // .eh_frame_hdr section for runtime. So we handle them with a special
1023 // class. For relocatable outputs, they are just passed through.
1024 if (name == ".eh_frame" && !config->relocatable)
1025 return makeThreadLocal<EhInputSection>(*this, sec, name);
1027 if ((sec.sh_flags & SHF_MERGE) && shouldMerge(sec, name))
1028 return makeThreadLocal<MergeInputSection>(*this, sec, name);
1029 return makeThreadLocal<InputSection>(*this, sec, name);
1032 // Initialize this->Symbols. this->Symbols is a parallel array as
1033 // its corresponding ELF symbol table.
1034 template <class ELFT>
1035 void ObjFile<ELFT>::initializeSymbols(const object::ELFFile<ELFT> &obj) {
1036 SymbolTable &symtab = *elf::symtab;
1038 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1039 symbols.resize(eSyms.size());
1041 // Some entries have been filled by LazyObjFile.
1042 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
1043 if (!symbols[i])
1044 symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this));
1046 // Perform symbol resolution on non-local symbols.
1047 SmallVector<unsigned, 32> undefineds;
1048 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1049 const Elf_Sym &eSym = eSyms[i];
1050 uint32_t secIdx = eSym.st_shndx;
1051 if (secIdx == SHN_UNDEF) {
1052 undefineds.push_back(i);
1053 continue;
1056 uint8_t binding = eSym.getBinding();
1057 uint8_t stOther = eSym.st_other;
1058 uint8_t type = eSym.getType();
1059 uint64_t value = eSym.st_value;
1060 uint64_t size = eSym.st_size;
1062 Symbol *sym = symbols[i];
1063 sym->isUsedInRegularObj = true;
1064 if (LLVM_UNLIKELY(eSym.st_shndx == SHN_COMMON)) {
1065 if (value == 0 || value >= UINT32_MAX)
1066 fatal(toString(this) + ": common symbol '" + sym->getName() +
1067 "' has invalid alignment: " + Twine(value));
1068 hasCommonSyms = true;
1069 sym->resolve(
1070 CommonSymbol{this, StringRef(), binding, stOther, type, value, size});
1071 continue;
1074 // Handle global defined symbols. Defined::section will be set in postParse.
1075 sym->resolve(Defined{this, StringRef(), binding, stOther, type, value, size,
1076 nullptr});
1079 // Undefined symbols (excluding those defined relative to non-prevailing
1080 // sections) can trigger recursive extract. Process defined symbols first so
1081 // that the relative order between a defined symbol and an undefined symbol
1082 // does not change the symbol resolution behavior. In addition, a set of
1083 // interconnected symbols will all be resolved to the same file, instead of
1084 // being resolved to different files.
1085 for (unsigned i : undefineds) {
1086 const Elf_Sym &eSym = eSyms[i];
1087 Symbol *sym = symbols[i];
1088 sym->resolve(Undefined{this, StringRef(), eSym.getBinding(), eSym.st_other,
1089 eSym.getType()});
1090 sym->isUsedInRegularObj = true;
1091 sym->referenced = true;
1095 template <class ELFT>
1096 void ObjFile<ELFT>::initSectionsAndLocalSyms(bool ignoreComdats) {
1097 if (!justSymbols)
1098 initializeSections(ignoreComdats, getObj());
1100 if (!firstGlobal)
1101 return;
1102 SymbolUnion *locals = makeThreadLocalN<SymbolUnion>(firstGlobal);
1104 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1105 for (size_t i = 0, end = firstGlobal; i != end; ++i) {
1106 const Elf_Sym &eSym = eSyms[i];
1107 uint32_t secIdx = eSym.st_shndx;
1108 if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
1109 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
1110 else if (secIdx >= SHN_LORESERVE)
1111 secIdx = 0;
1112 if (LLVM_UNLIKELY(secIdx >= sections.size()))
1113 fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1114 if (LLVM_UNLIKELY(eSym.getBinding() != STB_LOCAL))
1115 error(toString(this) + ": non-local symbol (" + Twine(i) +
1116 ") found at index < .symtab's sh_info (" + Twine(end) + ")");
1118 InputSectionBase *sec = sections[secIdx];
1119 uint8_t type = eSym.getType();
1120 if (type == STT_FILE)
1121 sourceFile = CHECK(eSym.getName(stringTable), this);
1122 if (LLVM_UNLIKELY(stringTable.size() <= eSym.st_name))
1123 fatal(toString(this) + ": invalid symbol name offset");
1124 StringRef name(stringTable.data() + eSym.st_name);
1126 symbols[i] = reinterpret_cast<Symbol *>(locals + i);
1127 if (eSym.st_shndx == SHN_UNDEF || sec == &InputSection::discarded)
1128 new (symbols[i]) Undefined(this, name, STB_LOCAL, eSym.st_other, type,
1129 /*discardedSecIdx=*/secIdx);
1130 else
1131 new (symbols[i]) Defined(this, name, STB_LOCAL, eSym.st_other, type,
1132 eSym.st_value, eSym.st_size, sec);
1133 symbols[i]->isUsedInRegularObj = true;
1137 // Called after all ObjFile::parse is called for all ObjFiles. This checks
1138 // duplicate symbols and may do symbol property merge in the future.
1139 template <class ELFT> void ObjFile<ELFT>::postParse() {
1140 static std::mutex mu;
1141 ArrayRef<Elf_Sym> eSyms = this->getELFSyms<ELFT>();
1142 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i) {
1143 const Elf_Sym &eSym = eSyms[i];
1144 Symbol &sym = *symbols[i];
1145 uint32_t secIdx = eSym.st_shndx;
1146 uint8_t binding = eSym.getBinding();
1147 if (LLVM_UNLIKELY(binding != STB_GLOBAL && binding != STB_WEAK &&
1148 binding != STB_GNU_UNIQUE))
1149 errorOrWarn(toString(this) + ": symbol (" + Twine(i) +
1150 ") has invalid binding: " + Twine((int)binding));
1152 // st_value of STT_TLS represents the assigned offset, not the actual
1153 // address which is used by STT_FUNC and STT_OBJECT. STT_TLS symbols can
1154 // only be referenced by special TLS relocations. It is usually an error if
1155 // a STT_TLS symbol is replaced by a non-STT_TLS symbol, vice versa.
1156 if (LLVM_UNLIKELY(sym.isTls()) && eSym.getType() != STT_TLS &&
1157 eSym.getType() != STT_NOTYPE)
1158 errorOrWarn("TLS attribute mismatch: " + toString(sym) + "\n>>> in " +
1159 toString(sym.file) + "\n>>> in " + toString(this));
1161 // Handle non-COMMON defined symbol below. !sym.file allows a symbol
1162 // assignment to redefine a symbol without an error.
1163 if (!sym.file || !sym.isDefined() || secIdx == SHN_UNDEF ||
1164 secIdx == SHN_COMMON)
1165 continue;
1167 if (LLVM_UNLIKELY(secIdx == SHN_XINDEX))
1168 secIdx = check(getExtendedSymbolTableIndex<ELFT>(eSym, i, shndxTable));
1169 else if (secIdx >= SHN_LORESERVE)
1170 secIdx = 0;
1171 if (LLVM_UNLIKELY(secIdx >= sections.size()))
1172 fatal(toString(this) + ": invalid section index: " + Twine(secIdx));
1173 InputSectionBase *sec = sections[secIdx];
1174 if (sec == &InputSection::discarded) {
1175 if (sym.traced) {
1176 printTraceSymbol(Undefined{this, sym.getName(), sym.binding,
1177 sym.stOther, sym.type, secIdx},
1178 sym.getName());
1180 if (sym.file == this) {
1181 std::lock_guard<std::mutex> lock(mu);
1182 ctx->nonPrevailingSyms.emplace_back(&sym, secIdx);
1184 continue;
1187 if (sym.file == this) {
1188 cast<Defined>(sym).section = sec;
1189 continue;
1192 if (binding == STB_WEAK)
1193 continue;
1194 std::lock_guard<std::mutex> lock(mu);
1195 ctx->duplicates.push_back({&sym, this, sec, eSym.st_value});
1199 // The handling of tentative definitions (COMMON symbols) in archives is murky.
1200 // A tentative definition will be promoted to a global definition if there are
1201 // no non-tentative definitions to dominate it. When we hold a tentative
1202 // definition to a symbol and are inspecting archive members for inclusion
1203 // there are 2 ways we can proceed:
1205 // 1) Consider the tentative definition a 'real' definition (ie promotion from
1206 // tentative to real definition has already happened) and not inspect
1207 // archive members for Global/Weak definitions to replace the tentative
1208 // definition. An archive member would only be included if it satisfies some
1209 // other undefined symbol. This is the behavior Gold uses.
1211 // 2) Consider the tentative definition as still undefined (ie the promotion to
1212 // a real definition happens only after all symbol resolution is done).
1213 // The linker searches archive members for STB_GLOBAL definitions to
1214 // replace the tentative definition with. This is the behavior used by
1215 // GNU ld.
1217 // The second behavior is inherited from SysVR4, which based it on the FORTRAN
1218 // COMMON BLOCK model. This behavior is needed for proper initialization in old
1219 // (pre F90) FORTRAN code that is packaged into an archive.
1221 // The following functions search archive members for definitions to replace
1222 // tentative definitions (implementing behavior 2).
1223 static bool isBitcodeNonCommonDef(MemoryBufferRef mb, StringRef symName,
1224 StringRef archiveName) {
1225 IRSymtabFile symtabFile = check(readIRSymtab(mb));
1226 for (const irsymtab::Reader::SymbolRef &sym :
1227 symtabFile.TheReader.symbols()) {
1228 if (sym.isGlobal() && sym.getName() == symName)
1229 return !sym.isUndefined() && !sym.isWeak() && !sym.isCommon();
1231 return false;
1234 template <class ELFT>
1235 static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName,
1236 StringRef archiveName) {
1237 ObjFile<ELFT> *obj = make<ObjFile<ELFT>>(mb, archiveName);
1238 StringRef stringtable = obj->getStringTable();
1240 for (auto sym : obj->template getGlobalELFSyms<ELFT>()) {
1241 Expected<StringRef> name = sym.getName(stringtable);
1242 if (name && name.get() == symName)
1243 return sym.isDefined() && sym.getBinding() == STB_GLOBAL &&
1244 !sym.isCommon();
1246 return false;
1249 static bool isNonCommonDef(MemoryBufferRef mb, StringRef symName,
1250 StringRef archiveName) {
1251 switch (getELFKind(mb, archiveName)) {
1252 case ELF32LEKind:
1253 return isNonCommonDef<ELF32LE>(mb, symName, archiveName);
1254 case ELF32BEKind:
1255 return isNonCommonDef<ELF32BE>(mb, symName, archiveName);
1256 case ELF64LEKind:
1257 return isNonCommonDef<ELF64LE>(mb, symName, archiveName);
1258 case ELF64BEKind:
1259 return isNonCommonDef<ELF64BE>(mb, symName, archiveName);
1260 default:
1261 llvm_unreachable("getELFKind");
1265 unsigned SharedFile::vernauxNum;
1267 // Parse the version definitions in the object file if present, and return a
1268 // vector whose nth element contains a pointer to the Elf_Verdef for version
1269 // identifier n. Version identifiers that are not definitions map to nullptr.
1270 template <typename ELFT>
1271 static SmallVector<const void *, 0>
1272 parseVerdefs(const uint8_t *base, const typename ELFT::Shdr *sec) {
1273 if (!sec)
1274 return {};
1276 // Build the Verdefs array by following the chain of Elf_Verdef objects
1277 // from the start of the .gnu.version_d section.
1278 SmallVector<const void *, 0> verdefs;
1279 const uint8_t *verdef = base + sec->sh_offset;
1280 for (unsigned i = 0, e = sec->sh_info; i != e; ++i) {
1281 auto *curVerdef = reinterpret_cast<const typename ELFT::Verdef *>(verdef);
1282 verdef += curVerdef->vd_next;
1283 unsigned verdefIndex = curVerdef->vd_ndx;
1284 if (verdefIndex >= verdefs.size())
1285 verdefs.resize(verdefIndex + 1);
1286 verdefs[verdefIndex] = curVerdef;
1288 return verdefs;
1291 // Parse SHT_GNU_verneed to properly set the name of a versioned undefined
1292 // symbol. We detect fatal issues which would cause vulnerabilities, but do not
1293 // implement sophisticated error checking like in llvm-readobj because the value
1294 // of such diagnostics is low.
1295 template <typename ELFT>
1296 std::vector<uint32_t> SharedFile::parseVerneed(const ELFFile<ELFT> &obj,
1297 const typename ELFT::Shdr *sec) {
1298 if (!sec)
1299 return {};
1300 std::vector<uint32_t> verneeds;
1301 ArrayRef<uint8_t> data = CHECK(obj.getSectionContents(*sec), this);
1302 const uint8_t *verneedBuf = data.begin();
1303 for (unsigned i = 0; i != sec->sh_info; ++i) {
1304 if (verneedBuf + sizeof(typename ELFT::Verneed) > data.end())
1305 fatal(toString(this) + " has an invalid Verneed");
1306 auto *vn = reinterpret_cast<const typename ELFT::Verneed *>(verneedBuf);
1307 const uint8_t *vernauxBuf = verneedBuf + vn->vn_aux;
1308 for (unsigned j = 0; j != vn->vn_cnt; ++j) {
1309 if (vernauxBuf + sizeof(typename ELFT::Vernaux) > data.end())
1310 fatal(toString(this) + " has an invalid Vernaux");
1311 auto *aux = reinterpret_cast<const typename ELFT::Vernaux *>(vernauxBuf);
1312 if (aux->vna_name >= this->stringTable.size())
1313 fatal(toString(this) + " has a Vernaux with an invalid vna_name");
1314 uint16_t version = aux->vna_other & VERSYM_VERSION;
1315 if (version >= verneeds.size())
1316 verneeds.resize(version + 1);
1317 verneeds[version] = aux->vna_name;
1318 vernauxBuf += aux->vna_next;
1320 verneedBuf += vn->vn_next;
1322 return verneeds;
1325 // We do not usually care about alignments of data in shared object
1326 // files because the loader takes care of it. However, if we promote a
1327 // DSO symbol to point to .bss due to copy relocation, we need to keep
1328 // the original alignment requirements. We infer it in this function.
1329 template <typename ELFT>
1330 static uint64_t getAlignment(ArrayRef<typename ELFT::Shdr> sections,
1331 const typename ELFT::Sym &sym) {
1332 uint64_t ret = UINT64_MAX;
1333 if (sym.st_value)
1334 ret = 1ULL << countTrailingZeros((uint64_t)sym.st_value);
1335 if (0 < sym.st_shndx && sym.st_shndx < sections.size())
1336 ret = std::min<uint64_t>(ret, sections[sym.st_shndx].sh_addralign);
1337 return (ret > UINT32_MAX) ? 0 : ret;
1340 // Fully parse the shared object file.
1342 // This function parses symbol versions. If a DSO has version information,
1343 // the file has a ".gnu.version_d" section which contains symbol version
1344 // definitions. Each symbol is associated to one version through a table in
1345 // ".gnu.version" section. That table is a parallel array for the symbol
1346 // table, and each table entry contains an index in ".gnu.version_d".
1348 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
1349 // VER_NDX_GLOBAL. There's no table entry for these special versions in
1350 // ".gnu.version_d".
1352 // The file format for symbol versioning is perhaps a bit more complicated
1353 // than necessary, but you can easily understand the code if you wrap your
1354 // head around the data structure described above.
1355 template <class ELFT> void SharedFile::parse() {
1356 using Elf_Dyn = typename ELFT::Dyn;
1357 using Elf_Shdr = typename ELFT::Shdr;
1358 using Elf_Sym = typename ELFT::Sym;
1359 using Elf_Verdef = typename ELFT::Verdef;
1360 using Elf_Versym = typename ELFT::Versym;
1362 ArrayRef<Elf_Dyn> dynamicTags;
1363 const ELFFile<ELFT> obj = this->getObj<ELFT>();
1364 ArrayRef<Elf_Shdr> sections = getELFShdrs<ELFT>();
1366 const Elf_Shdr *versymSec = nullptr;
1367 const Elf_Shdr *verdefSec = nullptr;
1368 const Elf_Shdr *verneedSec = nullptr;
1370 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1371 for (const Elf_Shdr &sec : sections) {
1372 switch (sec.sh_type) {
1373 default:
1374 continue;
1375 case SHT_DYNAMIC:
1376 dynamicTags =
1377 CHECK(obj.template getSectionContentsAsArray<Elf_Dyn>(sec), this);
1378 break;
1379 case SHT_GNU_versym:
1380 versymSec = &sec;
1381 break;
1382 case SHT_GNU_verdef:
1383 verdefSec = &sec;
1384 break;
1385 case SHT_GNU_verneed:
1386 verneedSec = &sec;
1387 break;
1391 if (versymSec && numELFSyms == 0) {
1392 error("SHT_GNU_versym should be associated with symbol table");
1393 return;
1396 // Search for a DT_SONAME tag to initialize this->soName.
1397 for (const Elf_Dyn &dyn : dynamicTags) {
1398 if (dyn.d_tag == DT_NEEDED) {
1399 uint64_t val = dyn.getVal();
1400 if (val >= this->stringTable.size())
1401 fatal(toString(this) + ": invalid DT_NEEDED entry");
1402 dtNeeded.push_back(this->stringTable.data() + val);
1403 } else if (dyn.d_tag == DT_SONAME) {
1404 uint64_t val = dyn.getVal();
1405 if (val >= this->stringTable.size())
1406 fatal(toString(this) + ": invalid DT_SONAME entry");
1407 soName = this->stringTable.data() + val;
1411 // DSOs are uniquified not by filename but by soname.
1412 DenseMap<CachedHashStringRef, SharedFile *>::iterator it;
1413 bool wasInserted;
1414 std::tie(it, wasInserted) =
1415 symtab->soNames.try_emplace(CachedHashStringRef(soName), this);
1417 // If a DSO appears more than once on the command line with and without
1418 // --as-needed, --no-as-needed takes precedence over --as-needed because a
1419 // user can add an extra DSO with --no-as-needed to force it to be added to
1420 // the dependency list.
1421 it->second->isNeeded |= isNeeded;
1422 if (!wasInserted)
1423 return;
1425 ctx->sharedFiles.push_back(this);
1427 verdefs = parseVerdefs<ELFT>(obj.base(), verdefSec);
1428 std::vector<uint32_t> verneeds = parseVerneed<ELFT>(obj, verneedSec);
1430 // Parse ".gnu.version" section which is a parallel array for the symbol
1431 // table. If a given file doesn't have a ".gnu.version" section, we use
1432 // VER_NDX_GLOBAL.
1433 size_t size = numELFSyms - firstGlobal;
1434 std::vector<uint16_t> versyms(size, VER_NDX_GLOBAL);
1435 if (versymSec) {
1436 ArrayRef<Elf_Versym> versym =
1437 CHECK(obj.template getSectionContentsAsArray<Elf_Versym>(*versymSec),
1438 this)
1439 .slice(firstGlobal);
1440 for (size_t i = 0; i < size; ++i)
1441 versyms[i] = versym[i].vs_index;
1444 // System libraries can have a lot of symbols with versions. Using a
1445 // fixed buffer for computing the versions name (foo@ver) can save a
1446 // lot of allocations.
1447 SmallString<0> versionedNameBuffer;
1449 // Add symbols to the symbol table.
1450 SymbolTable &symtab = *elf::symtab;
1451 ArrayRef<Elf_Sym> syms = this->getGlobalELFSyms<ELFT>();
1452 for (size_t i = 0, e = syms.size(); i != e; ++i) {
1453 const Elf_Sym &sym = syms[i];
1455 // ELF spec requires that all local symbols precede weak or global
1456 // symbols in each symbol table, and the index of first non-local symbol
1457 // is stored to sh_info. If a local symbol appears after some non-local
1458 // symbol, that's a violation of the spec.
1459 StringRef name = CHECK(sym.getName(stringTable), this);
1460 if (sym.getBinding() == STB_LOCAL) {
1461 warn("found local symbol '" + name +
1462 "' in global part of symbol table in file " + toString(this));
1463 continue;
1466 uint16_t idx = versyms[i] & ~VERSYM_HIDDEN;
1467 if (sym.isUndefined()) {
1468 // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but
1469 // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL.
1470 if (idx != VER_NDX_LOCAL && idx != VER_NDX_GLOBAL) {
1471 if (idx >= verneeds.size()) {
1472 error("corrupt input file: version need index " + Twine(idx) +
1473 " for symbol " + name + " is out of bounds\n>>> defined in " +
1474 toString(this));
1475 continue;
1477 StringRef verName = stringTable.data() + verneeds[idx];
1478 versionedNameBuffer.clear();
1479 name = saver().save(
1480 (name + "@" + verName).toStringRef(versionedNameBuffer));
1482 Symbol *s = symtab.addSymbol(
1483 Undefined{this, name, sym.getBinding(), sym.st_other, sym.getType()});
1484 s->exportDynamic = true;
1485 if (s->isUndefined() && sym.getBinding() != STB_WEAK &&
1486 config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore)
1487 requiredSymbols.push_back(s);
1488 continue;
1491 // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
1492 // assigns VER_NDX_LOCAL to this section global symbol. Here is a
1493 // workaround for this bug.
1494 if (config->emachine == EM_MIPS && idx == VER_NDX_LOCAL &&
1495 name == "_gp_disp")
1496 continue;
1498 uint32_t alignment = getAlignment<ELFT>(sections, sym);
1499 if (!(versyms[i] & VERSYM_HIDDEN)) {
1500 auto *s = symtab.addSymbol(
1501 SharedSymbol{*this, name, sym.getBinding(), sym.st_other,
1502 sym.getType(), sym.st_value, sym.st_size, alignment});
1503 if (s->file == this)
1504 s->verdefIndex = idx;
1507 // Also add the symbol with the versioned name to handle undefined symbols
1508 // with explicit versions.
1509 if (idx == VER_NDX_GLOBAL)
1510 continue;
1512 if (idx >= verdefs.size() || idx == VER_NDX_LOCAL) {
1513 error("corrupt input file: version definition index " + Twine(idx) +
1514 " for symbol " + name + " is out of bounds\n>>> defined in " +
1515 toString(this));
1516 continue;
1519 StringRef verName =
1520 stringTable.data() +
1521 reinterpret_cast<const Elf_Verdef *>(verdefs[idx])->getAux()->vda_name;
1522 versionedNameBuffer.clear();
1523 name = (name + "@" + verName).toStringRef(versionedNameBuffer);
1524 auto *s = symtab.addSymbol(
1525 SharedSymbol{*this, saver().save(name), sym.getBinding(), sym.st_other,
1526 sym.getType(), sym.st_value, sym.st_size, alignment});
1527 if (s->file == this)
1528 s->verdefIndex = idx;
1532 static ELFKind getBitcodeELFKind(const Triple &t) {
1533 if (t.isLittleEndian())
1534 return t.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
1535 return t.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
1538 static uint16_t getBitcodeMachineKind(StringRef path, const Triple &t) {
1539 switch (t.getArch()) {
1540 case Triple::aarch64:
1541 case Triple::aarch64_be:
1542 return EM_AARCH64;
1543 case Triple::amdgcn:
1544 case Triple::r600:
1545 return EM_AMDGPU;
1546 case Triple::arm:
1547 case Triple::thumb:
1548 return EM_ARM;
1549 case Triple::avr:
1550 return EM_AVR;
1551 case Triple::hexagon:
1552 return EM_HEXAGON;
1553 case Triple::mips:
1554 case Triple::mipsel:
1555 case Triple::mips64:
1556 case Triple::mips64el:
1557 return EM_MIPS;
1558 case Triple::msp430:
1559 return EM_MSP430;
1560 case Triple::ppc:
1561 case Triple::ppcle:
1562 return EM_PPC;
1563 case Triple::ppc64:
1564 case Triple::ppc64le:
1565 return EM_PPC64;
1566 case Triple::riscv32:
1567 case Triple::riscv64:
1568 return EM_RISCV;
1569 case Triple::x86:
1570 return t.isOSIAMCU() ? EM_IAMCU : EM_386;
1571 case Triple::x86_64:
1572 return EM_X86_64;
1573 default:
1574 error(path + ": could not infer e_machine from bitcode target triple " +
1575 t.str());
1576 return EM_NONE;
1580 static uint8_t getOsAbi(const Triple &t) {
1581 switch (t.getOS()) {
1582 case Triple::AMDHSA:
1583 return ELF::ELFOSABI_AMDGPU_HSA;
1584 case Triple::AMDPAL:
1585 return ELF::ELFOSABI_AMDGPU_PAL;
1586 case Triple::Mesa3D:
1587 return ELF::ELFOSABI_AMDGPU_MESA3D;
1588 default:
1589 return ELF::ELFOSABI_NONE;
1593 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
1594 uint64_t offsetInArchive, bool lazy)
1595 : InputFile(BitcodeKind, mb) {
1596 this->archiveName = archiveName;
1597 this->lazy = lazy;
1599 std::string path = mb.getBufferIdentifier().str();
1600 if (config->thinLTOIndexOnly)
1601 path = replaceThinLTOSuffix(mb.getBufferIdentifier());
1603 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1604 // name. If two archives define two members with the same name, this
1605 // causes a collision which result in only one of the objects being taken
1606 // into consideration at LTO time (which very likely causes undefined
1607 // symbols later in the link stage). So we append file offset to make
1608 // filename unique.
1609 StringRef name = archiveName.empty()
1610 ? saver().save(path)
1611 : saver().save(archiveName + "(" + path::filename(path) +
1612 " at " + utostr(offsetInArchive) + ")");
1613 MemoryBufferRef mbref(mb.getBuffer(), name);
1615 obj = CHECK(lto::InputFile::create(mbref), this);
1617 Triple t(obj->getTargetTriple());
1618 ekind = getBitcodeELFKind(t);
1619 emachine = getBitcodeMachineKind(mb.getBufferIdentifier(), t);
1620 osabi = getOsAbi(t);
1623 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
1624 switch (gvVisibility) {
1625 case GlobalValue::DefaultVisibility:
1626 return STV_DEFAULT;
1627 case GlobalValue::HiddenVisibility:
1628 return STV_HIDDEN;
1629 case GlobalValue::ProtectedVisibility:
1630 return STV_PROTECTED;
1632 llvm_unreachable("unknown visibility");
1635 template <class ELFT>
1636 static void
1637 createBitcodeSymbol(Symbol *&sym, const std::vector<bool> &keptComdats,
1638 const lto::InputFile::Symbol &objSym, BitcodeFile &f) {
1639 uint8_t binding = objSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1640 uint8_t type = objSym.isTLS() ? STT_TLS : STT_NOTYPE;
1641 uint8_t visibility = mapVisibility(objSym.getVisibility());
1643 if (!sym)
1644 sym = symtab->insert(saver().save(objSym.getName()));
1646 int c = objSym.getComdatIndex();
1647 if (objSym.isUndefined() || (c != -1 && !keptComdats[c])) {
1648 Undefined newSym(&f, StringRef(), binding, visibility, type);
1649 sym->resolve(newSym);
1650 sym->referenced = true;
1651 return;
1654 if (objSym.isCommon()) {
1655 sym->resolve(CommonSymbol{&f, StringRef(), binding, visibility, STT_OBJECT,
1656 objSym.getCommonAlignment(),
1657 objSym.getCommonSize()});
1658 } else {
1659 Defined newSym(&f, StringRef(), binding, visibility, type, 0, 0, nullptr);
1660 if (objSym.canBeOmittedFromSymbolTable())
1661 newSym.exportDynamic = false;
1662 sym->resolve(newSym);
1666 template <class ELFT> void BitcodeFile::parse() {
1667 for (std::pair<StringRef, Comdat::SelectionKind> s : obj->getComdatTable()) {
1668 keptComdats.push_back(
1669 s.second == Comdat::NoDeduplicate ||
1670 symtab->comdatGroups.try_emplace(CachedHashStringRef(s.first), this)
1671 .second);
1674 symbols.resize(obj->symbols().size());
1675 // Process defined symbols first. See the comment in
1676 // ObjFile<ELFT>::initializeSymbols.
1677 for (auto it : llvm::enumerate(obj->symbols()))
1678 if (!it.value().isUndefined()) {
1679 Symbol *&sym = symbols[it.index()];
1680 createBitcodeSymbol<ELFT>(sym, keptComdats, it.value(), *this);
1682 for (auto it : llvm::enumerate(obj->symbols()))
1683 if (it.value().isUndefined()) {
1684 Symbol *&sym = symbols[it.index()];
1685 createBitcodeSymbol<ELFT>(sym, keptComdats, it.value(), *this);
1688 for (auto l : obj->getDependentLibraries())
1689 addDependentLibrary(l, this);
1692 void BitcodeFile::parseLazy() {
1693 SymbolTable &symtab = *elf::symtab;
1694 symbols.resize(obj->symbols().size());
1695 for (auto it : llvm::enumerate(obj->symbols()))
1696 if (!it.value().isUndefined()) {
1697 auto *sym = symtab.insert(saver().save(it.value().getName()));
1698 sym->resolve(LazyObject{*this});
1699 symbols[it.index()] = sym;
1703 void BitcodeFile::postParse() {
1704 for (auto it : llvm::enumerate(obj->symbols())) {
1705 const Symbol &sym = *symbols[it.index()];
1706 const auto &objSym = it.value();
1707 if (sym.file == this || !sym.isDefined() || objSym.isUndefined() ||
1708 objSym.isCommon() || objSym.isWeak())
1709 continue;
1710 int c = objSym.getComdatIndex();
1711 if (c != -1 && !keptComdats[c])
1712 continue;
1713 reportDuplicate(sym, this, nullptr, 0);
1717 void BinaryFile::parse() {
1718 ArrayRef<uint8_t> data = arrayRefFromStringRef(mb.getBuffer());
1719 auto *section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1720 8, data, ".data");
1721 sections.push_back(section);
1723 // For each input file foo that is embedded to a result as a binary
1724 // blob, we define _binary_foo_{start,end,size} symbols, so that
1725 // user programs can access blobs by name. Non-alphanumeric
1726 // characters in a filename are replaced with underscore.
1727 std::string s = "_binary_" + mb.getBufferIdentifier().str();
1728 for (size_t i = 0; i < s.size(); ++i)
1729 if (!isAlnum(s[i]))
1730 s[i] = '_';
1732 llvm::StringSaver &saver = lld::saver();
1734 symtab->addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_start"),
1735 STB_GLOBAL, STV_DEFAULT, STT_OBJECT, 0,
1736 0, section});
1737 symtab->addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_end"),
1738 STB_GLOBAL, STV_DEFAULT, STT_OBJECT,
1739 data.size(), 0, section});
1740 symtab->addAndCheckDuplicate(Defined{nullptr, saver.save(s + "_size"),
1741 STB_GLOBAL, STV_DEFAULT, STT_OBJECT,
1742 data.size(), 0, nullptr});
1745 ELFFileBase *elf::createObjFile(MemoryBufferRef mb, StringRef archiveName,
1746 bool lazy) {
1747 ELFFileBase *f;
1748 switch (getELFKind(mb, archiveName)) {
1749 case ELF32LEKind:
1750 f = make<ObjFile<ELF32LE>>(mb, archiveName);
1751 break;
1752 case ELF32BEKind:
1753 f = make<ObjFile<ELF32BE>>(mb, archiveName);
1754 break;
1755 case ELF64LEKind:
1756 f = make<ObjFile<ELF64LE>>(mb, archiveName);
1757 break;
1758 case ELF64BEKind:
1759 f = make<ObjFile<ELF64BE>>(mb, archiveName);
1760 break;
1761 default:
1762 llvm_unreachable("getELFKind");
1764 f->lazy = lazy;
1765 return f;
1768 template <class ELFT> void ObjFile<ELFT>::parseLazy() {
1769 const ArrayRef<typename ELFT::Sym> eSyms = this->getELFSyms<ELFT>();
1770 SymbolTable &symtab = *elf::symtab;
1772 symbols.resize(eSyms.size());
1773 for (size_t i = firstGlobal, end = eSyms.size(); i != end; ++i)
1774 if (eSyms[i].st_shndx != SHN_UNDEF)
1775 symbols[i] = symtab.insert(CHECK(eSyms[i].getName(stringTable), this));
1777 // Replace existing symbols with LazyObject symbols.
1779 // resolve() may trigger this->extract() if an existing symbol is an undefined
1780 // symbol. If that happens, this function has served its purpose, and we can
1781 // exit from the loop early.
1782 for (Symbol *sym : makeArrayRef(symbols).slice(firstGlobal))
1783 if (sym) {
1784 sym->resolve(LazyObject{*this});
1785 if (!lazy)
1786 return;
1790 bool InputFile::shouldExtractForCommon(StringRef name) {
1791 if (isa<BitcodeFile>(this))
1792 return isBitcodeNonCommonDef(mb, name, archiveName);
1794 return isNonCommonDef(mb, name, archiveName);
1797 std::string elf::replaceThinLTOSuffix(StringRef path) {
1798 StringRef suffix = config->thinLTOObjectSuffixReplace.first;
1799 StringRef repl = config->thinLTOObjectSuffixReplace.second;
1801 if (path.consume_back(suffix))
1802 return (path + repl).str();
1803 return std::string(path);
1806 template void BitcodeFile::parse<ELF32LE>();
1807 template void BitcodeFile::parse<ELF32BE>();
1808 template void BitcodeFile::parse<ELF64LE>();
1809 template void BitcodeFile::parse<ELF64BE>();
1811 template class elf::ObjFile<ELF32LE>;
1812 template class elf::ObjFile<ELF32BE>;
1813 template class elf::ObjFile<ELF64LE>;
1814 template class elf::ObjFile<ELF64BE>;
1816 template void SharedFile::parse<ELF32LE>();
1817 template void SharedFile::parse<ELF32BE>();
1818 template void SharedFile::parse<ELF64LE>();
1819 template void SharedFile::parse<ELF64BE>();