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"
13 #include "InputSection.h"
14 #include "LinkerScript.h"
16 #include "SymbolTable.h"
18 #include "SyntheticSections.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Bitcode/BitcodeReader.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/LTO/LTO.h"
26 #include "llvm/MC/StringTableBuilder.h"
27 #include "llvm/Object/ELFObjectFile.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm::ELF;
33 using namespace llvm::object;
34 using namespace llvm::sys::fs;
37 using namespace lld::elf;
40 // In ELF object file all section addresses are zero. If we have multiple
41 // .text sections (when using -ffunction-section or comdat group) then
42 // LLVM DWARF parser will not be able to parse .debug_line correctly, unless
43 // we assign each section some unique address. This callback method assigns
44 // each section an address equal to its offset in ELF object file.
45 class ObjectInfo : public LoadedObjectInfo {
47 uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
48 return static_cast<const ELFSectionRef &>(Sec).getOffset();
50 std::unique_ptr<LoadedObjectInfo> clone() const override {
51 return std::unique_ptr<LoadedObjectInfo>();
56 template <class ELFT> void elf::ObjectFile<ELFT>::initializeDwarfLine() {
57 std::unique_ptr<object::ObjectFile> Obj =
58 check(object::ObjectFile::createObjectFile(this->MB),
59 "createObjectFile failed");
62 DWARFContextInMemory Dwarf(*Obj, &ObjInfo);
63 DwarfLine.reset(new DWARFDebugLine(&Dwarf.getLineSection().Relocs));
64 DataExtractor LineData(Dwarf.getLineSection().Data,
65 ELFT::TargetEndianness == support::little,
66 ELFT::Is64Bits ? 8 : 4);
68 // The second parameter is offset in .debug_line section
69 // for compilation unit (CU) of interest. We have only one
70 // CU (object file), so offset is always 0.
71 DwarfLine->getOrParseLineTable(LineData, 0);
74 // Returns source line information for a given offset
75 // using DWARF debug info.
77 std::string elf::ObjectFile<ELFT>::getLineInfo(InputSectionBase<ELFT> *S,
80 initializeDwarfLine();
82 // The offset to CU is 0.
83 const DWARFDebugLine::LineTable *Tbl = DwarfLine->getLineTable(0);
87 // Use fake address calcuated by adding section file offset and offset in
88 // section. See comments for ObjectInfo class.
90 Tbl->getFileLineInfoForAddress(
91 S->Offset + Offset, nullptr,
92 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info);
95 return Info.FileName + ":" + std::to_string(Info.Line);
98 // Returns "(internal)", "foo.a(bar.o)" or "baz.o".
99 std::string lld::toString(const InputFile *F) {
102 if (!F->ArchiveName.empty())
103 return (F->ArchiveName + "(" + F->getName() + ")").str();
107 template <class ELFT> static ELFKind getELFKind() {
108 if (ELFT::TargetEndianness == support::little)
109 return ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
110 return ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
113 template <class ELFT>
114 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
115 EKind = getELFKind<ELFT>();
116 EMachine = getObj().getHeader()->e_machine;
117 OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
120 template <class ELFT>
121 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalSymbols() {
122 return makeArrayRef(Symbols.begin() + FirstNonLocal, Symbols.end());
125 template <class ELFT>
126 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
127 return check(getObj().getSectionIndex(&Sym, Symbols, SymtabSHNDX));
130 template <class ELFT>
131 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
132 const Elf_Shdr *Symtab) {
133 FirstNonLocal = Symtab->sh_info;
134 Symbols = check(getObj().symbols(Symtab));
135 if (FirstNonLocal == 0 || FirstNonLocal > Symbols.size())
136 fatal(toString(this) + ": invalid sh_info in symbol table");
138 StringTable = check(getObj().getStringTableForSymtab(*Symtab, Sections));
141 template <class ELFT>
142 elf::ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M)
143 : ELFFileBase<ELFT>(Base::ObjectKind, M) {}
145 template <class ELFT>
146 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getNonLocalSymbols() {
147 return makeArrayRef(this->SymbolBodies).slice(this->FirstNonLocal);
150 template <class ELFT>
151 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getLocalSymbols() {
152 if (this->SymbolBodies.empty())
153 return this->SymbolBodies;
154 return makeArrayRef(this->SymbolBodies).slice(1, this->FirstNonLocal - 1);
157 template <class ELFT>
158 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getSymbols() {
159 if (this->SymbolBodies.empty())
160 return this->SymbolBodies;
161 return makeArrayRef(this->SymbolBodies).slice(1);
164 template <class ELFT>
165 void elf::ObjectFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
166 // Read section and symbol tables.
167 initializeSections(ComdatGroups);
171 // Sections with SHT_GROUP and comdat bits define comdat section groups.
172 // They are identified and deduplicated by group name. This function
173 // returns a group name.
174 template <class ELFT>
176 elf::ObjectFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
177 const Elf_Shdr &Sec) {
178 if (this->Symbols.empty())
179 this->initSymtab(Sections,
180 check(object::getSection<ELFT>(Sections, Sec.sh_link)));
182 check(object::getSymbol<ELFT>(this->Symbols, Sec.sh_info));
183 return check(Sym->getName(this->StringTable));
186 template <class ELFT>
187 ArrayRef<typename elf::ObjectFile<ELFT>::Elf_Word>
188 elf::ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
189 const ELFFile<ELFT> &Obj = this->getObj();
190 ArrayRef<Elf_Word> Entries =
191 check(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec));
192 if (Entries.empty() || Entries[0] != GRP_COMDAT)
193 fatal(toString(this) + ": unsupported SHT_GROUP format");
194 return Entries.slice(1);
197 template <class ELFT>
198 bool elf::ObjectFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
199 // We don't merge sections if -O0 (default is -O1). This makes sometimes
200 // the linker significantly faster, although the output will be bigger.
201 if (Config->Optimize == 0)
204 // Do not merge sections if generating a relocatable object. It makes
205 // the code simpler because we do not need to update relocation addends
206 // to reflect changes introduced by merging. Instead of that we write
207 // such "merge" sections into separate OutputSections and keep SHF_MERGE
208 // / SHF_STRINGS flags and sh_entsize value to be able to perform merging
209 // later during a final linking.
210 if (Config->Relocatable)
213 // A mergeable section with size 0 is useless because they don't have
214 // any data to merge. A mergeable string section with size 0 can be
215 // argued as invalid because it doesn't end with a null character.
216 // We'll avoid a mess by handling them as if they were non-mergeable.
217 if (Sec.sh_size == 0)
220 // Check for sh_entsize. The ELF spec is not clear about the zero
221 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
222 // the section does not hold a table of fixed-size entries". We know
223 // that Rust 1.13 produces a string mergeable section with a zero
224 // sh_entsize. Here we just accept it rather than being picky about it.
225 uintX_t EntSize = Sec.sh_entsize;
228 if (Sec.sh_size % EntSize)
229 fatal(toString(this) +
230 ": SHF_MERGE section size must be a multiple of sh_entsize");
232 uintX_t Flags = Sec.sh_flags;
233 if (!(Flags & SHF_MERGE))
235 if (Flags & SHF_WRITE)
236 fatal(toString(this) + ": writable SHF_MERGE section is not supported");
238 // Don't try to merge if the alignment is larger than the sh_entsize and this
239 // is not SHF_STRINGS.
241 // Since this is not a SHF_STRINGS, we would need to pad after every entity.
242 // It would be equivalent for the producer of the .o to just set a larger
244 if (Flags & SHF_STRINGS)
247 return Sec.sh_addralign <= EntSize;
250 template <class ELFT>
251 void elf::ObjectFile<ELFT>::initializeSections(
252 DenseSet<CachedHashStringRef> &ComdatGroups) {
253 ArrayRef<Elf_Shdr> ObjSections = check(this->getObj().sections());
254 const ELFFile<ELFT> &Obj = this->getObj();
255 uint64_t Size = ObjSections.size();
256 Sections.resize(Size);
258 StringRef SectionStringTable = check(Obj.getSectionStringTable(ObjSections));
259 for (const Elf_Shdr &Sec : ObjSections) {
261 if (Sections[I] == &InputSection<ELFT>::Discarded)
264 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
265 // if -r is given, we'll let the final link discard such sections.
266 // This is compatible with GNU.
267 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
268 Sections[I] = &InputSection<ELFT>::Discarded;
272 switch (Sec.sh_type) {
274 Sections[I] = &InputSection<ELFT>::Discarded;
275 if (ComdatGroups.insert(CachedHashStringRef(
276 getShtGroupSignature(ObjSections, Sec)))
279 for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
280 if (SecIndex >= Size)
281 fatal(toString(this) + ": invalid section index in group: " +
283 Sections[SecIndex] = &InputSection<ELFT>::Discarded;
287 this->initSymtab(ObjSections, &Sec);
289 case SHT_SYMTAB_SHNDX:
290 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec, ObjSections));
296 Sections[I] = createInputSection(Sec, SectionStringTable);
299 // .ARM.exidx sections have a reverse dependency on the InputSection they
300 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
301 if (Sec.sh_flags & SHF_LINK_ORDER) {
302 if (Sec.sh_link >= Sections.size())
303 fatal(toString(this) + ": invalid sh_link index: " +
305 auto *IS = cast<InputSection<ELFT>>(Sections[Sec.sh_link]);
306 IS->DependentSection = Sections[I];
311 template <class ELFT>
312 InputSectionBase<ELFT> *
313 elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
314 uint32_t Idx = Sec.sh_info;
315 if (Idx >= Sections.size())
316 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
317 InputSectionBase<ELFT> *Target = Sections[Idx];
319 // Strictly speaking, a relocation section must be included in the
320 // group of the section it relocates. However, LLVM 3.3 and earlier
321 // would fail to do so, so we gracefully handle that case.
322 if (Target == &InputSection<ELFT>::Discarded)
326 fatal(toString(this) + ": unsupported relocation reference");
330 template <class ELFT>
331 InputSectionBase<ELFT> *
332 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec,
333 StringRef SectionStringTable) {
335 check(this->getObj().getSectionName(&Sec, SectionStringTable));
337 switch (Sec.sh_type) {
338 case SHT_ARM_ATTRIBUTES:
339 // FIXME: ARM meta-data section. Retain the first attribute section
340 // we see. The eglibc ARM dynamic loaders require the presence of an
341 // attribute section for dlopen to work.
342 // In a full implementation we would merge all attribute sections.
343 if (In<ELFT>::ARMAttributes == nullptr) {
344 In<ELFT>::ARMAttributes = make<InputSection<ELFT>>(this, &Sec, Name);
345 return In<ELFT>::ARMAttributes;
347 return &InputSection<ELFT>::Discarded;
350 // This section contains relocation information.
351 // If -r is given, we do not interpret or apply relocation
352 // but just copy relocation sections to output.
353 if (Config->Relocatable)
354 return make<InputSection<ELFT>>(this, &Sec, Name);
356 // Find the relocation target section and associate this
358 InputSectionBase<ELFT> *Target = getRelocTarget(Sec);
361 if (Target->FirstRelocation)
362 fatal(toString(this) +
363 ": multiple relocation sections to one section are not supported");
364 if (!isa<InputSection<ELFT>>(Target) && !isa<EhInputSection<ELFT>>(Target))
365 fatal(toString(this) +
366 ": relocations pointing to SHF_MERGE are not supported");
368 size_t NumRelocations;
369 if (Sec.sh_type == SHT_RELA) {
370 ArrayRef<Elf_Rela> Rels = check(this->getObj().relas(&Sec));
371 Target->FirstRelocation = Rels.begin();
372 NumRelocations = Rels.size();
373 Target->AreRelocsRela = true;
375 ArrayRef<Elf_Rel> Rels = check(this->getObj().rels(&Sec));
376 Target->FirstRelocation = Rels.begin();
377 NumRelocations = Rels.size();
378 Target->AreRelocsRela = false;
380 assert(isUInt<31>(NumRelocations));
381 Target->NumRelocations = NumRelocations;
386 // .note.GNU-stack is a marker section to control the presence of
387 // PT_GNU_STACK segment in outputs. Since the presence of the segment
388 // is controlled only by the command line option (-z execstack) in LLD,
389 // .note.GNU-stack is ignored.
390 if (Name == ".note.GNU-stack")
391 return &InputSection<ELFT>::Discarded;
393 if (Name == ".note.GNU-split-stack") {
394 error("objects using splitstacks are not supported");
395 return &InputSection<ELFT>::Discarded;
398 if (Config->Strip != StripPolicy::None && Name.startswith(".debug"))
399 return &InputSection<ELFT>::Discarded;
401 // The linker merges EH (exception handling) frames and creates a
402 // .eh_frame_hdr section for runtime. So we handle them with a special
403 // class. For relocatable outputs, they are just passed through.
404 if (Name == ".eh_frame" && !Config->Relocatable)
405 return make<EhInputSection<ELFT>>(this, &Sec, Name);
407 if (shouldMerge(Sec))
408 return make<MergeInputSection<ELFT>>(this, &Sec, Name);
409 return make<InputSection<ELFT>>(this, &Sec, Name);
412 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() {
413 SymbolBodies.reserve(this->Symbols.size());
414 for (const Elf_Sym &Sym : this->Symbols)
415 SymbolBodies.push_back(createSymbolBody(&Sym));
418 template <class ELFT>
419 InputSectionBase<ELFT> *
420 elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
421 uint32_t Index = this->getSectionIndex(Sym);
422 if (Index >= Sections.size())
423 fatal(toString(this) + ": invalid section index: " + Twine(Index));
424 InputSectionBase<ELFT> *S = Sections[Index];
426 // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03 could
427 // generate broken objects. STT_SECTION/STT_NOTYPE symbols can be
428 // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections.
429 // In this case it is fine for section to be null here as we do not
430 // allocate sections of these types.
432 if (Index == 0 || Sym.getType() == STT_SECTION ||
433 Sym.getType() == STT_NOTYPE)
435 fatal(toString(this) + ": invalid section index: " + Twine(Index));
438 if (S == &InputSection<ELFT>::Discarded)
443 template <class ELFT>
444 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
445 int Binding = Sym->getBinding();
446 InputSectionBase<ELFT> *Sec = getSection(*Sym);
448 uint8_t StOther = Sym->st_other;
449 uint8_t Type = Sym->getType();
450 uintX_t Value = Sym->st_value;
451 uintX_t Size = Sym->st_size;
453 if (Binding == STB_LOCAL) {
454 if (Sym->getType() == STT_FILE)
455 SourceFile = check(Sym->getName(this->StringTable));
457 if (this->StringTable.size() <= Sym->st_name)
458 fatal(toString(this) + ": invalid symbol name offset");
460 StringRefZ Name = this->StringTable.data() + Sym->st_name;
461 if (Sym->st_shndx == SHN_UNDEF)
463 Undefined<ELFT>(Name, /*IsLocal=*/true, StOther, Type, this);
465 return new (BAlloc) DefinedRegular<ELFT>(Name, /*IsLocal=*/true, StOther,
466 Type, Value, Size, Sec, this);
469 StringRef Name = check(Sym->getName(this->StringTable));
471 switch (Sym->st_shndx) {
473 return elf::Symtab<ELFT>::X
474 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type,
475 /*CanOmitFromDynSym=*/false, this)
478 if (Value == 0 || Value >= UINT32_MAX)
479 fatal(toString(this) + ": common symbol '" + Name +
480 "' has invalid alignment: " + Twine(Value));
481 return elf::Symtab<ELFT>::X
482 ->addCommon(Name, Size, Value, Binding, StOther, Type, this)
488 fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
492 if (Sec == &InputSection<ELFT>::Discarded)
493 return elf::Symtab<ELFT>::X
494 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type,
495 /*CanOmitFromDynSym=*/false, this)
497 return elf::Symtab<ELFT>::X
498 ->addRegular(Name, StOther, Type, Value, Size, Binding, Sec, this)
503 template <class ELFT> void ArchiveFile::parse() {
504 File = check(Archive::create(MB),
505 MB.getBufferIdentifier() + ": failed to parse archive");
507 // Read the symbol table to construct Lazy objects.
508 for (const Archive::Symbol &Sym : File->symbols())
509 Symtab<ELFT>::X->addLazyArchive(this, Sym);
512 // Returns a buffer pointing to a member file containing a given symbol.
513 std::pair<MemoryBufferRef, uint64_t>
514 ArchiveFile::getMember(const Archive::Symbol *Sym) {
516 check(Sym->getMember(),
517 "could not get the member for symbol " + Sym->getName());
519 if (!Seen.insert(C.getChildOffset()).second)
520 return {MemoryBufferRef(), 0};
522 MemoryBufferRef Ret =
523 check(C.getMemoryBufferRef(),
524 "could not get the buffer for the member defining symbol " +
527 if (C.getParent()->isThin() && Driver->Tar)
528 Driver->Tar->append(relativeToRoot(check(C.getFullName())),
530 if (C.getParent()->isThin())
532 return {Ret, C.getChildOffset()};
535 template <class ELFT>
536 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
537 : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {}
539 template <class ELFT>
540 const typename ELFT::Shdr *
541 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
543 this->getObj().getSection(&Sym, this->Symbols, this->SymtabSHNDX));
546 // Partially parse the shared object file so that we can call
547 // getSoName on this object.
548 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
549 const Elf_Shdr *DynamicSec = nullptr;
551 const ELFFile<ELFT> Obj = this->getObj();
552 ArrayRef<Elf_Shdr> Sections = check(Obj.sections());
553 for (const Elf_Shdr &Sec : Sections) {
554 switch (Sec.sh_type) {
558 this->initSymtab(Sections, &Sec);
563 case SHT_SYMTAB_SHNDX:
564 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec, Sections));
567 this->VersymSec = &Sec;
570 this->VerdefSec = &Sec;
575 if (this->VersymSec && this->Symbols.empty())
576 error("SHT_GNU_versym should be associated with symbol table");
578 // DSOs are identified by soname, and they usually contain
579 // DT_SONAME tag in their header. But if they are missing,
580 // filenames are used as default sonames.
581 SoName = sys::path::filename(this->getName());
586 ArrayRef<Elf_Dyn> Arr =
587 check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec),
588 toString(this) + ": getSectionContentsAsArray failed");
589 for (const Elf_Dyn &Dyn : Arr) {
590 if (Dyn.d_tag == DT_SONAME) {
591 uintX_t Val = Dyn.getVal();
592 if (Val >= this->StringTable.size())
593 fatal(toString(this) + ": invalid DT_SONAME entry");
594 SoName = StringRef(this->StringTable.data() + Val);
600 // Parse the version definitions in the object file if present. Returns a vector
601 // whose nth element contains a pointer to the Elf_Verdef for version identifier
602 // n. Version identifiers that are not definitions map to nullptr. The array
603 // always has at least length 1.
604 template <class ELFT>
605 std::vector<const typename ELFT::Verdef *>
606 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
607 std::vector<const Elf_Verdef *> Verdefs(1);
608 // We only need to process symbol versions for this DSO if it has both a
609 // versym and a verdef section, which indicates that the DSO contains symbol
610 // version definitions.
611 if (!VersymSec || !VerdefSec)
614 // The location of the first global versym entry.
615 const char *Base = this->MB.getBuffer().data();
616 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
619 // We cannot determine the largest verdef identifier without inspecting
620 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
621 // sequentially starting from 1, so we predict that the largest identifier
622 // will be VerdefCount.
623 unsigned VerdefCount = VerdefSec->sh_info;
624 Verdefs.resize(VerdefCount + 1);
626 // Build the Verdefs array by following the chain of Elf_Verdef objects
627 // from the start of the .gnu.version_d section.
628 const char *Verdef = Base + VerdefSec->sh_offset;
629 for (unsigned I = 0; I != VerdefCount; ++I) {
630 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
631 Verdef += CurVerdef->vd_next;
632 unsigned VerdefIndex = CurVerdef->vd_ndx;
633 if (Verdefs.size() <= VerdefIndex)
634 Verdefs.resize(VerdefIndex + 1);
635 Verdefs[VerdefIndex] = CurVerdef;
641 // Fully parse the shared object file. This must be called after parseSoName().
642 template <class ELFT> void SharedFile<ELFT>::parseRest() {
643 // Create mapping from version identifiers to Elf_Verdef entries.
644 const Elf_Versym *Versym = nullptr;
645 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
647 Elf_Sym_Range Syms = this->getGlobalSymbols();
648 for (const Elf_Sym &Sym : Syms) {
649 unsigned VersymIndex = 0;
651 VersymIndex = Versym->vs_index;
655 StringRef Name = check(Sym.getName(this->StringTable));
656 if (Sym.isUndefined()) {
657 Undefs.push_back(Name);
662 // Ignore local symbols and non-default versions.
663 if (VersymIndex == VER_NDX_LOCAL || (VersymIndex & VERSYM_HIDDEN))
667 const Elf_Verdef *V =
668 VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
669 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
673 static ELFKind getBitcodeELFKind(MemoryBufferRef MB) {
674 Triple T(check(getBitcodeTargetTriple(MB)));
675 if (T.isLittleEndian())
676 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
677 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
680 static uint8_t getBitcodeMachineKind(MemoryBufferRef MB) {
681 Triple T(check(getBitcodeTargetTriple(MB)));
682 switch (T.getArch()) {
683 case Triple::aarch64:
690 case Triple::mips64el:
697 return T.isOSIAMCU() ? EM_IAMCU : EM_386;
701 fatal(MB.getBufferIdentifier() +
702 ": could not infer e_machine from bitcode target triple " + T.str());
706 BitcodeFile::BitcodeFile(MemoryBufferRef MB) : InputFile(BitcodeKind, MB) {
707 EKind = getBitcodeELFKind(MB);
708 EMachine = getBitcodeMachineKind(MB);
711 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
712 switch (GvVisibility) {
713 case GlobalValue::DefaultVisibility:
715 case GlobalValue::HiddenVisibility:
717 case GlobalValue::ProtectedVisibility:
718 return STV_PROTECTED;
720 llvm_unreachable("unknown visibility");
723 template <class ELFT>
724 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
725 const lto::InputFile::Symbol &ObjSym,
727 StringRef NameRef = Saver.save(ObjSym.getName());
728 uint32_t Flags = ObjSym.getFlags();
729 uint32_t Binding = (Flags & BasicSymbolRef::SF_Weak) ? STB_WEAK : STB_GLOBAL;
731 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
732 uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
733 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
735 int C = check(ObjSym.getComdatIndex());
736 if (C != -1 && !KeptComdats[C])
737 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding,
738 Visibility, Type, CanOmitFromDynSym,
741 if (Flags & BasicSymbolRef::SF_Undefined)
742 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding,
743 Visibility, Type, CanOmitFromDynSym,
746 if (Flags & BasicSymbolRef::SF_Common)
747 return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(),
748 ObjSym.getCommonAlignment(), Binding,
749 Visibility, STT_OBJECT, F);
751 return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type,
752 CanOmitFromDynSym, F);
755 template <class ELFT>
756 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
758 // Here we pass a new MemoryBufferRef which is identified by ArchiveName
759 // (the fully resolved path of the archive) + member name + offset of the
760 // member in the archive.
761 // ThinLTO uses the MemoryBufferRef identifier to access its internal
762 // data structures and if two archives define two members with the same name,
763 // this causes a collision which result in only one of the objects being
764 // taken into consideration at LTO time (which very likely causes undefined
765 // symbols later in the link stage).
766 Obj = check(lto::InputFile::create(MemoryBufferRef(
767 MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier() +
768 utostr(OffsetInArchive)))));
770 std::vector<bool> KeptComdats;
771 for (StringRef S : Obj->getComdatTable()) {
772 StringRef N = Saver.save(S);
773 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(N)).second);
776 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
777 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this));
780 template <template <class> class T>
781 static InputFile *createELFFile(MemoryBufferRef MB) {
783 unsigned char Endian;
784 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
785 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
786 fatal(MB.getBufferIdentifier() + ": invalid data encoding");
788 size_t BufSize = MB.getBuffer().size();
789 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
790 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
791 fatal(MB.getBufferIdentifier() + ": file is too short");
794 if (Size == ELFCLASS32 && Endian == ELFDATA2LSB)
795 Obj = make<T<ELF32LE>>(MB);
796 else if (Size == ELFCLASS32 && Endian == ELFDATA2MSB)
797 Obj = make<T<ELF32BE>>(MB);
798 else if (Size == ELFCLASS64 && Endian == ELFDATA2LSB)
799 Obj = make<T<ELF64LE>>(MB);
800 else if (Size == ELFCLASS64 && Endian == ELFDATA2MSB)
801 Obj = make<T<ELF64BE>>(MB);
803 fatal(MB.getBufferIdentifier() + ": invalid file class");
805 if (!Config->FirstElf)
806 Config->FirstElf = Obj;
810 template <class ELFT> void BinaryFile::parse() {
811 StringRef Buf = MB.getBuffer();
812 ArrayRef<uint8_t> Data =
813 makeArrayRef<uint8_t>((const uint8_t *)Buf.data(), Buf.size());
815 std::string Filename = MB.getBufferIdentifier();
816 std::transform(Filename.begin(), Filename.end(), Filename.begin(),
817 [](char C) { return isalnum(C) ? C : '_'; });
818 Filename = "_binary_" + Filename;
819 StringRef StartName = Saver.save(Twine(Filename) + "_start");
820 StringRef EndName = Saver.save(Twine(Filename) + "_end");
821 StringRef SizeName = Saver.save(Twine(Filename) + "_size");
824 make<InputSection<ELFT>>(SHF_ALLOC, SHT_PROGBITS, 8, Data, ".data");
825 Sections.push_back(Section);
827 elf::Symtab<ELFT>::X->addRegular(StartName, STV_DEFAULT, STT_OBJECT, 0, 0,
828 STB_GLOBAL, Section, nullptr);
829 elf::Symtab<ELFT>::X->addRegular(EndName, STV_DEFAULT, STT_OBJECT,
830 Data.size(), 0, STB_GLOBAL, Section,
832 elf::Symtab<ELFT>::X->addRegular(SizeName, STV_DEFAULT, STT_OBJECT,
833 Data.size(), 0, STB_GLOBAL, nullptr,
837 static bool isBitcode(MemoryBufferRef MB) {
838 using namespace sys::fs;
839 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
842 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
843 uint64_t OffsetInArchive) {
845 isBitcode(MB) ? make<BitcodeFile>(MB) : createELFFile<ObjectFile>(MB);
846 F->ArchiveName = ArchiveName;
847 F->OffsetInArchive = OffsetInArchive;
851 InputFile *elf::createSharedFile(MemoryBufferRef MB) {
852 return createELFFile<SharedFile>(MB);
855 MemoryBufferRef LazyObjectFile::getBuffer() {
857 return MemoryBufferRef();
862 template <class ELFT> void LazyObjectFile::parse() {
863 for (StringRef Sym : getSymbols())
864 Symtab<ELFT>::X->addLazyObject(Sym, *this);
867 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() {
868 typedef typename ELFT::Shdr Elf_Shdr;
869 typedef typename ELFT::Sym Elf_Sym;
870 typedef typename ELFT::SymRange Elf_Sym_Range;
872 const ELFFile<ELFT> Obj(this->MB.getBuffer());
873 ArrayRef<Elf_Shdr> Sections = check(Obj.sections());
874 for (const Elf_Shdr &Sec : Sections) {
875 if (Sec.sh_type != SHT_SYMTAB)
877 Elf_Sym_Range Syms = check(Obj.symbols(&Sec));
878 uint32_t FirstNonLocal = Sec.sh_info;
879 StringRef StringTable = check(Obj.getStringTableForSymtab(Sec, Sections));
880 std::vector<StringRef> V;
881 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
882 if (Sym.st_shndx != SHN_UNDEF)
883 V.push_back(check(Sym.getName(StringTable)));
889 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() {
890 std::unique_ptr<lto::InputFile> Obj = check(lto::InputFile::create(this->MB));
891 std::vector<StringRef> V;
892 for (const lto::InputFile::Symbol &Sym : Obj->symbols())
893 if (!(Sym.getFlags() & BasicSymbolRef::SF_Undefined))
894 V.push_back(Saver.save(Sym.getName()));
898 // Returns a vector of globally-visible defined symbol names.
899 std::vector<StringRef> LazyObjectFile::getSymbols() {
900 if (isBitcode(this->MB))
901 return getBitcodeSymbols();
904 unsigned char Endian;
905 std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer());
906 if (Size == ELFCLASS32) {
907 if (Endian == ELFDATA2LSB)
908 return getElfSymbols<ELF32LE>();
909 return getElfSymbols<ELF32BE>();
911 if (Endian == ELFDATA2LSB)
912 return getElfSymbols<ELF64LE>();
913 return getElfSymbols<ELF64BE>();
916 template void ArchiveFile::parse<ELF32LE>();
917 template void ArchiveFile::parse<ELF32BE>();
918 template void ArchiveFile::parse<ELF64LE>();
919 template void ArchiveFile::parse<ELF64BE>();
921 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
922 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
923 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
924 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
926 template void LazyObjectFile::parse<ELF32LE>();
927 template void LazyObjectFile::parse<ELF32BE>();
928 template void LazyObjectFile::parse<ELF64LE>();
929 template void LazyObjectFile::parse<ELF64BE>();
931 template class elf::ELFFileBase<ELF32LE>;
932 template class elf::ELFFileBase<ELF32BE>;
933 template class elf::ELFFileBase<ELF64LE>;
934 template class elf::ELFFileBase<ELF64BE>;
936 template class elf::ObjectFile<ELF32LE>;
937 template class elf::ObjectFile<ELF32BE>;
938 template class elf::ObjectFile<ELF64LE>;
939 template class elf::ObjectFile<ELF64BE>;
941 template class elf::SharedFile<ELF32LE>;
942 template class elf::SharedFile<ELF32BE>;
943 template class elf::SharedFile<ELF64LE>;
944 template class elf::SharedFile<ELF64BE>;
946 template void BinaryFile::parse<ELF32LE>();
947 template void BinaryFile::parse<ELF32BE>();
948 template void BinaryFile::parse<ELF64LE>();
949 template void BinaryFile::parse<ELF64BE>();