1 //===- InputFiles.cpp -----------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "InputFiles.h"
13 #include "InputSection.h"
14 #include "LinkerScript.h"
15 #include "SymbolTable.h"
17 #include "SyntheticSections.h"
19 #include "lld/Common/CommonLinkerContext.h"
20 #include "lld/Common/DWARF.h"
21 #include "llvm/ADT/CachedHashString.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/Object/IRObjectFile.h"
25 #include "llvm/Support/ARMAttributeParser.h"
26 #include "llvm/Support/ARMBuildAttributes.h"
27 #include "llvm/Support/Endian.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/RISCVAttributeParser.h"
31 #include "llvm/Support/TimeProfiler.h"
32 #include "llvm/Support/raw_ostream.h"
36 using namespace llvm::ELF
;
37 using namespace llvm::object
;
38 using namespace llvm::sys
;
39 using namespace llvm::sys::fs
;
40 using namespace llvm::support::endian
;
42 using namespace lld::elf
;
44 // This function is explicitly instantiated in ARM.cpp, don't do it here to
45 // avoid warnings with MSVC.
46 extern template void ObjFile
<ELF32LE
>::importCmseSymbols();
47 extern template void ObjFile
<ELF32BE
>::importCmseSymbols();
48 extern template void ObjFile
<ELF64LE
>::importCmseSymbols();
49 extern template void ObjFile
<ELF64BE
>::importCmseSymbols();
51 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
52 std::string
elf::toStr(Ctx
&ctx
, const InputFile
*f
) {
58 std::lock_guard
<std::mutex
> lock(mu
);
59 if (f
->toStringCache
.empty()) {
60 if (f
->archiveName
.empty())
61 f
->toStringCache
= f
->getName();
63 (f
->archiveName
+ "(" + f
->getName() + ")").toVector(f
->toStringCache
);
66 return std::string(f
->toStringCache
);
69 const ELFSyncStream
&elf::operator<<(const ELFSyncStream
&s
,
71 return s
<< toStr(s
.ctx
, f
);
74 static ELFKind
getELFKind(Ctx
&ctx
, MemoryBufferRef mb
, StringRef archiveName
) {
77 std::tie(size
, endian
) = getElfArchType(mb
.getBuffer());
79 auto report
= [&](StringRef msg
) {
80 StringRef filename
= mb
.getBufferIdentifier();
81 if (archiveName
.empty())
82 Fatal(ctx
) << filename
<< ": " << msg
;
84 Fatal(ctx
) << archiveName
<< "(" << filename
<< "): " << msg
;
87 if (!mb
.getBuffer().starts_with(ElfMagic
))
88 report("not an ELF file");
89 if (endian
!= ELFDATA2LSB
&& endian
!= ELFDATA2MSB
)
90 report("corrupted ELF file: invalid data encoding");
91 if (size
!= ELFCLASS32
&& size
!= ELFCLASS64
)
92 report("corrupted ELF file: invalid file class");
94 size_t bufSize
= mb
.getBuffer().size();
95 if ((size
== ELFCLASS32
&& bufSize
< sizeof(Elf32_Ehdr
)) ||
96 (size
== ELFCLASS64
&& bufSize
< sizeof(Elf64_Ehdr
)))
97 report("corrupted ELF file: file is too short");
99 if (size
== ELFCLASS32
)
100 return (endian
== ELFDATA2LSB
) ? ELF32LEKind
: ELF32BEKind
;
101 return (endian
== ELFDATA2LSB
) ? ELF64LEKind
: ELF64BEKind
;
104 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
105 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
106 // the input objects have been compiled.
107 static void updateARMVFPArgs(Ctx
&ctx
, const ARMAttributeParser
&attributes
,
108 const InputFile
*f
) {
109 std::optional
<unsigned> attr
=
110 attributes
.getAttributeValue(ARMBuildAttrs::ABI_VFP_args
);
112 // If an ABI tag isn't present then it is implicitly given the value of 0
113 // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
114 // including some in glibc that don't use FP args (and should have value 3)
115 // don't have the attribute so we do not consider an implicit value of 0
119 unsigned vfpArgs
= *attr
;
122 case ARMBuildAttrs::BaseAAPCS
:
123 arg
= ARMVFPArgKind::Base
;
125 case ARMBuildAttrs::HardFPAAPCS
:
126 arg
= ARMVFPArgKind::VFP
;
128 case ARMBuildAttrs::ToolChainFPPCS
:
129 // Tool chain specific convention that conforms to neither AAPCS variant.
130 arg
= ARMVFPArgKind::ToolChain
;
132 case ARMBuildAttrs::CompatibleFPAAPCS
:
133 // Object compatible with all conventions.
136 ErrAlways(ctx
) << f
<< ": unknown Tag_ABI_VFP_args value: " << vfpArgs
;
139 // Follow ld.bfd and error if there is a mix of calling conventions.
140 if (ctx
.arg
.armVFPArgs
!= arg
&& ctx
.arg
.armVFPArgs
!= ARMVFPArgKind::Default
)
141 ErrAlways(ctx
) << f
<< ": incompatible Tag_ABI_VFP_args";
143 ctx
.arg
.armVFPArgs
= arg
;
146 // The ARM support in lld makes some use of instructions that are not available
147 // on all ARM architectures. Namely:
148 // - Use of BLX instruction for interworking between ARM and Thumb state.
149 // - Use of the extended Thumb branch encoding in relocation.
150 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
151 // The ARM Attributes section contains information about the architecture chosen
152 // at compile time. We follow the convention that if at least one input object
153 // is compiled with an architecture that supports these features then lld is
154 // permitted to use them.
155 static void updateSupportedARMFeatures(Ctx
&ctx
,
156 const ARMAttributeParser
&attributes
) {
157 std::optional
<unsigned> attr
=
158 attributes
.getAttributeValue(ARMBuildAttrs::CPU_arch
);
163 case ARMBuildAttrs::Pre_v4
:
164 case ARMBuildAttrs::v4
:
165 case ARMBuildAttrs::v4T
:
166 // Architectures prior to v5 do not support BLX instruction
168 case ARMBuildAttrs::v5T
:
169 case ARMBuildAttrs::v5TE
:
170 case ARMBuildAttrs::v5TEJ
:
171 case ARMBuildAttrs::v6
:
172 case ARMBuildAttrs::v6KZ
:
173 case ARMBuildAttrs::v6K
:
174 ctx
.arg
.armHasBlx
= true;
175 // Architectures used in pre-Cortex processors do not support
176 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
177 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
180 // All other Architectures have BLX and extended branch encoding
181 ctx
.arg
.armHasBlx
= true;
182 ctx
.arg
.armJ1J2BranchEncoding
= true;
183 if (arch
!= ARMBuildAttrs::v6_M
&& arch
!= ARMBuildAttrs::v6S_M
)
184 // All Architectures used in Cortex processors with the exception
185 // of v6-M and v6S-M have the MOVT and MOVW instructions.
186 ctx
.arg
.armHasMovtMovw
= true;
190 // Only ARMv8-M or later architectures have CMSE support.
191 std::optional
<unsigned> profile
=
192 attributes
.getAttributeValue(ARMBuildAttrs::CPU_arch_profile
);
195 if (arch
>= ARMBuildAttrs::CPUArch::v8_M_Base
&&
196 profile
== ARMBuildAttrs::MicroControllerProfile
)
197 ctx
.arg
.armCMSESupport
= true;
199 // The thumb PLT entries require Thumb2 which can be used on multiple archs.
200 // For now, let's limit it to ones where ARM isn't available and we know have
202 std::optional
<unsigned> armISA
=
203 attributes
.getAttributeValue(ARMBuildAttrs::ARM_ISA_use
);
204 std::optional
<unsigned> thumb
=
205 attributes
.getAttributeValue(ARMBuildAttrs::THUMB_ISA_use
);
206 ctx
.arg
.armHasArmISA
|= armISA
&& *armISA
>= ARMBuildAttrs::Allowed
;
207 ctx
.arg
.armHasThumb2ISA
|= thumb
&& *thumb
>= ARMBuildAttrs::AllowThumb32
;
210 InputFile::InputFile(Ctx
&ctx
, Kind k
, MemoryBufferRef m
)
211 : ctx(ctx
), mb(m
), groupId(ctx
.driver
.nextGroupId
), fileKind(k
) {
212 // All files within the same --{start,end}-group get the same group ID.
213 // Otherwise, a new file will get a new group ID.
214 if (!ctx
.driver
.isInGroup
)
215 ++ctx
.driver
.nextGroupId
;
218 InputFile::~InputFile() {}
220 std::optional
<MemoryBufferRef
> elf::readFile(Ctx
&ctx
, StringRef path
) {
221 llvm::TimeTraceScope
timeScope("Load input files", path
);
223 // The --chroot option changes our virtual root directory.
224 // This is useful when you are dealing with files created by --reproduce.
225 if (!ctx
.arg
.chroot
.empty() && path
.starts_with("/"))
226 path
= ctx
.saver
.save(ctx
.arg
.chroot
+ path
);
228 bool remapped
= false;
229 auto it
= ctx
.arg
.remapInputs
.find(path
);
230 if (it
!= ctx
.arg
.remapInputs
.end()) {
234 for (const auto &[pat
, toFile
] : ctx
.arg
.remapInputsWildcards
) {
235 if (pat
.match(path
)) {
243 // Use /dev/null to indicate an input file that should be ignored. Change
244 // the path to NUL on Windows.
246 if (path
== "/dev/null")
252 ctx
.arg
.dependencyFiles
.insert(llvm::CachedHashString(path
));
254 auto mbOrErr
= MemoryBuffer::getFile(path
, /*IsText=*/false,
255 /*RequiresNullTerminator=*/false);
256 if (auto ec
= mbOrErr
.getError()) {
257 ErrAlways(ctx
) << "cannot open " << path
<< ": " << ec
.message();
261 MemoryBufferRef mbref
= (*mbOrErr
)->getMemBufferRef();
262 ctx
.memoryBuffers
.push_back(std::move(*mbOrErr
)); // take MB ownership
265 ctx
.tar
->append(relativeToRoot(path
), mbref
.getBuffer());
269 // All input object files must be for the same architecture
270 // (e.g. it does not make sense to link x86 object files with
271 // MIPS object files.) This function checks for that error.
272 static bool isCompatible(Ctx
&ctx
, InputFile
*file
) {
273 if (!file
->isElf() && !isa
<BitcodeFile
>(file
))
276 if (file
->ekind
== ctx
.arg
.ekind
&& file
->emachine
== ctx
.arg
.emachine
) {
277 if (ctx
.arg
.emachine
!= EM_MIPS
)
279 if (isMipsN32Abi(ctx
, *file
) == ctx
.arg
.mipsN32Abi
)
284 !ctx
.arg
.bfdname
.empty() ? ctx
.arg
.bfdname
: ctx
.arg
.emulation
;
285 if (!target
.empty()) {
286 Err(ctx
) << file
<< " is incompatible with " << target
;
290 InputFile
*existing
= nullptr;
291 if (!ctx
.objectFiles
.empty())
292 existing
= ctx
.objectFiles
[0];
293 else if (!ctx
.sharedFiles
.empty())
294 existing
= ctx
.sharedFiles
[0];
295 else if (!ctx
.bitcodeFiles
.empty())
296 existing
= ctx
.bitcodeFiles
[0];
297 auto diag
= Err(ctx
);
298 diag
<< file
<< " is incompatible";
300 diag
<< " with " << existing
;
304 template <class ELFT
> static void doParseFile(Ctx
&ctx
, InputFile
*file
) {
305 if (!isCompatible(ctx
, file
))
310 if (auto *f
= dyn_cast
<BitcodeFile
>(file
)) {
311 ctx
.lazyBitcodeFiles
.push_back(f
);
314 cast
<ObjFile
<ELFT
>>(file
)->parseLazy();
322 if (file
->kind() == InputFile::ObjKind
) {
323 ctx
.objectFiles
.push_back(cast
<ELFFileBase
>(file
));
324 cast
<ObjFile
<ELFT
>>(file
)->parse();
325 } else if (auto *f
= dyn_cast
<SharedFile
>(file
)) {
327 } else if (auto *f
= dyn_cast
<BitcodeFile
>(file
)) {
328 ctx
.bitcodeFiles
.push_back(f
);
331 ctx
.binaryFiles
.push_back(cast
<BinaryFile
>(file
));
332 cast
<BinaryFile
>(file
)->parse();
336 // Add symbols in File to the symbol table.
337 void elf::parseFile(Ctx
&ctx
, InputFile
*file
) {
338 invokeELFT(doParseFile
, ctx
, file
);
341 // This function is explicitly instantiated in ARM.cpp. Mark it extern here,
342 // to avoid warnings when building with MSVC.
343 extern template void ObjFile
<ELF32LE
>::importCmseSymbols();
344 extern template void ObjFile
<ELF32BE
>::importCmseSymbols();
345 extern template void ObjFile
<ELF64LE
>::importCmseSymbols();
346 extern template void ObjFile
<ELF64BE
>::importCmseSymbols();
348 template <class ELFT
>
350 doParseFiles(Ctx
&ctx
,
351 const SmallVector
<std::unique_ptr
<InputFile
>, 0> &files
) {
352 // Add all files to the symbol table. This will add almost all symbols that we
353 // need to the symbol table. This process might add files to the link due to
354 // addDependentLibrary.
355 for (size_t i
= 0; i
< files
.size(); ++i
) {
356 llvm::TimeTraceScope
timeScope("Parse input files", files
[i
]->getName());
357 doParseFile
<ELFT
>(ctx
, files
[i
].get());
359 if (ctx
.driver
.armCmseImpLib
)
360 cast
<ObjFile
<ELFT
>>(*ctx
.driver
.armCmseImpLib
).importCmseSymbols();
363 void elf::parseFiles(Ctx
&ctx
,
364 const SmallVector
<std::unique_ptr
<InputFile
>, 0> &files
) {
365 llvm::TimeTraceScope
timeScope("Parse input files");
366 invokeELFT(doParseFiles
, ctx
, files
);
369 // Concatenates arguments to construct a string representing an error location.
370 StringRef
InputFile::getNameForScript() const {
371 if (archiveName
.empty())
374 if (nameForScriptCache
.empty())
375 nameForScriptCache
= (archiveName
+ Twine(':') + getName()).str();
377 return nameForScriptCache
;
380 // An ELF object file may contain a `.deplibs` section. If it exists, the
381 // section contains a list of library specifiers such as `m` for libm. This
382 // function resolves a given name by finding the first matching library checking
383 // the various ways that a library can be specified to LLD. This ELF extension
384 // is a form of autolinking and is called `dependent libraries`. It is currently
385 // unique to LLVM and lld.
386 static void addDependentLibrary(Ctx
&ctx
, StringRef specifier
,
387 const InputFile
*f
) {
388 if (!ctx
.arg
.dependentLibraries
)
390 if (std::optional
<std::string
> s
= searchLibraryBaseName(ctx
, specifier
))
391 ctx
.driver
.addFile(ctx
.saver
.save(*s
), /*withLOption=*/true);
392 else if (std::optional
<std::string
> s
= findFromSearchPaths(ctx
, specifier
))
393 ctx
.driver
.addFile(ctx
.saver
.save(*s
), /*withLOption=*/true);
394 else if (fs::exists(specifier
))
395 ctx
.driver
.addFile(specifier
, /*withLOption=*/false);
398 << f
<< ": unable to find library from dependent library specifier: "
402 // Record the membership of a section group so that in the garbage collection
403 // pass, section group members are kept or discarded as a unit.
404 template <class ELFT
>
405 static void handleSectionGroup(ArrayRef
<InputSectionBase
*> sections
,
406 ArrayRef
<typename
ELFT::Word
> entries
) {
407 bool hasAlloc
= false;
408 for (uint32_t index
: entries
.slice(1)) {
409 if (index
>= sections
.size())
411 if (InputSectionBase
*s
= sections
[index
])
412 if (s
!= &InputSection::discarded
&& s
->flags
& SHF_ALLOC
)
416 // If any member has the SHF_ALLOC flag, the whole group is subject to garbage
417 // collection. See the comment in markLive(). This rule retains .debug_types
418 // and .rela.debug_types.
422 // Connect the members in a circular doubly-linked list via
423 // nextInSectionGroup.
424 InputSectionBase
*head
;
425 InputSectionBase
*prev
= nullptr;
426 for (uint32_t index
: entries
.slice(1)) {
427 InputSectionBase
*s
= sections
[index
];
428 if (!s
|| s
== &InputSection::discarded
)
431 prev
->nextInSectionGroup
= s
;
437 prev
->nextInSectionGroup
= head
;
440 template <class ELFT
> void ObjFile
<ELFT
>::initDwarf() {
441 dwarf
= std::make_unique
<DWARFCache
>(std::make_unique
<DWARFContext
>(
442 std::make_unique
<LLDDwarfObj
<ELFT
>>(this), "",
443 [&](Error err
) { Warn(ctx
) << getName() + ": " << std::move(err
); },
445 Warn(ctx
) << getName() << ": " << std::move(warning
);
449 DWARFCache
*ELFFileBase::getDwarf() {
450 assert(fileKind
== ObjKind
);
451 llvm::call_once(initDwarf
, [this]() {
454 llvm_unreachable("");
456 return cast
<ObjFile
<ELF32LE
>>(this)->initDwarf();
458 return cast
<ObjFile
<ELF32BE
>>(this)->initDwarf();
460 return cast
<ObjFile
<ELF64LE
>>(this)->initDwarf();
462 return cast
<ObjFile
<ELF64BE
>>(this)->initDwarf();
468 ELFFileBase::ELFFileBase(Ctx
&ctx
, Kind k
, ELFKind ekind
, MemoryBufferRef mb
)
469 : InputFile(ctx
, k
, mb
) {
473 ELFFileBase::~ELFFileBase() {}
475 template <typename Elf_Shdr
>
476 static const Elf_Shdr
*findSection(ArrayRef
<Elf_Shdr
> sections
, uint32_t type
) {
477 for (const Elf_Shdr
&sec
: sections
)
478 if (sec
.sh_type
== type
)
483 void ELFFileBase::init() {
486 init
<ELF32LE
>(fileKind
);
489 init
<ELF32BE
>(fileKind
);
492 init
<ELF64LE
>(fileKind
);
495 init
<ELF64BE
>(fileKind
);
498 llvm_unreachable("getELFKind");
502 template <class ELFT
> void ELFFileBase::init(InputFile::Kind k
) {
503 using Elf_Shdr
= typename
ELFT::Shdr
;
504 using Elf_Sym
= typename
ELFT::Sym
;
506 // Initialize trivial attributes.
507 const ELFFile
<ELFT
> &obj
= getObj
<ELFT
>();
508 emachine
= obj
.getHeader().e_machine
;
509 osabi
= obj
.getHeader().e_ident
[llvm::ELF::EI_OSABI
];
510 abiVersion
= obj
.getHeader().e_ident
[llvm::ELF::EI_ABIVERSION
];
512 ArrayRef
<Elf_Shdr
> sections
= CHECK2(obj
.sections(), this);
513 elfShdrs
= sections
.data();
514 numELFShdrs
= sections
.size();
516 // Find a symbol table.
517 const Elf_Shdr
*symtabSec
=
518 findSection(sections
, k
== SharedKind
? SHT_DYNSYM
: SHT_SYMTAB
);
523 // Initialize members corresponding to a symbol table.
524 firstGlobal
= symtabSec
->sh_info
;
526 ArrayRef
<Elf_Sym
> eSyms
= CHECK2(obj
.symbols(symtabSec
), this);
527 if (firstGlobal
== 0 || firstGlobal
> eSyms
.size())
528 Fatal(ctx
) << this << ": invalid sh_info in symbol table";
530 elfSyms
= reinterpret_cast<const void *>(eSyms
.data());
531 numSymbols
= eSyms
.size();
532 stringTable
= CHECK2(obj
.getStringTableForSymtab(*symtabSec
, sections
), this);
535 template <class ELFT
>
536 uint32_t ObjFile
<ELFT
>::getSectionIndex(const Elf_Sym
&sym
) const {
538 this->getObj().getSectionIndex(sym
, getELFSyms
<ELFT
>(), shndxTable
),
542 template <class ELFT
> void ObjFile
<ELFT
>::parse(bool ignoreComdats
) {
543 object::ELFFile
<ELFT
> obj
= this->getObj();
544 // Read a section table. justSymbols is usually false.
545 if (this->justSymbols
) {
546 initializeJustSymbols();
547 initializeSymbols(obj
);
551 // Handle dependent libraries and selection of section groups as these are not
553 ArrayRef
<Elf_Shdr
> objSections
= getELFShdrs
<ELFT
>();
554 StringRef shstrtab
= CHECK2(obj
.getSectionStringTable(objSections
), this);
555 uint64_t size
= objSections
.size();
556 sections
.resize(size
);
557 for (size_t i
= 0; i
!= size
; ++i
) {
558 const Elf_Shdr
&sec
= objSections
[i
];
559 if (LLVM_LIKELY(sec
.sh_type
== SHT_PROGBITS
))
561 if (LLVM_LIKELY(sec
.sh_type
== SHT_GROUP
)) {
562 StringRef signature
= getShtGroupSignature(objSections
, sec
);
563 ArrayRef
<Elf_Word
> entries
=
564 CHECK2(obj
.template getSectionContentsAsArray
<Elf_Word
>(sec
), this);
566 Fatal(ctx
) << this << ": empty SHT_GROUP";
568 Elf_Word flag
= entries
[0];
569 if (flag
&& flag
!= GRP_COMDAT
)
570 Fatal(ctx
) << this << ": unsupported SHT_GROUP format";
572 bool keepGroup
= !flag
|| ignoreComdats
||
573 ctx
.symtab
->comdatGroups
574 .try_emplace(CachedHashStringRef(signature
), this)
577 if (!ctx
.arg
.resolveGroups
)
578 sections
[i
] = createInputSection(
579 i
, sec
, check(obj
.getSectionName(sec
, shstrtab
)));
581 // Otherwise, discard group members.
582 for (uint32_t secIndex
: entries
.slice(1)) {
583 if (secIndex
>= size
)
585 << ": invalid section index in group: " << secIndex
;
586 sections
[secIndex
] = &InputSection::discarded
;
592 if (sec
.sh_type
== SHT_LLVM_DEPENDENT_LIBRARIES
&& !ctx
.arg
.relocatable
) {
593 StringRef name
= check(obj
.getSectionName(sec
, shstrtab
));
594 ArrayRef
<char> data
= CHECK2(
595 this->getObj().template getSectionContentsAsArray
<char>(sec
), this);
596 if (!data
.empty() && data
.back() != '\0') {
599 << ": corrupted dependent libraries section (unterminated string): "
602 for (const char *d
= data
.begin(), *e
= data
.end(); d
< e
;) {
604 addDependentLibrary(ctx
, s
, this);
608 sections
[i
] = &InputSection::discarded
;
612 switch (ctx
.arg
.emachine
) {
614 if (sec
.sh_type
== SHT_ARM_ATTRIBUTES
) {
615 ARMAttributeParser attributes
;
616 ArrayRef
<uint8_t> contents
=
617 check(this->getObj().getSectionContents(sec
));
618 StringRef name
= check(obj
.getSectionName(sec
, shstrtab
));
619 sections
[i
] = &InputSection::discarded
;
620 if (Error e
= attributes
.parse(contents
, ekind
== ELF32LEKind
621 ? llvm::endianness::little
622 : llvm::endianness::big
)) {
623 InputSection
isec(*this, sec
, name
);
624 Warn(ctx
) << &isec
<< ": " << std::move(e
);
626 updateSupportedARMFeatures(ctx
, attributes
);
627 updateARMVFPArgs(ctx
, attributes
, this);
629 // FIXME: Retain the first attribute section we see. The eglibc ARM
630 // dynamic loaders require the presence of an attribute section for
631 // dlopen to work. In a full implementation we would merge all
632 // attribute sections.
633 if (ctx
.in
.attributes
== nullptr) {
635 std::make_unique
<InputSection
>(*this, sec
, name
);
636 sections
[i
] = ctx
.in
.attributes
.get();
642 // Producing a static binary with MTE globals is not currently supported,
643 // remove all SHT_AARCH64_MEMTAG_GLOBALS_STATIC sections as they're unused
644 // medatada, and we don't want them to end up in the output file for
645 // static executables.
646 if (sec
.sh_type
== SHT_AARCH64_MEMTAG_GLOBALS_STATIC
&&
647 !canHaveMemtagGlobals(ctx
))
648 sections
[i
] = &InputSection::discarded
;
653 // Read a symbol table.
654 initializeSymbols(obj
);
657 // Sections with SHT_GROUP and comdat bits define comdat section groups.
658 // They are identified and deduplicated by group name. This function
659 // returns a group name.
660 template <class ELFT
>
661 StringRef ObjFile
<ELFT
>::getShtGroupSignature(ArrayRef
<Elf_Shdr
> sections
,
662 const Elf_Shdr
&sec
) {
663 typename
ELFT::SymRange symbols
= this->getELFSyms
<ELFT
>();
664 if (sec
.sh_info
>= symbols
.size())
665 Fatal(ctx
) << this << ": invalid symbol index";
666 const typename
ELFT::Sym
&sym
= symbols
[sec
.sh_info
];
667 return CHECK2(sym
.getName(this->stringTable
), this);
670 template <class ELFT
>
671 bool ObjFile
<ELFT
>::shouldMerge(const Elf_Shdr
&sec
, StringRef name
) {
672 // On a regular link we don't merge sections if -O0 (default is -O1). This
673 // sometimes makes the linker significantly faster, although the output will
676 // Doing the same for -r would create a problem as it would combine sections
677 // with different sh_entsize. One option would be to just copy every SHF_MERGE
678 // section as is to the output. While this would produce a valid ELF file with
679 // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
680 // they see two .debug_str. We could have separate logic for combining
681 // SHF_MERGE sections based both on their name and sh_entsize, but that seems
682 // to be more trouble than it is worth. Instead, we just use the regular (-O1)
684 if (ctx
.arg
.optimize
== 0 && !ctx
.arg
.relocatable
)
687 // A mergeable section with size 0 is useless because they don't have
688 // any data to merge. A mergeable string section with size 0 can be
689 // argued as invalid because it doesn't end with a null character.
690 // We'll avoid a mess by handling them as if they were non-mergeable.
691 if (sec
.sh_size
== 0)
694 // Check for sh_entsize. The ELF spec is not clear about the zero
695 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
696 // the section does not hold a table of fixed-size entries". We know
697 // that Rust 1.13 produces a string mergeable section with a zero
698 // sh_entsize. Here we just accept it rather than being picky about it.
699 uint64_t entSize
= sec
.sh_entsize
;
702 if (sec
.sh_size
% entSize
)
703 Fatal(ctx
) << this << ":(" << name
<< "): SHF_MERGE section size ("
704 << uint64_t(sec
.sh_size
)
705 << ") must be a multiple of sh_entsize (" << entSize
<< ")";
707 if (sec
.sh_flags
& SHF_WRITE
)
708 Fatal(ctx
) << this << ":(" << name
709 << "): writable SHF_MERGE section is not supported";
714 // This is for --just-symbols.
716 // --just-symbols is a very minor feature that allows you to link your
717 // output against other existing program, so that if you load both your
718 // program and the other program into memory, your output can refer the
719 // other program's symbols.
721 // When the option is given, we link "just symbols". The section table is
722 // initialized with null pointers.
723 template <class ELFT
> void ObjFile
<ELFT
>::initializeJustSymbols() {
724 sections
.resize(numELFShdrs
);
727 static bool isKnownSpecificSectionType(uint32_t t
, uint32_t flags
) {
728 if (SHT_LOUSER
<= t
&& t
<= SHT_HIUSER
&& !(flags
& SHF_ALLOC
))
730 if (SHT_LOOS
<= t
&& t
<= SHT_HIOS
&& !(flags
& SHF_OS_NONCONFORMING
))
732 // Allow all processor-specific types. This is different from GNU ld.
733 return SHT_LOPROC
<= t
&& t
<= SHT_HIPROC
;
736 template <class ELFT
>
737 void ObjFile
<ELFT
>::initializeSections(bool ignoreComdats
,
738 const llvm::object::ELFFile
<ELFT
> &obj
) {
739 ArrayRef
<Elf_Shdr
> objSections
= getELFShdrs
<ELFT
>();
740 StringRef shstrtab
= CHECK2(obj
.getSectionStringTable(objSections
), this);
741 uint64_t size
= objSections
.size();
742 SmallVector
<ArrayRef
<Elf_Word
>, 0> selectedGroups
;
743 for (size_t i
= 0; i
!= size
; ++i
) {
744 if (this->sections
[i
] == &InputSection::discarded
)
746 const Elf_Shdr
&sec
= objSections
[i
];
747 const uint32_t type
= sec
.sh_type
;
749 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
750 // if -r is given, we'll let the final link discard such sections.
751 // This is compatible with GNU.
752 if ((sec
.sh_flags
& SHF_EXCLUDE
) && !ctx
.arg
.relocatable
) {
753 if (type
== SHT_LLVM_CALL_GRAPH_PROFILE
)
754 cgProfileSectionIndex
= i
;
755 if (type
== SHT_LLVM_ADDRSIG
) {
756 // We ignore the address-significance table if we know that the object
757 // file was created by objcopy or ld -r. This is because these tools
758 // will reorder the symbols in the symbol table, invalidating the data
759 // in the address-significance table, which refers to symbols by index.
760 if (sec
.sh_link
!= 0)
761 this->addrsigSec
= &sec
;
762 else if (ctx
.arg
.icf
== ICFLevel::Safe
)
764 << ": --icf=safe conservatively ignores "
765 "SHT_LLVM_ADDRSIG [index "
767 << "] with sh_link=0 "
768 "(likely created using objcopy or ld -r)";
770 this->sections
[i
] = &InputSection::discarded
;
776 if (!ctx
.arg
.relocatable
)
777 sections
[i
] = &InputSection::discarded
;
778 StringRef signature
=
779 cantFail(this->getELFSyms
<ELFT
>()[sec
.sh_info
].getName(stringTable
));
780 ArrayRef
<Elf_Word
> entries
=
781 cantFail(obj
.template getSectionContentsAsArray
<Elf_Word
>(sec
));
782 if ((entries
[0] & GRP_COMDAT
) == 0 || ignoreComdats
||
783 ctx
.symtab
->comdatGroups
.find(CachedHashStringRef(signature
))
785 selectedGroups
.push_back(entries
);
788 case SHT_SYMTAB_SHNDX
:
789 shndxTable
= CHECK2(obj
.getSHNDXTable(sec
, objSections
), this);
803 case SHT_PREINIT_ARRAY
:
805 createInputSection(i
, sec
, check(obj
.getSectionName(sec
, shstrtab
)));
808 // Discard .llvm.lto in a relocatable link that does not use the bitcode.
809 // The concatenated output does not properly reflect the linking
810 // semantics. In addition, since we do not use the bitcode wrapper format,
811 // the concatenated raw bitcode would be invalid.
812 if (ctx
.arg
.relocatable
&& !ctx
.arg
.fatLTOObjects
) {
813 sections
[i
] = &InputSection::discarded
;
819 createInputSection(i
, sec
, check(obj
.getSectionName(sec
, shstrtab
)));
820 if (type
== SHT_LLVM_SYMPART
)
821 ctx
.hasSympart
.store(true, std::memory_order_relaxed
);
822 else if (ctx
.arg
.rejectMismatch
&&
823 !isKnownSpecificSectionType(type
, sec
.sh_flags
))
824 Err(ctx
) << this->sections
[i
] << ": unknown section type 0x"
825 << Twine::utohexstr(type
);
830 // We have a second loop. It is used to:
831 // 1) handle SHF_LINK_ORDER sections.
832 // 2) create relocation sections. In some cases the section header index of a
833 // relocation section may be smaller than that of the relocated section. In
834 // such cases, the relocation section would attempt to reference a target
835 // section that has not yet been created. For simplicity, delay creation of
836 // relocation sections until now.
837 for (size_t i
= 0; i
!= size
; ++i
) {
838 if (this->sections
[i
] == &InputSection::discarded
)
840 const Elf_Shdr
&sec
= objSections
[i
];
842 if (isStaticRelSecType(sec
.sh_type
)) {
843 // Find a relocation target section and associate this section with that.
844 // Target may have been discarded if it is in a different section group
845 // and the group is discarded, even though it's a violation of the spec.
846 // We handle that situation gracefully by discarding dangling relocation
848 const uint32_t info
= sec
.sh_info
;
849 InputSectionBase
*s
= getRelocTarget(i
, info
);
853 // ELF spec allows mergeable sections with relocations, but they are rare,
854 // and it is in practice hard to merge such sections by contents, because
855 // applying relocations at end of linking changes section contents. So, we
856 // simply handle such sections as non-mergeable ones. Degrading like this
857 // is acceptable because section merging is optional.
858 if (auto *ms
= dyn_cast
<MergeInputSection
>(s
)) {
859 s
= makeThreadLocal
<InputSection
>(ms
->file
, ms
->name
, ms
->type
,
860 ms
->flags
, ms
->addralign
, ms
->entsize
,
861 ms
->contentMaybeDecompress());
865 if (s
->relSecIdx
!= 0)
867 << ": multiple relocation sections to one section are "
871 // Relocation sections are usually removed from the output, so return
872 // `nullptr` for the normal case. However, if -r or --emit-relocs is
873 // specified, we need to copy them to the output. (Some post link analysis
874 // tools specify --emit-relocs to obtain the information.)
875 if (ctx
.arg
.copyRelocs
) {
876 auto *isec
= makeThreadLocal
<InputSection
>(
877 *this, sec
, check(obj
.getSectionName(sec
, shstrtab
)));
878 // If the relocated section is discarded (due to /DISCARD/ or
879 // --gc-sections), the relocation section should be discarded as well.
880 s
->dependentSections
.push_back(isec
);
886 // A SHF_LINK_ORDER section with sh_link=0 is handled as if it did not have
888 if (!sec
.sh_link
|| !(sec
.sh_flags
& SHF_LINK_ORDER
))
891 InputSectionBase
*linkSec
= nullptr;
892 if (sec
.sh_link
< size
)
893 linkSec
= this->sections
[sec
.sh_link
];
896 << ": invalid sh_link index: " << uint32_t(sec
.sh_link
);
898 // A SHF_LINK_ORDER section is discarded if its linked-to section is
900 InputSection
*isec
= cast
<InputSection
>(this->sections
[i
]);
901 linkSec
->dependentSections
.push_back(isec
);
902 if (!isa
<InputSection
>(linkSec
))
904 << "a section " << isec
->name
905 << " with SHF_LINK_ORDER should not refer a non-regular section: "
909 for (ArrayRef
<Elf_Word
> entries
: selectedGroups
)
910 handleSectionGroup
<ELFT
>(this->sections
, entries
);
913 // Read the following info from the .note.gnu.property section and write it to
914 // the corresponding fields in `ObjFile`:
915 // - Feature flags (32 bits) representing x86 or AArch64 features for
916 // hardware-assisted call flow control;
917 // - AArch64 PAuth ABI core info (16 bytes).
918 template <class ELFT
>
919 static void readGnuProperty(Ctx
&ctx
, const InputSection
&sec
,
921 using Elf_Nhdr
= typename
ELFT::Nhdr
;
922 using Elf_Note
= typename
ELFT::Note
;
924 ArrayRef
<uint8_t> data
= sec
.content();
925 auto reportFatal
= [&](const uint8_t *place
, const Twine
&msg
) {
926 Fatal(ctx
) << sec
.file
<< ":(" << sec
.name
<< "+0x"
927 << Twine::utohexstr(place
- sec
.content().data())
930 while (!data
.empty()) {
931 // Read one NOTE record.
932 auto *nhdr
= reinterpret_cast<const Elf_Nhdr
*>(data
.data());
933 if (data
.size() < sizeof(Elf_Nhdr
) ||
934 data
.size() < nhdr
->getSize(sec
.addralign
))
935 reportFatal(data
.data(), "data is too short");
937 Elf_Note
note(*nhdr
);
938 if (nhdr
->n_type
!= NT_GNU_PROPERTY_TYPE_0
|| note
.getName() != "GNU") {
939 data
= data
.slice(nhdr
->getSize(sec
.addralign
));
943 uint32_t featureAndType
= ctx
.arg
.emachine
== EM_AARCH64
944 ? GNU_PROPERTY_AARCH64_FEATURE_1_AND
945 : GNU_PROPERTY_X86_FEATURE_1_AND
;
947 // Read a body of a NOTE record, which consists of type-length-value fields.
948 ArrayRef
<uint8_t> desc
= note
.getDesc(sec
.addralign
);
949 while (!desc
.empty()) {
950 const uint8_t *place
= desc
.data();
952 reportFatal(place
, "program property is too short");
953 uint32_t type
= read32
<ELFT::Endianness
>(desc
.data());
954 uint32_t size
= read32
<ELFT::Endianness
>(desc
.data() + 4);
955 desc
= desc
.slice(8);
956 if (desc
.size() < size
)
957 reportFatal(place
, "program property is too short");
959 if (type
== featureAndType
) {
960 // We found a FEATURE_1_AND field. There may be more than one of these
961 // in a .note.gnu.property section, for a relocatable object we
962 // accumulate the bits set.
964 reportFatal(place
, "FEATURE_1_AND entry is too short");
965 f
.andFeatures
|= read32
<ELFT::Endianness
>(desc
.data());
966 } else if (ctx
.arg
.emachine
== EM_AARCH64
&&
967 type
== GNU_PROPERTY_AARCH64_FEATURE_PAUTH
) {
968 if (!f
.aarch64PauthAbiCoreInfo
.empty()) {
969 reportFatal(data
.data(),
970 "multiple GNU_PROPERTY_AARCH64_FEATURE_PAUTH entries are "
972 } else if (size
!= 16) {
973 reportFatal(data
.data(), "GNU_PROPERTY_AARCH64_FEATURE_PAUTH entry "
974 "is invalid: expected 16 bytes, but got " +
977 f
.aarch64PauthAbiCoreInfo
= desc
;
980 // Padding is present in the note descriptor, if necessary.
981 desc
= desc
.slice(alignTo
<(ELFT::Is64Bits
? 8 : 4)>(size
));
984 // Go to next NOTE record to look for more FEATURE_1_AND descriptions.
985 data
= data
.slice(nhdr
->getSize(sec
.addralign
));
989 template <class ELFT
>
990 InputSectionBase
*ObjFile
<ELFT
>::getRelocTarget(uint32_t idx
, uint32_t info
) {
991 if (info
< this->sections
.size()) {
992 InputSectionBase
*target
= this->sections
[info
];
994 // Strictly speaking, a relocation section must be included in the
995 // group of the section it relocates. However, LLVM 3.3 and earlier
996 // would fail to do so, so we gracefully handle that case.
997 if (target
== &InputSection::discarded
)
1000 if (target
!= nullptr)
1004 Err(ctx
) << this << ": relocation section (index " << idx
1005 << ") has invalid sh_info (" << info
<< ')';
1009 // The function may be called concurrently for different input files. For
1010 // allocation, prefer makeThreadLocal which does not require holding a lock.
1011 template <class ELFT
>
1012 InputSectionBase
*ObjFile
<ELFT
>::createInputSection(uint32_t idx
,
1013 const Elf_Shdr
&sec
,
1015 if (name
.starts_with(".n")) {
1016 // The GNU linker uses .note.GNU-stack section as a marker indicating
1017 // that the code in the object file does not expect that the stack is
1018 // executable (in terms of NX bit). If all input files have the marker,
1019 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
1020 // make the stack non-executable. Most object files have this section as
1023 // But making the stack non-executable is a norm today for security
1024 // reasons. Failure to do so may result in a serious security issue.
1025 // Therefore, we make LLD always add PT_GNU_STACK unless it is
1026 // explicitly told to do otherwise (by -z execstack). Because the stack
1027 // executable-ness is controlled solely by command line options,
1028 // .note.GNU-stack sections are simply ignored.
1029 if (name
== ".note.GNU-stack")
1030 return &InputSection::discarded
;
1032 // Object files that use processor features such as Intel Control-Flow
1033 // Enforcement (CET) or AArch64 Branch Target Identification BTI, use a
1034 // .note.gnu.property section containing a bitfield of feature bits like the
1035 // GNU_PROPERTY_X86_FEATURE_1_IBT flag. Read a bitmap containing the flag.
1037 // Since we merge bitmaps from multiple object files to create a new
1038 // .note.gnu.property containing a single AND'ed bitmap, we discard an input
1039 // file's .note.gnu.property section.
1040 if (name
== ".note.gnu.property") {
1041 readGnuProperty
<ELFT
>(ctx
, InputSection(*this, sec
, name
), *this);
1042 return &InputSection::discarded
;
1045 // Split stacks is a feature to support a discontiguous stack,
1046 // commonly used in the programming language Go. For the details,
1047 // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
1048 // for split stack will include a .note.GNU-split-stack section.
1049 if (name
== ".note.GNU-split-stack") {
1050 if (ctx
.arg
.relocatable
) {
1051 ErrAlways(ctx
) << "cannot mix split-stack and non-split-stack in a "
1053 return &InputSection::discarded
;
1055 this->splitStack
= true;
1056 return &InputSection::discarded
;
1059 // An object file compiled for split stack, but where some of the
1060 // functions were compiled with the no_split_stack_attribute will
1061 // include a .note.GNU-no-split-stack section.
1062 if (name
== ".note.GNU-no-split-stack") {
1063 this->someNoSplitStack
= true;
1064 return &InputSection::discarded
;
1067 // Strip existing .note.gnu.build-id sections so that the output won't have
1068 // more than one build-id. This is not usually a problem because input
1069 // object files normally don't have .build-id sections, but you can create
1070 // such files by "ld.{bfd,gold,lld} -r --build-id", and we want to guard
1072 if (name
== ".note.gnu.build-id")
1073 return &InputSection::discarded
;
1076 // The linker merges EH (exception handling) frames and creates a
1077 // .eh_frame_hdr section for runtime. So we handle them with a special
1078 // class. For relocatable outputs, they are just passed through.
1079 if (name
== ".eh_frame" && !ctx
.arg
.relocatable
)
1080 return makeThreadLocal
<EhInputSection
>(*this, sec
, name
);
1082 if ((sec
.sh_flags
& SHF_MERGE
) && shouldMerge(sec
, name
))
1083 return makeThreadLocal
<MergeInputSection
>(*this, sec
, name
);
1084 return makeThreadLocal
<InputSection
>(*this, sec
, name
);
1087 // Initialize symbols. symbols is a parallel array to the corresponding ELF
1089 template <class ELFT
>
1090 void ObjFile
<ELFT
>::initializeSymbols(const object::ELFFile
<ELFT
> &obj
) {
1091 ArrayRef
<Elf_Sym
> eSyms
= this->getELFSyms
<ELFT
>();
1093 symbols
= std::make_unique
<Symbol
*[]>(numSymbols
);
1095 // Some entries have been filled by LazyObjFile.
1096 auto *symtab
= ctx
.symtab
.get();
1097 for (size_t i
= firstGlobal
, end
= eSyms
.size(); i
!= end
; ++i
)
1099 symbols
[i
] = symtab
->insert(CHECK2(eSyms
[i
].getName(stringTable
), this));
1101 // Perform symbol resolution on non-local symbols.
1102 SmallVector
<unsigned, 32> undefineds
;
1103 for (size_t i
= firstGlobal
, end
= eSyms
.size(); i
!= end
; ++i
) {
1104 const Elf_Sym
&eSym
= eSyms
[i
];
1105 uint32_t secIdx
= eSym
.st_shndx
;
1106 if (secIdx
== SHN_UNDEF
) {
1107 undefineds
.push_back(i
);
1111 uint8_t binding
= eSym
.getBinding();
1112 uint8_t stOther
= eSym
.st_other
;
1113 uint8_t type
= eSym
.getType();
1114 uint64_t value
= eSym
.st_value
;
1115 uint64_t size
= eSym
.st_size
;
1117 Symbol
*sym
= symbols
[i
];
1118 sym
->isUsedInRegularObj
= true;
1119 if (LLVM_UNLIKELY(eSym
.st_shndx
== SHN_COMMON
)) {
1120 if (value
== 0 || value
>= UINT32_MAX
)
1121 Fatal(ctx
) << this << ": common symbol '" << sym
->getName()
1122 << "' has invalid alignment: " << value
;
1123 hasCommonSyms
= true;
1124 sym
->resolve(ctx
, CommonSymbol
{ctx
, this, StringRef(), binding
, stOther
,
1125 type
, value
, size
});
1129 // Handle global defined symbols. Defined::section will be set in postParse.
1130 sym
->resolve(ctx
, Defined
{ctx
, this, StringRef(), binding
, stOther
, type
,
1131 value
, size
, nullptr});
1134 // Undefined symbols (excluding those defined relative to non-prevailing
1135 // sections) can trigger recursive extract. Process defined symbols first so
1136 // that the relative order between a defined symbol and an undefined symbol
1137 // does not change the symbol resolution behavior. In addition, a set of
1138 // interconnected symbols will all be resolved to the same file, instead of
1139 // being resolved to different files.
1140 for (unsigned i
: undefineds
) {
1141 const Elf_Sym
&eSym
= eSyms
[i
];
1142 Symbol
*sym
= symbols
[i
];
1143 sym
->resolve(ctx
, Undefined
{this, StringRef(), eSym
.getBinding(),
1144 eSym
.st_other
, eSym
.getType()});
1145 sym
->isUsedInRegularObj
= true;
1146 sym
->referenced
= true;
1150 template <class ELFT
>
1151 void ObjFile
<ELFT
>::initSectionsAndLocalSyms(bool ignoreComdats
) {
1153 initializeSections(ignoreComdats
, getObj());
1157 SymbolUnion
*locals
= makeThreadLocalN
<SymbolUnion
>(firstGlobal
);
1158 memset(locals
, 0, sizeof(SymbolUnion
) * firstGlobal
);
1160 ArrayRef
<Elf_Sym
> eSyms
= this->getELFSyms
<ELFT
>();
1161 for (size_t i
= 0, end
= firstGlobal
; i
!= end
; ++i
) {
1162 const Elf_Sym
&eSym
= eSyms
[i
];
1163 uint32_t secIdx
= eSym
.st_shndx
;
1164 if (LLVM_UNLIKELY(secIdx
== SHN_XINDEX
))
1165 secIdx
= check(getExtendedSymbolTableIndex
<ELFT
>(eSym
, i
, shndxTable
));
1166 else if (secIdx
>= SHN_LORESERVE
)
1168 if (LLVM_UNLIKELY(secIdx
>= sections
.size()))
1169 Fatal(ctx
) << this << ": invalid section index: " << secIdx
;
1170 if (LLVM_UNLIKELY(eSym
.getBinding() != STB_LOCAL
))
1171 ErrAlways(ctx
) << this << ": non-local symbol (" << i
1172 << ") found at index < .symtab's sh_info (" << end
<< ")";
1174 InputSectionBase
*sec
= sections
[secIdx
];
1175 uint8_t type
= eSym
.getType();
1176 if (type
== STT_FILE
)
1177 sourceFile
= CHECK2(eSym
.getName(stringTable
), this);
1178 if (LLVM_UNLIKELY(stringTable
.size() <= eSym
.st_name
))
1179 Fatal(ctx
) << this << ": invalid symbol name offset";
1180 StringRef
name(stringTable
.data() + eSym
.st_name
);
1182 symbols
[i
] = reinterpret_cast<Symbol
*>(locals
+ i
);
1183 if (eSym
.st_shndx
== SHN_UNDEF
|| sec
== &InputSection::discarded
)
1184 new (symbols
[i
]) Undefined(this, name
, STB_LOCAL
, eSym
.st_other
, type
,
1185 /*discardedSecIdx=*/secIdx
);
1187 new (symbols
[i
]) Defined(ctx
, this, name
, STB_LOCAL
, eSym
.st_other
, type
,
1188 eSym
.st_value
, eSym
.st_size
, sec
);
1189 symbols
[i
]->partition
= 1;
1190 symbols
[i
]->isUsedInRegularObj
= true;
1194 // Called after all ObjFile::parse is called for all ObjFiles. This checks
1195 // duplicate symbols and may do symbol property merge in the future.
1196 template <class ELFT
> void ObjFile
<ELFT
>::postParse() {
1197 static std::mutex mu
;
1198 ArrayRef
<Elf_Sym
> eSyms
= this->getELFSyms
<ELFT
>();
1199 for (size_t i
= firstGlobal
, end
= eSyms
.size(); i
!= end
; ++i
) {
1200 const Elf_Sym
&eSym
= eSyms
[i
];
1201 Symbol
&sym
= *symbols
[i
];
1202 uint32_t secIdx
= eSym
.st_shndx
;
1203 uint8_t binding
= eSym
.getBinding();
1204 if (LLVM_UNLIKELY(binding
!= STB_GLOBAL
&& binding
!= STB_WEAK
&&
1205 binding
!= STB_GNU_UNIQUE
))
1206 Err(ctx
) << this << ": symbol (" << i
1207 << ") has invalid binding: " << (int)binding
;
1209 // st_value of STT_TLS represents the assigned offset, not the actual
1210 // address which is used by STT_FUNC and STT_OBJECT. STT_TLS symbols can
1211 // only be referenced by special TLS relocations. It is usually an error if
1212 // a STT_TLS symbol is replaced by a non-STT_TLS symbol, vice versa.
1213 if (LLVM_UNLIKELY(sym
.isTls()) && eSym
.getType() != STT_TLS
&&
1214 eSym
.getType() != STT_NOTYPE
)
1215 Err(ctx
) << "TLS attribute mismatch: " << &sym
<< "\n>>> in " << sym
.file
1216 << "\n>>> in " << this;
1218 // Handle non-COMMON defined symbol below. !sym.file allows a symbol
1219 // assignment to redefine a symbol without an error.
1220 if (!sym
.isDefined() || secIdx
== SHN_UNDEF
)
1222 if (LLVM_UNLIKELY(secIdx
>= SHN_LORESERVE
)) {
1223 if (secIdx
== SHN_COMMON
)
1225 if (secIdx
== SHN_XINDEX
)
1226 secIdx
= check(getExtendedSymbolTableIndex
<ELFT
>(eSym
, i
, shndxTable
));
1231 if (LLVM_UNLIKELY(secIdx
>= sections
.size()))
1232 Fatal(ctx
) << this << ": invalid section index: " << secIdx
;
1233 InputSectionBase
*sec
= sections
[secIdx
];
1234 if (sec
== &InputSection::discarded
) {
1236 printTraceSymbol(Undefined
{this, sym
.getName(), sym
.binding
,
1237 sym
.stOther
, sym
.type
, secIdx
},
1240 if (sym
.file
== this) {
1241 std::lock_guard
<std::mutex
> lock(mu
);
1242 ctx
.nonPrevailingSyms
.emplace_back(&sym
, secIdx
);
1247 if (sym
.file
== this) {
1248 cast
<Defined
>(sym
).section
= sec
;
1252 if (sym
.binding
== STB_WEAK
|| binding
== STB_WEAK
)
1254 std::lock_guard
<std::mutex
> lock(mu
);
1255 ctx
.duplicates
.push_back({&sym
, this, sec
, eSym
.st_value
});
1259 // The handling of tentative definitions (COMMON symbols) in archives is murky.
1260 // A tentative definition will be promoted to a global definition if there are
1261 // no non-tentative definitions to dominate it. When we hold a tentative
1262 // definition to a symbol and are inspecting archive members for inclusion
1263 // there are 2 ways we can proceed:
1265 // 1) Consider the tentative definition a 'real' definition (ie promotion from
1266 // tentative to real definition has already happened) and not inspect
1267 // archive members for Global/Weak definitions to replace the tentative
1268 // definition. An archive member would only be included if it satisfies some
1269 // other undefined symbol. This is the behavior Gold uses.
1271 // 2) Consider the tentative definition as still undefined (ie the promotion to
1272 // a real definition happens only after all symbol resolution is done).
1273 // The linker searches archive members for STB_GLOBAL definitions to
1274 // replace the tentative definition with. This is the behavior used by
1277 // The second behavior is inherited from SysVR4, which based it on the FORTRAN
1278 // COMMON BLOCK model. This behavior is needed for proper initialization in old
1279 // (pre F90) FORTRAN code that is packaged into an archive.
1281 // The following functions search archive members for definitions to replace
1282 // tentative definitions (implementing behavior 2).
1283 static bool isBitcodeNonCommonDef(MemoryBufferRef mb
, StringRef symName
,
1284 StringRef archiveName
) {
1285 IRSymtabFile symtabFile
= check(readIRSymtab(mb
));
1286 for (const irsymtab::Reader::SymbolRef
&sym
:
1287 symtabFile
.TheReader
.symbols()) {
1288 if (sym
.isGlobal() && sym
.getName() == symName
)
1289 return !sym
.isUndefined() && !sym
.isWeak() && !sym
.isCommon();
1294 template <class ELFT
>
1295 static bool isNonCommonDef(Ctx
&ctx
, ELFKind ekind
, MemoryBufferRef mb
,
1296 StringRef symName
, StringRef archiveName
) {
1297 ObjFile
<ELFT
> *obj
= make
<ObjFile
<ELFT
>>(ctx
, ekind
, mb
, archiveName
);
1299 StringRef stringtable
= obj
->getStringTable();
1301 for (auto sym
: obj
->template getGlobalELFSyms
<ELFT
>()) {
1302 Expected
<StringRef
> name
= sym
.getName(stringtable
);
1303 if (name
&& name
.get() == symName
)
1304 return sym
.isDefined() && sym
.getBinding() == STB_GLOBAL
&&
1310 static bool isNonCommonDef(Ctx
&ctx
, MemoryBufferRef mb
, StringRef symName
,
1311 StringRef archiveName
) {
1312 switch (getELFKind(ctx
, mb
, archiveName
)) {
1314 return isNonCommonDef
<ELF32LE
>(ctx
, ELF32LEKind
, mb
, symName
, archiveName
);
1316 return isNonCommonDef
<ELF32BE
>(ctx
, ELF32BEKind
, mb
, symName
, archiveName
);
1318 return isNonCommonDef
<ELF64LE
>(ctx
, ELF64LEKind
, mb
, symName
, archiveName
);
1320 return isNonCommonDef
<ELF64BE
>(ctx
, ELF64BEKind
, mb
, symName
, archiveName
);
1322 llvm_unreachable("getELFKind");
1326 SharedFile::SharedFile(Ctx
&ctx
, MemoryBufferRef m
, StringRef defaultSoName
)
1327 : ELFFileBase(ctx
, SharedKind
, getELFKind(ctx
, m
, ""), m
),
1328 soName(defaultSoName
), isNeeded(!ctx
.arg
.asNeeded
) {}
1330 // Parse the version definitions in the object file if present, and return a
1331 // vector whose nth element contains a pointer to the Elf_Verdef for version
1332 // identifier n. Version identifiers that are not definitions map to nullptr.
1333 template <typename ELFT
>
1334 static SmallVector
<const void *, 0>
1335 parseVerdefs(const uint8_t *base
, const typename
ELFT::Shdr
*sec
) {
1339 // Build the Verdefs array by following the chain of Elf_Verdef objects
1340 // from the start of the .gnu.version_d section.
1341 SmallVector
<const void *, 0> verdefs
;
1342 const uint8_t *verdef
= base
+ sec
->sh_offset
;
1343 for (unsigned i
= 0, e
= sec
->sh_info
; i
!= e
; ++i
) {
1344 auto *curVerdef
= reinterpret_cast<const typename
ELFT::Verdef
*>(verdef
);
1345 verdef
+= curVerdef
->vd_next
;
1346 unsigned verdefIndex
= curVerdef
->vd_ndx
;
1347 if (verdefIndex
>= verdefs
.size())
1348 verdefs
.resize(verdefIndex
+ 1);
1349 verdefs
[verdefIndex
] = curVerdef
;
1354 // Parse SHT_GNU_verneed to properly set the name of a versioned undefined
1355 // symbol. We detect fatal issues which would cause vulnerabilities, but do not
1356 // implement sophisticated error checking like in llvm-readobj because the value
1357 // of such diagnostics is low.
1358 template <typename ELFT
>
1359 std::vector
<uint32_t> SharedFile::parseVerneed(const ELFFile
<ELFT
> &obj
,
1360 const typename
ELFT::Shdr
*sec
) {
1363 std::vector
<uint32_t> verneeds
;
1364 ArrayRef
<uint8_t> data
= CHECK2(obj
.getSectionContents(*sec
), this);
1365 const uint8_t *verneedBuf
= data
.begin();
1366 for (unsigned i
= 0; i
!= sec
->sh_info
; ++i
) {
1367 if (verneedBuf
+ sizeof(typename
ELFT::Verneed
) > data
.end())
1368 Fatal(ctx
) << this << " has an invalid Verneed";
1369 auto *vn
= reinterpret_cast<const typename
ELFT::Verneed
*>(verneedBuf
);
1370 const uint8_t *vernauxBuf
= verneedBuf
+ vn
->vn_aux
;
1371 for (unsigned j
= 0; j
!= vn
->vn_cnt
; ++j
) {
1372 if (vernauxBuf
+ sizeof(typename
ELFT::Vernaux
) > data
.end())
1373 Fatal(ctx
) << this << " has an invalid Vernaux";
1374 auto *aux
= reinterpret_cast<const typename
ELFT::Vernaux
*>(vernauxBuf
);
1375 if (aux
->vna_name
>= this->stringTable
.size())
1376 Fatal(ctx
) << this << " has a Vernaux with an invalid vna_name";
1377 uint16_t version
= aux
->vna_other
& VERSYM_VERSION
;
1378 if (version
>= verneeds
.size())
1379 verneeds
.resize(version
+ 1);
1380 verneeds
[version
] = aux
->vna_name
;
1381 vernauxBuf
+= aux
->vna_next
;
1383 verneedBuf
+= vn
->vn_next
;
1388 // We do not usually care about alignments of data in shared object
1389 // files because the loader takes care of it. However, if we promote a
1390 // DSO symbol to point to .bss due to copy relocation, we need to keep
1391 // the original alignment requirements. We infer it in this function.
1392 template <typename ELFT
>
1393 static uint64_t getAlignment(ArrayRef
<typename
ELFT::Shdr
> sections
,
1394 const typename
ELFT::Sym
&sym
) {
1395 uint64_t ret
= UINT64_MAX
;
1397 ret
= 1ULL << llvm::countr_zero((uint64_t)sym
.st_value
);
1398 if (0 < sym
.st_shndx
&& sym
.st_shndx
< sections
.size())
1399 ret
= std::min
<uint64_t>(ret
, sections
[sym
.st_shndx
].sh_addralign
);
1400 return (ret
> UINT32_MAX
) ? 0 : ret
;
1403 // Fully parse the shared object file.
1405 // This function parses symbol versions. If a DSO has version information,
1406 // the file has a ".gnu.version_d" section which contains symbol version
1407 // definitions. Each symbol is associated to one version through a table in
1408 // ".gnu.version" section. That table is a parallel array for the symbol
1409 // table, and each table entry contains an index in ".gnu.version_d".
1411 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
1412 // VER_NDX_GLOBAL. There's no table entry for these special versions in
1413 // ".gnu.version_d".
1415 // The file format for symbol versioning is perhaps a bit more complicated
1416 // than necessary, but you can easily understand the code if you wrap your
1417 // head around the data structure described above.
1418 template <class ELFT
> void SharedFile::parse() {
1419 using Elf_Dyn
= typename
ELFT::Dyn
;
1420 using Elf_Shdr
= typename
ELFT::Shdr
;
1421 using Elf_Sym
= typename
ELFT::Sym
;
1422 using Elf_Verdef
= typename
ELFT::Verdef
;
1423 using Elf_Versym
= typename
ELFT::Versym
;
1425 ArrayRef
<Elf_Dyn
> dynamicTags
;
1426 const ELFFile
<ELFT
> obj
= this->getObj
<ELFT
>();
1427 ArrayRef
<Elf_Shdr
> sections
= getELFShdrs
<ELFT
>();
1429 const Elf_Shdr
*versymSec
= nullptr;
1430 const Elf_Shdr
*verdefSec
= nullptr;
1431 const Elf_Shdr
*verneedSec
= nullptr;
1432 symbols
= std::make_unique
<Symbol
*[]>(numSymbols
);
1434 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
1435 for (const Elf_Shdr
&sec
: sections
) {
1436 switch (sec
.sh_type
) {
1441 CHECK2(obj
.template getSectionContentsAsArray
<Elf_Dyn
>(sec
), this);
1443 case SHT_GNU_versym
:
1446 case SHT_GNU_verdef
:
1449 case SHT_GNU_verneed
:
1455 if (versymSec
&& numSymbols
== 0) {
1456 ErrAlways(ctx
) << "SHT_GNU_versym should be associated with symbol table";
1460 // Search for a DT_SONAME tag to initialize this->soName.
1461 for (const Elf_Dyn
&dyn
: dynamicTags
) {
1462 if (dyn
.d_tag
== DT_NEEDED
) {
1463 uint64_t val
= dyn
.getVal();
1464 if (val
>= this->stringTable
.size())
1465 Fatal(ctx
) << this << ": invalid DT_NEEDED entry";
1466 dtNeeded
.push_back(this->stringTable
.data() + val
);
1467 } else if (dyn
.d_tag
== DT_SONAME
) {
1468 uint64_t val
= dyn
.getVal();
1469 if (val
>= this->stringTable
.size())
1470 Fatal(ctx
) << this << ": invalid DT_SONAME entry";
1471 soName
= this->stringTable
.data() + val
;
1475 // DSOs are uniquified not by filename but by soname.
1476 StringSaver
&ss
= ctx
.saver
;
1477 DenseMap
<CachedHashStringRef
, SharedFile
*>::iterator it
;
1479 std::tie(it
, wasInserted
) =
1480 ctx
.symtab
->soNames
.try_emplace(CachedHashStringRef(soName
), this);
1482 // If a DSO appears more than once on the command line with and without
1483 // --as-needed, --no-as-needed takes precedence over --as-needed because a
1484 // user can add an extra DSO with --no-as-needed to force it to be added to
1485 // the dependency list.
1486 it
->second
->isNeeded
|= isNeeded
;
1490 ctx
.sharedFiles
.push_back(this);
1492 verdefs
= parseVerdefs
<ELFT
>(obj
.base(), verdefSec
);
1493 std::vector
<uint32_t> verneeds
= parseVerneed
<ELFT
>(obj
, verneedSec
);
1495 // Parse ".gnu.version" section which is a parallel array for the symbol
1496 // table. If a given file doesn't have a ".gnu.version" section, we use
1498 size_t size
= numSymbols
- firstGlobal
;
1499 std::vector
<uint16_t> versyms(size
, VER_NDX_GLOBAL
);
1501 ArrayRef
<Elf_Versym
> versym
=
1502 CHECK2(obj
.template getSectionContentsAsArray
<Elf_Versym
>(*versymSec
),
1504 .slice(firstGlobal
);
1505 for (size_t i
= 0; i
< size
; ++i
)
1506 versyms
[i
] = versym
[i
].vs_index
;
1509 // System libraries can have a lot of symbols with versions. Using a
1510 // fixed buffer for computing the versions name (foo@ver) can save a
1511 // lot of allocations.
1512 SmallString
<0> versionedNameBuffer
;
1514 // Add symbols to the symbol table.
1515 ArrayRef
<Elf_Sym
> syms
= this->getGlobalELFSyms
<ELFT
>();
1516 for (size_t i
= 0, e
= syms
.size(); i
!= e
; ++i
) {
1517 const Elf_Sym
&sym
= syms
[i
];
1519 // ELF spec requires that all local symbols precede weak or global
1520 // symbols in each symbol table, and the index of first non-local symbol
1521 // is stored to sh_info. If a local symbol appears after some non-local
1522 // symbol, that's a violation of the spec.
1523 StringRef name
= CHECK2(sym
.getName(stringTable
), this);
1524 if (sym
.getBinding() == STB_LOCAL
) {
1525 Err(ctx
) << this << ": invalid local symbol '" << name
1526 << "' in global part of symbol table";
1530 const uint16_t ver
= versyms
[i
], idx
= ver
& ~VERSYM_HIDDEN
;
1531 if (sym
.isUndefined()) {
1532 // For unversioned undefined symbols, VER_NDX_GLOBAL makes more sense but
1533 // as of binutils 2.34, GNU ld produces VER_NDX_LOCAL.
1534 if (ver
!= VER_NDX_LOCAL
&& ver
!= VER_NDX_GLOBAL
) {
1535 if (idx
>= verneeds
.size()) {
1536 ErrAlways(ctx
) << "corrupt input file: version need index " << idx
1537 << " for symbol " << name
1538 << " is out of bounds\n>>> defined in " << this;
1541 StringRef verName
= stringTable
.data() + verneeds
[idx
];
1542 versionedNameBuffer
.clear();
1543 name
= ss
.save((name
+ "@" + verName
).toStringRef(versionedNameBuffer
));
1545 Symbol
*s
= ctx
.symtab
->addSymbol(
1546 Undefined
{this, name
, sym
.getBinding(), sym
.st_other
, sym
.getType()});
1547 s
->exportDynamic
= true;
1548 if (sym
.getBinding() != STB_WEAK
&&
1549 ctx
.arg
.unresolvedSymbolsInShlib
!= UnresolvedPolicy::Ignore
)
1550 requiredSymbols
.push_back(s
);
1554 if (ver
== VER_NDX_LOCAL
||
1555 (ver
!= VER_NDX_GLOBAL
&& idx
>= verdefs
.size())) {
1556 // In GNU ld < 2.31 (before 3be08ea4728b56d35e136af4e6fd3086ade17764), the
1557 // MIPS port puts _gp_disp symbol into DSO files and incorrectly assigns
1558 // VER_NDX_LOCAL. Workaround this bug.
1559 if (ctx
.arg
.emachine
== EM_MIPS
&& name
== "_gp_disp")
1561 ErrAlways(ctx
) << "corrupt input file: version definition index " << idx
1562 << " for symbol " << name
1563 << " is out of bounds\n>>> defined in " << this;
1567 uint32_t alignment
= getAlignment
<ELFT
>(sections
, sym
);
1569 auto *s
= ctx
.symtab
->addSymbol(
1570 SharedSymbol
{*this, name
, sym
.getBinding(), sym
.st_other
,
1571 sym
.getType(), sym
.st_value
, sym
.st_size
, alignment
});
1572 s
->dsoDefined
= true;
1573 if (s
->file
== this)
1577 // Also add the symbol with the versioned name to handle undefined symbols
1578 // with explicit versions.
1579 if (ver
== VER_NDX_GLOBAL
)
1583 stringTable
.data() +
1584 reinterpret_cast<const Elf_Verdef
*>(verdefs
[idx
])->getAux()->vda_name
;
1585 versionedNameBuffer
.clear();
1586 name
= (name
+ "@" + verName
).toStringRef(versionedNameBuffer
);
1587 auto *s
= ctx
.symtab
->addSymbol(
1588 SharedSymbol
{*this, ss
.save(name
), sym
.getBinding(), sym
.st_other
,
1589 sym
.getType(), sym
.st_value
, sym
.st_size
, alignment
});
1590 s
->dsoDefined
= true;
1591 if (s
->file
== this)
1596 static ELFKind
getBitcodeELFKind(const Triple
&t
) {
1597 if (t
.isLittleEndian())
1598 return t
.isArch64Bit() ? ELF64LEKind
: ELF32LEKind
;
1599 return t
.isArch64Bit() ? ELF64BEKind
: ELF32BEKind
;
1602 static uint16_t getBitcodeMachineKind(Ctx
&ctx
, StringRef path
,
1604 switch (t
.getArch()) {
1605 case Triple::aarch64
:
1606 case Triple::aarch64_be
:
1608 case Triple::amdgcn
:
1614 case Triple::thumbeb
:
1618 case Triple::hexagon
:
1620 case Triple::loongarch32
:
1621 case Triple::loongarch64
:
1622 return EM_LOONGARCH
;
1624 case Triple::mipsel
:
1625 case Triple::mips64
:
1626 case Triple::mips64el
:
1628 case Triple::msp430
:
1634 case Triple::ppc64le
:
1636 case Triple::riscv32
:
1637 case Triple::riscv64
:
1639 case Triple::sparcv9
:
1641 case Triple::systemz
:
1644 return t
.isOSIAMCU() ? EM_IAMCU
: EM_386
;
1645 case Triple::x86_64
:
1648 ErrAlways(ctx
) << path
1649 << ": could not infer e_machine from bitcode target triple "
1655 static uint8_t getOsAbi(const Triple
&t
) {
1656 switch (t
.getOS()) {
1657 case Triple::AMDHSA
:
1658 return ELF::ELFOSABI_AMDGPU_HSA
;
1659 case Triple::AMDPAL
:
1660 return ELF::ELFOSABI_AMDGPU_PAL
;
1661 case Triple::Mesa3D
:
1662 return ELF::ELFOSABI_AMDGPU_MESA3D
;
1664 return ELF::ELFOSABI_NONE
;
1668 BitcodeFile::BitcodeFile(Ctx
&ctx
, MemoryBufferRef mb
, StringRef archiveName
,
1669 uint64_t offsetInArchive
, bool lazy
)
1670 : InputFile(ctx
, BitcodeKind
, mb
) {
1671 this->archiveName
= archiveName
;
1674 std::string path
= mb
.getBufferIdentifier().str();
1675 if (ctx
.arg
.thinLTOIndexOnly
)
1676 path
= replaceThinLTOSuffix(ctx
, mb
.getBufferIdentifier());
1678 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1679 // name. If two archives define two members with the same name, this
1680 // causes a collision which result in only one of the objects being taken
1681 // into consideration at LTO time (which very likely causes undefined
1682 // symbols later in the link stage). So we append file offset to make
1684 StringSaver
&ss
= ctx
.saver
;
1685 StringRef name
= archiveName
.empty()
1687 : ss
.save(archiveName
+ "(" + path::filename(path
) +
1688 " at " + utostr(offsetInArchive
) + ")");
1689 MemoryBufferRef
mbref(mb
.getBuffer(), name
);
1691 obj
= CHECK2(lto::InputFile::create(mbref
), this);
1693 Triple
t(obj
->getTargetTriple());
1694 ekind
= getBitcodeELFKind(t
);
1695 emachine
= getBitcodeMachineKind(ctx
, mb
.getBufferIdentifier(), t
);
1696 osabi
= getOsAbi(t
);
1699 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility
) {
1700 switch (gvVisibility
) {
1701 case GlobalValue::DefaultVisibility
:
1703 case GlobalValue::HiddenVisibility
:
1705 case GlobalValue::ProtectedVisibility
:
1706 return STV_PROTECTED
;
1708 llvm_unreachable("unknown visibility");
1711 static void createBitcodeSymbol(Ctx
&ctx
, Symbol
*&sym
,
1712 const lto::InputFile::Symbol
&objSym
,
1714 uint8_t binding
= objSym
.isWeak() ? STB_WEAK
: STB_GLOBAL
;
1715 uint8_t type
= objSym
.isTLS() ? STT_TLS
: STT_NOTYPE
;
1716 uint8_t visibility
= mapVisibility(objSym
.getVisibility());
1719 // Symbols can be duplicated in bitcode files because of '#include' and
1720 // linkonce_odr. Use uniqueSaver to save symbol names for de-duplication.
1721 // Update objSym.Name to reference (via StringRef) the string saver's copy;
1722 // this way LTO can reference the same string saver's copy rather than
1723 // keeping copies of its own.
1724 objSym
.Name
= ctx
.uniqueSaver
.save(objSym
.getName());
1725 sym
= ctx
.symtab
->insert(objSym
.getName());
1728 if (objSym
.isUndefined()) {
1729 Undefined
newSym(&f
, StringRef(), binding
, visibility
, type
);
1730 sym
->resolve(ctx
, newSym
);
1731 sym
->referenced
= true;
1735 if (objSym
.isCommon()) {
1736 sym
->resolve(ctx
, CommonSymbol
{ctx
, &f
, StringRef(), binding
, visibility
,
1737 STT_OBJECT
, objSym
.getCommonAlignment(),
1738 objSym
.getCommonSize()});
1740 Defined
newSym(ctx
, &f
, StringRef(), binding
, visibility
, type
, 0, 0,
1742 // The definition can be omitted if all bitcode definitions satisfy
1743 // `canBeOmittedFromSymbolTable()` and isUsedInRegularObj is false.
1744 // The latter condition is tested in Symbol::includeInDynsym.
1745 sym
->ltoCanOmit
= objSym
.canBeOmittedFromSymbolTable() &&
1746 (!sym
->isDefined() || sym
->ltoCanOmit
);
1747 sym
->resolve(ctx
, newSym
);
1751 void BitcodeFile::parse() {
1752 for (std::pair
<StringRef
, Comdat::SelectionKind
> s
: obj
->getComdatTable()) {
1753 keptComdats
.push_back(
1754 s
.second
== Comdat::NoDeduplicate
||
1755 ctx
.symtab
->comdatGroups
.try_emplace(CachedHashStringRef(s
.first
), this)
1759 if (numSymbols
== 0) {
1760 numSymbols
= obj
->symbols().size();
1761 symbols
= std::make_unique
<Symbol
*[]>(numSymbols
);
1763 // Process defined symbols first. See the comment in
1764 // ObjFile<ELFT>::initializeSymbols.
1765 for (auto [i
, irSym
] : llvm::enumerate(obj
->symbols()))
1766 if (!irSym
.isUndefined())
1767 createBitcodeSymbol(ctx
, symbols
[i
], irSym
, *this);
1768 for (auto [i
, irSym
] : llvm::enumerate(obj
->symbols()))
1769 if (irSym
.isUndefined())
1770 createBitcodeSymbol(ctx
, symbols
[i
], irSym
, *this);
1772 for (auto l
: obj
->getDependentLibraries())
1773 addDependentLibrary(ctx
, l
, this);
1776 void BitcodeFile::parseLazy() {
1777 numSymbols
= obj
->symbols().size();
1778 symbols
= std::make_unique
<Symbol
*[]>(numSymbols
);
1779 for (auto [i
, irSym
] : llvm::enumerate(obj
->symbols())) {
1780 // Symbols can be duplicated in bitcode files because of '#include' and
1781 // linkonce_odr. Use uniqueSaver to save symbol names for de-duplication.
1782 // Update objSym.Name to reference (via StringRef) the string saver's copy;
1783 // this way LTO can reference the same string saver's copy rather than
1784 // keeping copies of its own.
1785 irSym
.Name
= ctx
.uniqueSaver
.save(irSym
.getName());
1786 if (!irSym
.isUndefined()) {
1787 auto *sym
= ctx
.symtab
->insert(irSym
.getName());
1788 sym
->resolve(ctx
, LazySymbol
{*this});
1794 void BitcodeFile::postParse() {
1795 for (auto [i
, irSym
] : llvm::enumerate(obj
->symbols())) {
1796 const Symbol
&sym
= *symbols
[i
];
1797 if (sym
.file
== this || !sym
.isDefined() || irSym
.isUndefined() ||
1798 irSym
.isCommon() || irSym
.isWeak())
1800 int c
= irSym
.getComdatIndex();
1801 if (c
!= -1 && !keptComdats
[c
])
1803 reportDuplicate(ctx
, sym
, this, nullptr, 0);
1807 void BinaryFile::parse() {
1808 ArrayRef
<uint8_t> data
= arrayRefFromStringRef(mb
.getBuffer());
1810 make
<InputSection
>(this, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
,
1811 /*addralign=*/8, /*entsize=*/0, data
);
1812 sections
.push_back(section
);
1814 // For each input file foo that is embedded to a result as a binary
1815 // blob, we define _binary_foo_{start,end,size} symbols, so that
1816 // user programs can access blobs by name. Non-alphanumeric
1817 // characters in a filename are replaced with underscore.
1818 std::string s
= "_binary_" + mb
.getBufferIdentifier().str();
1823 llvm::StringSaver
&ss
= ctx
.saver
;
1824 ctx
.symtab
->addAndCheckDuplicate(
1825 ctx
, Defined
{ctx
, this, ss
.save(s
+ "_start"), STB_GLOBAL
, STV_DEFAULT
,
1826 STT_OBJECT
, 0, 0, section
});
1827 ctx
.symtab
->addAndCheckDuplicate(
1828 ctx
, Defined
{ctx
, this, ss
.save(s
+ "_end"), STB_GLOBAL
, STV_DEFAULT
,
1829 STT_OBJECT
, data
.size(), 0, section
});
1830 ctx
.symtab
->addAndCheckDuplicate(
1831 ctx
, Defined
{ctx
, this, ss
.save(s
+ "_size"), STB_GLOBAL
, STV_DEFAULT
,
1832 STT_OBJECT
, data
.size(), 0, nullptr});
1835 InputFile
*elf::createInternalFile(Ctx
&ctx
, StringRef name
) {
1837 make
<InputFile
>(ctx
, InputFile::InternalKind
, MemoryBufferRef("", name
));
1838 // References from an internal file do not lead to --warn-backrefs
1844 std::unique_ptr
<ELFFileBase
> elf::createObjFile(Ctx
&ctx
, MemoryBufferRef mb
,
1845 StringRef archiveName
,
1847 std::unique_ptr
<ELFFileBase
> f
;
1848 switch (getELFKind(ctx
, mb
, archiveName
)) {
1850 f
= std::make_unique
<ObjFile
<ELF32LE
>>(ctx
, ELF32LEKind
, mb
, archiveName
);
1853 f
= std::make_unique
<ObjFile
<ELF32BE
>>(ctx
, ELF32BEKind
, mb
, archiveName
);
1856 f
= std::make_unique
<ObjFile
<ELF64LE
>>(ctx
, ELF64LEKind
, mb
, archiveName
);
1859 f
= std::make_unique
<ObjFile
<ELF64BE
>>(ctx
, ELF64BEKind
, mb
, archiveName
);
1862 llvm_unreachable("getELFKind");
1869 template <class ELFT
> void ObjFile
<ELFT
>::parseLazy() {
1870 const ArrayRef
<typename
ELFT::Sym
> eSyms
= this->getELFSyms
<ELFT
>();
1871 numSymbols
= eSyms
.size();
1872 symbols
= std::make_unique
<Symbol
*[]>(numSymbols
);
1874 // resolve() may trigger this->extract() if an existing symbol is an undefined
1875 // symbol. If that happens, this function has served its purpose, and we can
1876 // exit from the loop early.
1877 auto *symtab
= ctx
.symtab
.get();
1878 for (size_t i
= firstGlobal
, end
= eSyms
.size(); i
!= end
; ++i
) {
1879 if (eSyms
[i
].st_shndx
== SHN_UNDEF
)
1881 symbols
[i
] = symtab
->insert(CHECK2(eSyms
[i
].getName(stringTable
), this));
1882 symbols
[i
]->resolve(ctx
, LazySymbol
{*this});
1888 bool InputFile::shouldExtractForCommon(StringRef name
) const {
1889 if (isa
<BitcodeFile
>(this))
1890 return isBitcodeNonCommonDef(mb
, name
, archiveName
);
1892 return isNonCommonDef(ctx
, mb
, name
, archiveName
);
1895 std::string
elf::replaceThinLTOSuffix(Ctx
&ctx
, StringRef path
) {
1896 auto [suffix
, repl
] = ctx
.arg
.thinLTOObjectSuffixReplace
;
1897 if (path
.consume_back(suffix
))
1898 return (path
+ repl
).str();
1899 return std::string(path
);
1902 template class elf::ObjFile
<ELF32LE
>;
1903 template class elf::ObjFile
<ELF32BE
>;
1904 template class elf::ObjFile
<ELF64LE
>;
1905 template class elf::ObjFile
<ELF64BE
>;
1907 template void SharedFile::parse
<ELF32LE
>();
1908 template void SharedFile::parse
<ELF32BE
>();
1909 template void SharedFile::parse
<ELF64LE
>();
1910 template void SharedFile::parse
<ELF64BE
>();