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