1 //===- InputFiles.cpp -----------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "InputFiles.h"
12 #include "InputSection.h"
13 #include "LinkerScript.h"
15 #include "SymbolTable.h"
17 #include "SyntheticSections.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/LTO/LTO.h"
24 #include "llvm/MC/StringTableBuilder.h"
25 #include "llvm/Object/ELFObjectFile.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/TarWriter.h"
28 #include "llvm/Support/raw_ostream.h"
31 using namespace llvm::ELF;
32 using namespace llvm::object;
33 using namespace llvm::sys::fs;
36 using namespace lld::elf;
40 InputFile::InputFile(Kind K, MemoryBufferRef M) : MB(M), FileKind(K) {}
43 // In ELF object file all section addresses are zero. If we have multiple
44 // .text sections (when using -ffunction-section or comdat group) then
45 // LLVM DWARF parser will not be able to parse .debug_line correctly, unless
46 // we assign each section some unique address. This callback method assigns
47 // each section an address equal to its offset in ELF object file.
48 class ObjectInfo : public LoadedObjectInfo {
50 uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
51 return static_cast<const ELFSectionRef &>(Sec).getOffset();
53 std::unique_ptr<LoadedObjectInfo> clone() const override {
54 return std::unique_ptr<LoadedObjectInfo>();
59 Optional<MemoryBufferRef> elf::readFile(StringRef Path) {
61 auto MBOrErr = MemoryBuffer::getFile(Path);
62 if (auto EC = MBOrErr.getError()) {
63 error("cannot open " + Path + ": " + EC.message());
67 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
68 MemoryBufferRef MBRef = MB->getMemBufferRef();
69 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
72 Tar->append(relativeToRoot(Path), MBRef.getBuffer());
76 template <class ELFT> void elf::ObjectFile<ELFT>::initializeDwarfLine() {
77 std::unique_ptr<object::ObjectFile> Obj =
78 check(object::ObjectFile::createObjectFile(this->MB), toString(this));
81 DWARFContextInMemory Dwarf(*Obj, &ObjInfo);
82 DwarfLine.reset(new DWARFDebugLine(&Dwarf.getLineSection().Relocs));
83 DataExtractor LineData(Dwarf.getLineSection().Data, Config->IsLE,
86 // The second parameter is offset in .debug_line section
87 // for compilation unit (CU) of interest. We have only one
88 // CU (object file), so offset is always 0.
89 DwarfLine->getOrParseLineTable(LineData, 0);
92 // Returns source line information for a given offset
93 // using DWARF debug info.
95 Optional<DILineInfo> elf::ObjectFile<ELFT>::getDILineInfo(InputSectionBase *S,
98 initializeDwarfLine();
100 // The offset to CU is 0.
101 const DWARFDebugLine::LineTable *Tbl = DwarfLine->getLineTable(0);
105 // Use fake address calcuated by adding section file offset and offset in
106 // section. See comments for ObjectInfo class.
108 Tbl->getFileLineInfoForAddress(
109 S->getOffsetInFile() + Offset, nullptr,
110 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info);
116 // Returns source line information for a given offset
117 // using DWARF debug info.
118 template <class ELFT>
119 std::string elf::ObjectFile<ELFT>::getLineInfo(InputSectionBase *S,
121 if (Optional<DILineInfo> Info = getDILineInfo(S, Offset))
122 return Info->FileName + ":" + std::to_string(Info->Line);
126 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
127 std::string lld::toString(const InputFile *F) {
131 if (F->ToStringCache.empty()) {
132 if (F->ArchiveName.empty())
133 F->ToStringCache = F->getName();
135 F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str();
137 return F->ToStringCache;
140 template <class ELFT>
141 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
142 if (ELFT::TargetEndianness == support::little)
143 EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
145 EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
147 EMachine = getObj().getHeader()->e_machine;
148 OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
151 template <class ELFT>
152 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalSymbols() {
153 return makeArrayRef(Symbols.begin() + FirstNonLocal, Symbols.end());
156 template <class ELFT>
157 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
158 return check(getObj().getSectionIndex(&Sym, Symbols, SymtabSHNDX),
162 template <class ELFT>
163 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
164 const Elf_Shdr *Symtab) {
165 FirstNonLocal = Symtab->sh_info;
166 Symbols = check(getObj().symbols(Symtab), toString(this));
167 if (FirstNonLocal == 0 || FirstNonLocal > Symbols.size())
168 fatal(toString(this) + ": invalid sh_info in symbol table");
170 StringTable = check(getObj().getStringTableForSymtab(*Symtab, Sections),
174 template <class ELFT>
175 elf::ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M, StringRef ArchiveName)
176 : ELFFileBase<ELFT>(Base::ObjectKind, M) {
177 this->ArchiveName = ArchiveName;
180 template <class ELFT>
181 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getLocalSymbols() {
182 if (this->SymbolBodies.empty())
183 return this->SymbolBodies;
184 return makeArrayRef(this->SymbolBodies).slice(1, this->FirstNonLocal - 1);
187 template <class ELFT>
188 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getSymbols() {
189 if (this->SymbolBodies.empty())
190 return this->SymbolBodies;
191 return makeArrayRef(this->SymbolBodies).slice(1);
194 template <class ELFT>
195 void elf::ObjectFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
196 // Read section and symbol tables.
197 initializeSections(ComdatGroups);
201 // Sections with SHT_GROUP and comdat bits define comdat section groups.
202 // They are identified and deduplicated by group name. This function
203 // returns a group name.
204 template <class ELFT>
206 elf::ObjectFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
207 const Elf_Shdr &Sec) {
208 // Group signatures are stored as symbol names in object files.
209 // sh_info contains a symbol index, so we fetch a symbol and read its name.
210 if (this->Symbols.empty())
213 check(object::getSection<ELFT>(Sections, Sec.sh_link), toString(this)));
215 const Elf_Sym *Sym = check(
216 object::getSymbol<ELFT>(this->Symbols, Sec.sh_info), toString(this));
217 StringRef Signature = check(Sym->getName(this->StringTable), toString(this));
219 // As a special case, if a symbol is a section symbol and has no name,
220 // we use a section name as a signature.
222 // Such SHT_GROUP sections are invalid from the perspective of the ELF
223 // standard, but GNU gold 1.14 (the neweset version as of July 2017) or
224 // older produce such sections as outputs for the -r option, so we need
225 // a bug-compatibility.
226 if (Signature.empty() && Sym->getType() == STT_SECTION)
227 return getSectionName(Sec);
231 template <class ELFT>
232 ArrayRef<typename elf::ObjectFile<ELFT>::Elf_Word>
233 elf::ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
234 const ELFFile<ELFT> &Obj = this->getObj();
235 ArrayRef<Elf_Word> Entries = check(
236 Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), toString(this));
237 if (Entries.empty() || Entries[0] != GRP_COMDAT)
238 fatal(toString(this) + ": unsupported SHT_GROUP format");
239 return Entries.slice(1);
242 template <class ELFT>
243 bool elf::ObjectFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
244 // We don't merge sections if -O0 (default is -O1). This makes sometimes
245 // the linker significantly faster, although the output will be bigger.
246 if (Config->Optimize == 0)
249 // Do not merge sections if generating a relocatable object. It makes
250 // the code simpler because we do not need to update relocation addends
251 // to reflect changes introduced by merging. Instead of that we write
252 // such "merge" sections into separate OutputSections and keep SHF_MERGE
253 // / SHF_STRINGS flags and sh_entsize value to be able to perform merging
254 // later during a final linking.
255 if (Config->Relocatable)
258 // A mergeable section with size 0 is useless because they don't have
259 // any data to merge. A mergeable string section with size 0 can be
260 // argued as invalid because it doesn't end with a null character.
261 // We'll avoid a mess by handling them as if they were non-mergeable.
262 if (Sec.sh_size == 0)
265 // Check for sh_entsize. The ELF spec is not clear about the zero
266 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
267 // the section does not hold a table of fixed-size entries". We know
268 // that Rust 1.13 produces a string mergeable section with a zero
269 // sh_entsize. Here we just accept it rather than being picky about it.
270 uint64_t EntSize = Sec.sh_entsize;
273 if (Sec.sh_size % EntSize)
274 fatal(toString(this) +
275 ": SHF_MERGE section size must be a multiple of sh_entsize");
277 uint64_t Flags = Sec.sh_flags;
278 if (!(Flags & SHF_MERGE))
280 if (Flags & SHF_WRITE)
281 fatal(toString(this) + ": writable SHF_MERGE section is not supported");
283 // Don't try to merge if the alignment is larger than the sh_entsize and this
284 // is not SHF_STRINGS.
286 // Since this is not a SHF_STRINGS, we would need to pad after every entity.
287 // It would be equivalent for the producer of the .o to just set a larger
289 if (Flags & SHF_STRINGS)
292 return Sec.sh_addralign <= EntSize;
295 template <class ELFT>
296 void elf::ObjectFile<ELFT>::initializeSections(
297 DenseSet<CachedHashStringRef> &ComdatGroups) {
298 const ELFFile<ELFT> &Obj = this->getObj();
300 ArrayRef<Elf_Shdr> ObjSections =
301 check(this->getObj().sections(), toString(this));
302 uint64_t Size = ObjSections.size();
303 this->Sections.resize(Size);
304 this->SectionStringTable =
305 check(Obj.getSectionStringTable(ObjSections), toString(this));
307 for (size_t I = 0, E = ObjSections.size(); I < E; I++) {
308 if (this->Sections[I] == &InputSection::Discarded)
310 const Elf_Shdr &Sec = ObjSections[I];
312 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
313 // if -r is given, we'll let the final link discard such sections.
314 // This is compatible with GNU.
315 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
316 this->Sections[I] = &InputSection::Discarded;
320 switch (Sec.sh_type) {
322 // De-duplicate section groups by their signatures.
323 StringRef Signature = getShtGroupSignature(ObjSections, Sec);
324 bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second;
325 this->Sections[I] = &InputSection::Discarded;
327 // If it is a new section group, we want to keep group members.
328 // Group leader sections, which contain indices of group members, are
329 // discarded because they are useless beyond this point. The only
330 // exception is the -r option because in order to produce re-linkable
331 // object files, we want to pass through basically everything.
333 if (Config->Relocatable)
334 this->Sections[I] = createInputSection(Sec);
338 // Otherwise, discard group members.
339 for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
340 if (SecIndex >= Size)
341 fatal(toString(this) +
342 ": invalid section index in group: " + Twine(SecIndex));
343 this->Sections[SecIndex] = &InputSection::Discarded;
348 this->initSymtab(ObjSections, &Sec);
350 case SHT_SYMTAB_SHNDX:
352 check(Obj.getSHNDXTable(Sec, ObjSections), toString(this));
358 this->Sections[I] = createInputSection(Sec);
361 // .ARM.exidx sections have a reverse dependency on the InputSection they
362 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
363 if (Sec.sh_flags & SHF_LINK_ORDER) {
364 if (Sec.sh_link >= this->Sections.size())
365 fatal(toString(this) + ": invalid sh_link index: " +
367 this->Sections[Sec.sh_link]->DependentSections.push_back(
373 template <class ELFT>
374 InputSectionBase *elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
375 uint32_t Idx = Sec.sh_info;
376 if (Idx >= this->Sections.size())
377 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
378 InputSectionBase *Target = this->Sections[Idx];
380 // Strictly speaking, a relocation section must be included in the
381 // group of the section it relocates. However, LLVM 3.3 and earlier
382 // would fail to do so, so we gracefully handle that case.
383 if (Target == &InputSection::Discarded)
387 fatal(toString(this) + ": unsupported relocation reference");
391 // Create a regular InputSection class that has the same contents
392 // as a given section.
393 InputSectionBase *toRegularSection(MergeInputSection *Sec) {
394 auto *Ret = make<InputSection>(Sec->Flags, Sec->Type, Sec->Alignment,
395 Sec->Data, Sec->Name);
396 Ret->File = Sec->File;
400 template <class ELFT>
402 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
403 StringRef Name = getSectionName(Sec);
405 switch (Sec.sh_type) {
406 case SHT_ARM_ATTRIBUTES:
407 // FIXME: ARM meta-data section. Retain the first attribute section
408 // we see. The eglibc ARM dynamic loaders require the presence of an
409 // attribute section for dlopen to work.
410 // In a full implementation we would merge all attribute sections.
411 if (InX::ARMAttributes == nullptr) {
412 InX::ARMAttributes = make<InputSection>(this, &Sec, Name);
413 return InX::ARMAttributes;
415 return &InputSection::Discarded;
418 // Find the relocation target section and associate this
419 // section with it. Target can be discarded, for example
420 // if it is a duplicated member of SHT_GROUP section, we
421 // do not create or proccess relocatable sections then.
422 InputSectionBase *Target = getRelocTarget(Sec);
426 // This section contains relocation information.
427 // If -r is given, we do not interpret or apply relocation
428 // but just copy relocation sections to output.
429 if (Config->Relocatable)
430 return make<InputSection>(this, &Sec, Name);
432 if (Target->FirstRelocation)
433 fatal(toString(this) +
434 ": multiple relocation sections to one section are not supported");
436 // Mergeable sections with relocations are tricky because relocations
437 // need to be taken into account when comparing section contents for
438 // merging. It's not worth supporting such mergeable sections because
439 // they are rare and it'd complicates the internal design (we usually
440 // have to determine if two sections are mergeable early in the link
441 // process much before applying relocations). We simply handle mergeable
442 // sections with relocations as non-mergeable.
443 if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
444 Target = toRegularSection(MS);
445 this->Sections[Sec.sh_info] = Target;
448 size_t NumRelocations;
449 if (Sec.sh_type == SHT_RELA) {
450 ArrayRef<Elf_Rela> Rels =
451 check(this->getObj().relas(&Sec), toString(this));
452 Target->FirstRelocation = Rels.begin();
453 NumRelocations = Rels.size();
454 Target->AreRelocsRela = true;
456 ArrayRef<Elf_Rel> Rels = check(this->getObj().rels(&Sec), toString(this));
457 Target->FirstRelocation = Rels.begin();
458 NumRelocations = Rels.size();
459 Target->AreRelocsRela = false;
461 assert(isUInt<31>(NumRelocations));
462 Target->NumRelocations = NumRelocations;
464 // Relocation sections processed by the linker are usually removed
465 // from the output, so returning `nullptr` for the normal case.
466 // However, if -emit-relocs is given, we need to leave them in the output.
467 // (Some post link analysis tools need this information.)
468 if (Config->EmitRelocs) {
469 InputSection *RelocSec = make<InputSection>(this, &Sec, Name);
470 // We will not emit relocation section if target was discarded.
471 Target->DependentSections.push_back(RelocSec);
478 // The GNU linker uses .note.GNU-stack section as a marker indicating
479 // that the code in the object file does not expect that the stack is
480 // executable (in terms of NX bit). If all input files have the marker,
481 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
482 // make the stack non-executable. Most object files have this section as
485 // But making the stack non-executable is a norm today for security
486 // reasons. Failure to do so may result in a serious security issue.
487 // Therefore, we make LLD always add PT_GNU_STACK unless it is
488 // explicitly told to do otherwise (by -z execstack). Because the stack
489 // executable-ness is controlled solely by command line options,
490 // .note.GNU-stack sections are simply ignored.
491 if (Name == ".note.GNU-stack")
492 return &InputSection::Discarded;
494 // Split stacks is a feature to support a discontiguous stack. At least
495 // as of 2017, it seems that the feature is not being used widely.
496 // Only GNU gold supports that. We don't. For the details about that,
497 // see https://gcc.gnu.org/wiki/SplitStacks
498 if (Name == ".note.GNU-split-stack") {
499 error(toString(this) +
500 ": object file compiled with -fsplit-stack is not supported");
501 return &InputSection::Discarded;
504 if (Config->Strip != StripPolicy::None && Name.startswith(".debug"))
505 return &InputSection::Discarded;
507 // If -gdb-index is given, LLD creates .gdb_index section, and that
508 // section serves the same purpose as .debug_gnu_pub{names,types} sections.
509 // If that's the case, we want to eliminate .debug_gnu_pub{names,types}
510 // because they are redundant and can waste large amount of disk space
511 // (for example, they are about 400 MiB in total for a clang debug build.)
512 if (Config->GdbIndex &&
513 (Name == ".debug_gnu_pubnames" || Name == ".debug_gnu_pubtypes"))
514 return &InputSection::Discarded;
516 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
517 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
518 // sections. Drop those sections to avoid duplicate symbol errors.
519 // FIXME: This is glibc PR20543, we should remove this hack once that has been
520 // fixed for a while.
521 if (Name.startswith(".gnu.linkonce."))
522 return &InputSection::Discarded;
524 // The linker merges EH (exception handling) frames and creates a
525 // .eh_frame_hdr section for runtime. So we handle them with a special
526 // class. For relocatable outputs, they are just passed through.
527 if (Name == ".eh_frame" && !Config->Relocatable)
528 return make<EhInputSection>(this, &Sec, Name);
530 if (shouldMerge(Sec))
531 return make<MergeInputSection>(this, &Sec, Name);
532 return make<InputSection>(this, &Sec, Name);
535 template <class ELFT>
536 StringRef elf::ObjectFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
537 return check(this->getObj().getSectionName(&Sec, SectionStringTable),
541 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() {
542 SymbolBodies.reserve(this->Symbols.size());
543 for (const Elf_Sym &Sym : this->Symbols)
544 SymbolBodies.push_back(createSymbolBody(&Sym));
547 template <class ELFT>
548 InputSectionBase *elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
549 uint32_t Index = this->getSectionIndex(Sym);
550 if (Index >= this->Sections.size())
551 fatal(toString(this) + ": invalid section index: " + Twine(Index));
552 InputSectionBase *S = this->Sections[Index];
554 // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03 could
555 // generate broken objects. STT_SECTION/STT_NOTYPE symbols can be
556 // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections.
557 // In this case it is fine for section to be null here as we do not
558 // allocate sections of these types.
560 if (Index == 0 || Sym.getType() == STT_SECTION ||
561 Sym.getType() == STT_NOTYPE)
563 fatal(toString(this) + ": invalid section index: " + Twine(Index));
566 if (S == &InputSection::Discarded)
571 template <class ELFT>
572 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
573 int Binding = Sym->getBinding();
574 InputSectionBase *Sec = getSection(*Sym);
576 uint8_t StOther = Sym->st_other;
577 uint8_t Type = Sym->getType();
578 uint64_t Value = Sym->st_value;
579 uint64_t Size = Sym->st_size;
581 if (Binding == STB_LOCAL) {
582 if (Sym->getType() == STT_FILE)
583 SourceFile = check(Sym->getName(this->StringTable), toString(this));
585 if (this->StringTable.size() <= Sym->st_name)
586 fatal(toString(this) + ": invalid symbol name offset");
588 StringRefZ Name = this->StringTable.data() + Sym->st_name;
589 if (Sym->st_shndx == SHN_UNDEF)
590 return make<Undefined>(Name, /*IsLocal=*/true, StOther, Type, this);
592 return make<DefinedRegular>(Name, /*IsLocal=*/true, StOther, Type, Value,
596 StringRef Name = check(Sym->getName(this->StringTable), toString(this));
598 switch (Sym->st_shndx) {
600 return elf::Symtab<ELFT>::X
601 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type,
602 /*CanOmitFromDynSym=*/false, this)
605 if (Value == 0 || Value >= UINT32_MAX)
606 fatal(toString(this) + ": common symbol '" + Name +
607 "' has invalid alignment: " + Twine(Value));
608 return elf::Symtab<ELFT>::X
609 ->addCommon(Name, Size, Value, Binding, StOther, Type, this)
615 fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
619 if (Sec == &InputSection::Discarded)
620 return elf::Symtab<ELFT>::X
621 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type,
622 /*CanOmitFromDynSym=*/false, this)
624 return elf::Symtab<ELFT>::X
625 ->addRegular(Name, StOther, Type, Value, Size, Binding, Sec, this)
630 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
631 : InputFile(ArchiveKind, File->getMemoryBufferRef()),
632 File(std::move(File)) {}
634 template <class ELFT> void ArchiveFile::parse() {
635 Symbols.reserve(File->getNumberOfSymbols());
636 for (const Archive::Symbol &Sym : File->symbols())
637 Symbols.push_back(Symtab<ELFT>::X->addLazyArchive(this, Sym));
640 // Returns a buffer pointing to a member file containing a given symbol.
641 std::pair<MemoryBufferRef, uint64_t>
642 ArchiveFile::getMember(const Archive::Symbol *Sym) {
644 check(Sym->getMember(), toString(this) +
645 ": could not get the member for symbol " +
648 if (!Seen.insert(C.getChildOffset()).second)
649 return {MemoryBufferRef(), 0};
651 MemoryBufferRef Ret =
652 check(C.getMemoryBufferRef(),
654 ": could not get the buffer for the member defining symbol " +
657 if (C.getParent()->isThin() && Tar)
658 Tar->append(relativeToRoot(check(C.getFullName(), toString(this))),
660 if (C.getParent()->isThin())
662 return {Ret, C.getChildOffset()};
665 template <class ELFT>
666 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
667 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
668 AsNeeded(Config->AsNeeded) {}
670 template <class ELFT>
671 const typename ELFT::Shdr *
672 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
674 this->getObj().getSection(&Sym, this->Symbols, this->SymtabSHNDX),
678 // Partially parse the shared object file so that we can call
679 // getSoName on this object.
680 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
681 const Elf_Shdr *DynamicSec = nullptr;
682 const ELFFile<ELFT> Obj = this->getObj();
683 ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this));
685 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
686 for (const Elf_Shdr &Sec : Sections) {
687 switch (Sec.sh_type) {
691 this->initSymtab(Sections, &Sec);
696 case SHT_SYMTAB_SHNDX:
698 check(Obj.getSHNDXTable(Sec, Sections), toString(this));
701 this->VersymSec = &Sec;
704 this->VerdefSec = &Sec;
709 if (this->VersymSec && this->Symbols.empty())
710 error("SHT_GNU_versym should be associated with symbol table");
712 // Search for a DT_SONAME tag to initialize this->SoName.
715 ArrayRef<Elf_Dyn> Arr =
716 check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec),
718 for (const Elf_Dyn &Dyn : Arr) {
719 if (Dyn.d_tag == DT_SONAME) {
720 uint64_t Val = Dyn.getVal();
721 if (Val >= this->StringTable.size())
722 fatal(toString(this) + ": invalid DT_SONAME entry");
723 SoName = this->StringTable.data() + Val;
729 // Parse the version definitions in the object file if present. Returns a vector
730 // whose nth element contains a pointer to the Elf_Verdef for version identifier
731 // n. Version identifiers that are not definitions map to nullptr. The array
732 // always has at least length 1.
733 template <class ELFT>
734 std::vector<const typename ELFT::Verdef *>
735 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
736 std::vector<const Elf_Verdef *> Verdefs(1);
737 // We only need to process symbol versions for this DSO if it has both a
738 // versym and a verdef section, which indicates that the DSO contains symbol
739 // version definitions.
740 if (!VersymSec || !VerdefSec)
743 // The location of the first global versym entry.
744 const char *Base = this->MB.getBuffer().data();
745 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
748 // We cannot determine the largest verdef identifier without inspecting
749 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
750 // sequentially starting from 1, so we predict that the largest identifier
751 // will be VerdefCount.
752 unsigned VerdefCount = VerdefSec->sh_info;
753 Verdefs.resize(VerdefCount + 1);
755 // Build the Verdefs array by following the chain of Elf_Verdef objects
756 // from the start of the .gnu.version_d section.
757 const char *Verdef = Base + VerdefSec->sh_offset;
758 for (unsigned I = 0; I != VerdefCount; ++I) {
759 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
760 Verdef += CurVerdef->vd_next;
761 unsigned VerdefIndex = CurVerdef->vd_ndx;
762 if (Verdefs.size() <= VerdefIndex)
763 Verdefs.resize(VerdefIndex + 1);
764 Verdefs[VerdefIndex] = CurVerdef;
770 // Fully parse the shared object file. This must be called after parseSoName().
771 template <class ELFT> void SharedFile<ELFT>::parseRest() {
772 // Create mapping from version identifiers to Elf_Verdef entries.
773 const Elf_Versym *Versym = nullptr;
774 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
776 Elf_Sym_Range Syms = this->getGlobalSymbols();
777 for (const Elf_Sym &Sym : Syms) {
778 unsigned VersymIndex = 0;
780 VersymIndex = Versym->vs_index;
783 bool Hidden = VersymIndex & VERSYM_HIDDEN;
784 VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
786 StringRef Name = check(Sym.getName(this->StringTable), toString(this));
787 if (Sym.isUndefined()) {
788 Undefs.push_back(Name);
792 // Ignore local symbols.
793 if (Versym && VersymIndex == VER_NDX_LOCAL)
796 const Elf_Verdef *V =
797 VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
800 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
802 // Also add the symbol with the versioned name to handle undefined symbols
803 // with explicit versions.
805 StringRef VerName = this->StringTable.data() + V->getAux()->vda_name;
806 Name = Saver.save(Name + "@" + VerName);
807 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
812 static ELFKind getBitcodeELFKind(const Triple &T) {
813 if (T.isLittleEndian())
814 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
815 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
818 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
819 switch (T.getArch()) {
820 case Triple::aarch64:
830 case Triple::mips64el:
837 return T.isOSIAMCU() ? EM_IAMCU : EM_386;
841 fatal(Path + ": could not infer e_machine from bitcode target triple " +
846 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
847 uint64_t OffsetInArchive)
848 : InputFile(BitcodeKind, MB) {
849 this->ArchiveName = ArchiveName;
851 // Here we pass a new MemoryBufferRef which is identified by ArchiveName
852 // (the fully resolved path of the archive) + member name + offset of the
853 // member in the archive.
854 // ThinLTO uses the MemoryBufferRef identifier to access its internal
855 // data structures and if two archives define two members with the same name,
856 // this causes a collision which result in only one of the objects being
857 // taken into consideration at LTO time (which very likely causes undefined
858 // symbols later in the link stage).
859 MemoryBufferRef MBRef(MB.getBuffer(),
860 Saver.save(ArchiveName + MB.getBufferIdentifier() +
861 utostr(OffsetInArchive)));
862 Obj = check(lto::InputFile::create(MBRef), toString(this));
864 Triple T(Obj->getTargetTriple());
865 EKind = getBitcodeELFKind(T);
866 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
869 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
870 switch (GvVisibility) {
871 case GlobalValue::DefaultVisibility:
873 case GlobalValue::HiddenVisibility:
875 case GlobalValue::ProtectedVisibility:
876 return STV_PROTECTED;
878 llvm_unreachable("unknown visibility");
881 template <class ELFT>
882 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
883 const lto::InputFile::Symbol &ObjSym,
885 StringRef NameRef = Saver.save(ObjSym.getName());
886 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
888 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
889 uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
890 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
892 int C = ObjSym.getComdatIndex();
893 if (C != -1 && !KeptComdats[C])
894 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding,
895 Visibility, Type, CanOmitFromDynSym,
898 if (ObjSym.isUndefined())
899 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding,
900 Visibility, Type, CanOmitFromDynSym,
903 if (ObjSym.isCommon())
904 return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(),
905 ObjSym.getCommonAlignment(), Binding,
906 Visibility, STT_OBJECT, F);
908 return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type,
909 CanOmitFromDynSym, F);
912 template <class ELFT>
913 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
914 std::vector<bool> KeptComdats;
915 for (StringRef S : Obj->getComdatTable())
916 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
918 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
919 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this));
922 static ELFKind getELFKind(MemoryBufferRef MB) {
924 unsigned char Endian;
925 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
927 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
928 fatal(MB.getBufferIdentifier() + ": invalid data encoding");
929 if (Size != ELFCLASS32 && Size != ELFCLASS64)
930 fatal(MB.getBufferIdentifier() + ": invalid file class");
932 size_t BufSize = MB.getBuffer().size();
933 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
934 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
935 fatal(MB.getBufferIdentifier() + ": file is too short");
937 if (Size == ELFCLASS32)
938 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
939 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
942 template <class ELFT> void BinaryFile::parse() {
943 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
945 make<InputSection>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 8, Data, ".data");
946 Sections.push_back(Section);
948 // For each input file foo that is embedded to a result as a binary
949 // blob, we define _binary_foo_{start,end,size} symbols, so that
950 // user programs can access blobs by name. Non-alphanumeric
951 // characters in a filename are replaced with underscore.
952 std::string S = "_binary_" + MB.getBufferIdentifier().str();
953 for (size_t I = 0; I < S.size(); ++I)
957 elf::Symtab<ELFT>::X->addRegular(Saver.save(S + "_start"), STV_DEFAULT,
958 STT_OBJECT, 0, 0, STB_GLOBAL, Section,
960 elf::Symtab<ELFT>::X->addRegular(Saver.save(S + "_end"), STV_DEFAULT,
961 STT_OBJECT, Data.size(), 0, STB_GLOBAL,
963 elf::Symtab<ELFT>::X->addRegular(Saver.save(S + "_size"), STV_DEFAULT,
964 STT_OBJECT, Data.size(), 0, STB_GLOBAL,
968 static bool isBitcode(MemoryBufferRef MB) {
969 using namespace sys::fs;
970 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
973 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
974 uint64_t OffsetInArchive) {
976 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
978 switch (getELFKind(MB)) {
980 return make<ObjectFile<ELF32LE>>(MB, ArchiveName);
982 return make<ObjectFile<ELF32BE>>(MB, ArchiveName);
984 return make<ObjectFile<ELF64LE>>(MB, ArchiveName);
986 return make<ObjectFile<ELF64BE>>(MB, ArchiveName);
988 llvm_unreachable("getELFKind");
992 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
993 switch (getELFKind(MB)) {
995 return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
997 return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
999 return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
1001 return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
1003 llvm_unreachable("getELFKind");
1007 MemoryBufferRef LazyObjectFile::getBuffer() {
1009 return MemoryBufferRef();
1014 InputFile *LazyObjectFile::fetch() {
1015 MemoryBufferRef MBRef = getBuffer();
1016 if (MBRef.getBuffer().empty())
1018 return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1021 template <class ELFT> void LazyObjectFile::parse() {
1022 for (StringRef Sym : getSymbols())
1023 Symtab<ELFT>::X->addLazyObject(Sym, *this);
1026 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() {
1027 typedef typename ELFT::Shdr Elf_Shdr;
1028 typedef typename ELFT::Sym Elf_Sym;
1029 typedef typename ELFT::SymRange Elf_Sym_Range;
1031 const ELFFile<ELFT> Obj(this->MB.getBuffer());
1032 ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this));
1033 for (const Elf_Shdr &Sec : Sections) {
1034 if (Sec.sh_type != SHT_SYMTAB)
1037 Elf_Sym_Range Syms = check(Obj.symbols(&Sec), toString(this));
1038 uint32_t FirstNonLocal = Sec.sh_info;
1039 StringRef StringTable =
1040 check(Obj.getStringTableForSymtab(Sec, Sections), toString(this));
1041 std::vector<StringRef> V;
1043 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1044 if (Sym.st_shndx != SHN_UNDEF)
1045 V.push_back(check(Sym.getName(StringTable), toString(this)));
1051 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() {
1052 std::unique_ptr<lto::InputFile> Obj =
1053 check(lto::InputFile::create(this->MB), toString(this));
1054 std::vector<StringRef> V;
1055 for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1056 if (!Sym.isUndefined())
1057 V.push_back(Saver.save(Sym.getName()));
1061 // Returns a vector of globally-visible defined symbol names.
1062 std::vector<StringRef> LazyObjectFile::getSymbols() {
1063 if (isBitcode(this->MB))
1064 return getBitcodeSymbols();
1066 switch (getELFKind(this->MB)) {
1068 return getElfSymbols<ELF32LE>();
1070 return getElfSymbols<ELF32BE>();
1072 return getElfSymbols<ELF64LE>();
1074 return getElfSymbols<ELF64BE>();
1076 llvm_unreachable("getELFKind");
1080 template void ArchiveFile::parse<ELF32LE>();
1081 template void ArchiveFile::parse<ELF32BE>();
1082 template void ArchiveFile::parse<ELF64LE>();
1083 template void ArchiveFile::parse<ELF64BE>();
1085 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1086 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1087 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1088 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1090 template void LazyObjectFile::parse<ELF32LE>();
1091 template void LazyObjectFile::parse<ELF32BE>();
1092 template void LazyObjectFile::parse<ELF64LE>();
1093 template void LazyObjectFile::parse<ELF64BE>();
1095 template class elf::ELFFileBase<ELF32LE>;
1096 template class elf::ELFFileBase<ELF32BE>;
1097 template class elf::ELFFileBase<ELF64LE>;
1098 template class elf::ELFFileBase<ELF64BE>;
1100 template class elf::ObjectFile<ELF32LE>;
1101 template class elf::ObjectFile<ELF32BE>;
1102 template class elf::ObjectFile<ELF64LE>;
1103 template class elf::ObjectFile<ELF64BE>;
1105 template class elf::SharedFile<ELF32LE>;
1106 template class elf::SharedFile<ELF32BE>;
1107 template class elf::SharedFile<ELF64LE>;
1108 template class elf::SharedFile<ELF64BE>;
1110 template void BinaryFile::parse<ELF32LE>();
1111 template void BinaryFile::parse<ELF32BE>();
1112 template void BinaryFile::parse<ELF64LE>();
1113 template void BinaryFile::parse<ELF64BE>();