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 convertToUnixPathSeparator(Info.FileName) + ":" +
96 std::to_string(Info.Line);
99 // Returns "(internal)", "foo.a(bar.o)" or "baz.o".
100 std::string elf::toString(const InputFile *F) {
103 if (!F->ArchiveName.empty())
104 return (F->ArchiveName + "(" + F->getName() + ")").str();
108 template <class ELFT> static ELFKind getELFKind() {
109 if (ELFT::TargetEndianness == support::little)
110 return ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
111 return ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
114 template <class ELFT>
115 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
116 EKind = getELFKind<ELFT>();
117 EMachine = getObj().getHeader()->e_machine;
118 OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
121 template <class ELFT>
122 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalSymbols() {
123 return makeArrayRef(Symbols.begin() + FirstNonLocal, Symbols.end());
126 template <class ELFT>
127 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
128 return check(getObj().getSectionIndex(&Sym, Symbols, SymtabSHNDX));
131 template <class ELFT>
132 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
133 const Elf_Shdr *Symtab) {
134 FirstNonLocal = Symtab->sh_info;
135 Symbols = check(getObj().symbols(Symtab));
136 if (FirstNonLocal == 0 || FirstNonLocal > Symbols.size())
137 fatal(toString(this) + ": invalid sh_info in symbol table");
139 StringTable = check(getObj().getStringTableForSymtab(*Symtab, Sections));
142 template <class ELFT>
143 elf::ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M)
144 : ELFFileBase<ELFT>(Base::ObjectKind, M) {}
146 template <class ELFT>
147 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getNonLocalSymbols() {
148 return makeArrayRef(this->SymbolBodies).slice(this->FirstNonLocal);
151 template <class ELFT>
152 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getLocalSymbols() {
153 if (this->SymbolBodies.empty())
154 return this->SymbolBodies;
155 return makeArrayRef(this->SymbolBodies).slice(1, this->FirstNonLocal - 1);
158 template <class ELFT>
159 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getSymbols() {
160 if (this->SymbolBodies.empty())
161 return this->SymbolBodies;
162 return makeArrayRef(this->SymbolBodies).slice(1);
165 template <class ELFT>
166 void elf::ObjectFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
167 // Read section and symbol tables.
168 initializeSections(ComdatGroups);
172 // Sections with SHT_GROUP and comdat bits define comdat section groups.
173 // They are identified and deduplicated by group name. This function
174 // returns a group name.
175 template <class ELFT>
177 elf::ObjectFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
178 const Elf_Shdr &Sec) {
179 if (this->Symbols.empty())
180 this->initSymtab(Sections,
181 check(object::getSection<ELFT>(Sections, Sec.sh_link)));
183 check(object::getSymbol<ELFT>(this->Symbols, Sec.sh_info));
184 return check(Sym->getName(this->StringTable));
187 template <class ELFT>
188 ArrayRef<typename elf::ObjectFile<ELFT>::Elf_Word>
189 elf::ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
190 const ELFFile<ELFT> &Obj = this->getObj();
191 ArrayRef<Elf_Word> Entries =
192 check(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec));
193 if (Entries.empty() || Entries[0] != GRP_COMDAT)
194 fatal(toString(this) + ": unsupported SHT_GROUP format");
195 return Entries.slice(1);
198 template <class ELFT>
199 bool elf::ObjectFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
200 // We don't merge sections if -O0 (default is -O1). This makes sometimes
201 // the linker significantly faster, although the output will be bigger.
202 if (Config->Optimize == 0)
205 // Do not merge sections if generating a relocatable object. It makes
206 // the code simpler because we do not need to update relocation addends
207 // to reflect changes introduced by merging. Instead of that we write
208 // such "merge" sections into separate OutputSections and keep SHF_MERGE
209 // / SHF_STRINGS flags and sh_entsize value to be able to perform merging
210 // later during a final linking.
211 if (Config->Relocatable)
214 // A mergeable section with size 0 is useless because they don't have
215 // any data to merge. A mergeable string section with size 0 can be
216 // argued as invalid because it doesn't end with a null character.
217 // We'll avoid a mess by handling them as if they were non-mergeable.
218 if (Sec.sh_size == 0)
221 // Check for sh_entsize. The ELF spec is not clear about the zero
222 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
223 // the section does not hold a table of fixed-size entries". We know
224 // that Rust 1.13 produces a string mergeable section with a zero
225 // sh_entsize. Here we just accept it rather than being picky about it.
226 uintX_t EntSize = Sec.sh_entsize;
229 if (Sec.sh_size % EntSize)
230 fatal(toString(this) +
231 ": SHF_MERGE section size must be a multiple of sh_entsize");
233 uintX_t Flags = Sec.sh_flags;
234 if (!(Flags & SHF_MERGE))
236 if (Flags & SHF_WRITE)
237 fatal(toString(this) + ": writable SHF_MERGE section is not supported");
239 // Don't try to merge if the alignment is larger than the sh_entsize and this
240 // is not SHF_STRINGS.
242 // Since this is not a SHF_STRINGS, we would need to pad after every entity.
243 // It would be equivalent for the producer of the .o to just set a larger
245 if (Flags & SHF_STRINGS)
248 return Sec.sh_addralign <= EntSize;
251 template <class ELFT>
252 void elf::ObjectFile<ELFT>::initializeSections(
253 DenseSet<CachedHashStringRef> &ComdatGroups) {
254 ArrayRef<Elf_Shdr> ObjSections = check(this->getObj().sections());
255 const ELFFile<ELFT> &Obj = this->getObj();
256 uint64_t Size = ObjSections.size();
257 Sections.resize(Size);
259 StringRef SectionStringTable = check(Obj.getSectionStringTable(ObjSections));
260 for (const Elf_Shdr &Sec : ObjSections) {
262 if (Sections[I] == &InputSection<ELFT>::Discarded)
265 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
266 // if -r is given, we'll let the final link discard such sections.
267 // This is compatible with GNU.
268 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
269 Sections[I] = &InputSection<ELFT>::Discarded;
273 switch (Sec.sh_type) {
275 Sections[I] = &InputSection<ELFT>::Discarded;
276 if (ComdatGroups.insert(CachedHashStringRef(
277 getShtGroupSignature(ObjSections, Sec)))
280 for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
281 if (SecIndex >= Size)
282 fatal(toString(this) + ": invalid section index in group: " +
284 Sections[SecIndex] = &InputSection<ELFT>::Discarded;
288 this->initSymtab(ObjSections, &Sec);
290 case SHT_SYMTAB_SHNDX:
291 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec, ObjSections));
297 Sections[I] = createInputSection(Sec, SectionStringTable);
300 // .ARM.exidx sections have a reverse dependency on the InputSection they
301 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
302 if (Sec.sh_flags & SHF_LINK_ORDER) {
303 if (Sec.sh_link >= Sections.size())
304 fatal(toString(this) + ": invalid sh_link index: " +
306 auto *IS = cast<InputSection<ELFT>>(Sections[Sec.sh_link]);
307 IS->DependentSection = Sections[I];
312 template <class ELFT>
313 InputSectionBase<ELFT> *
314 elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
315 uint32_t Idx = Sec.sh_info;
316 if (Idx >= Sections.size())
317 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
318 InputSectionBase<ELFT> *Target = Sections[Idx];
320 // Strictly speaking, a relocation section must be included in the
321 // group of the section it relocates. However, LLVM 3.3 and earlier
322 // would fail to do so, so we gracefully handle that case.
323 if (Target == &InputSection<ELFT>::Discarded)
327 fatal(toString(this) + ": unsupported relocation reference");
331 template <class ELFT>
332 InputSectionBase<ELFT> *
333 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec,
334 StringRef SectionStringTable) {
336 check(this->getObj().getSectionName(&Sec, SectionStringTable));
338 switch (Sec.sh_type) {
339 case SHT_ARM_ATTRIBUTES:
340 // FIXME: ARM meta-data section. Retain the first attribute section
341 // we see. The eglibc ARM dynamic loaders require the presence of an
342 // attribute section for dlopen to work.
343 // In a full implementation we would merge all attribute sections.
344 if (In<ELFT>::ARMAttributes == nullptr) {
345 In<ELFT>::ARMAttributes = make<InputSection<ELFT>>(this, &Sec, Name);
346 return In<ELFT>::ARMAttributes;
348 return &InputSection<ELFT>::Discarded;
351 // This section contains relocation information.
352 // If -r is given, we do not interpret or apply relocation
353 // but just copy relocation sections to output.
354 if (Config->Relocatable)
355 return make<InputSection<ELFT>>(this, &Sec, Name);
357 // Find the relocation target section and associate this
359 InputSectionBase<ELFT> *Target = getRelocTarget(Sec);
362 if (Target->FirstRelocation)
363 fatal(toString(this) +
364 ": multiple relocation sections to one section are not supported");
365 if (!isa<InputSection<ELFT>>(Target) && !isa<EhInputSection<ELFT>>(Target))
366 fatal(toString(this) +
367 ": relocations pointing to SHF_MERGE are not supported");
369 size_t NumRelocations;
370 if (Sec.sh_type == SHT_RELA) {
371 ArrayRef<Elf_Rela> Rels = check(this->getObj().relas(&Sec));
372 Target->FirstRelocation = Rels.begin();
373 NumRelocations = Rels.size();
374 Target->AreRelocsRela = true;
376 ArrayRef<Elf_Rel> Rels = check(this->getObj().rels(&Sec));
377 Target->FirstRelocation = Rels.begin();
378 NumRelocations = Rels.size();
379 Target->AreRelocsRela = false;
381 assert(isUInt<31>(NumRelocations));
382 Target->NumRelocations = NumRelocations;
387 // .note.GNU-stack is a marker section to control the presence of
388 // PT_GNU_STACK segment in outputs. Since the presence of the segment
389 // is controlled only by the command line option (-z execstack) in LLD,
390 // .note.GNU-stack is ignored.
391 if (Name == ".note.GNU-stack")
392 return &InputSection<ELFT>::Discarded;
394 if (Name == ".note.GNU-split-stack") {
395 error("objects using splitstacks are not supported");
396 return &InputSection<ELFT>::Discarded;
399 if (Config->Strip != StripPolicy::None && Name.startswith(".debug"))
400 return &InputSection<ELFT>::Discarded;
402 // The linker merges EH (exception handling) frames and creates a
403 // .eh_frame_hdr section for runtime. So we handle them with a special
404 // class. For relocatable outputs, they are just passed through.
405 if (Name == ".eh_frame" && !Config->Relocatable)
406 return make<EhInputSection<ELFT>>(this, &Sec, Name);
408 if (shouldMerge(Sec))
409 return make<MergeInputSection<ELFT>>(this, &Sec, Name);
410 return make<InputSection<ELFT>>(this, &Sec, Name);
413 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() {
414 SymbolBodies.reserve(this->Symbols.size());
415 for (const Elf_Sym &Sym : this->Symbols)
416 SymbolBodies.push_back(createSymbolBody(&Sym));
419 template <class ELFT>
420 InputSectionBase<ELFT> *
421 elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
422 uint32_t Index = this->getSectionIndex(Sym);
423 if (Index >= Sections.size())
424 fatal(toString(this) + ": invalid section index: " + Twine(Index));
425 InputSectionBase<ELFT> *S = Sections[Index];
427 // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03 could
428 // generate broken objects. STT_SECTION/STT_NOTYPE symbols can be
429 // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections.
430 // In this case it is fine for section to be null here as we do not
431 // allocate sections of these types.
433 if (Index == 0 || Sym.getType() == STT_SECTION ||
434 Sym.getType() == STT_NOTYPE)
436 fatal(toString(this) + ": invalid section index: " + Twine(Index));
439 if (S == &InputSection<ELFT>::Discarded)
444 template <class ELFT>
445 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
446 int Binding = Sym->getBinding();
447 InputSectionBase<ELFT> *Sec = getSection(*Sym);
449 uint8_t StOther = Sym->st_other;
450 uint8_t Type = Sym->getType();
451 uintX_t Value = Sym->st_value;
452 uintX_t Size = Sym->st_size;
454 if (Binding == STB_LOCAL) {
455 if (Sym->getType() == STT_FILE)
456 SourceFile = check(Sym->getName(this->StringTable));
458 if (this->StringTable.size() <= Sym->st_name)
459 fatal(toString(this) + ": invalid symbol name offset");
461 StringRefZ Name = this->StringTable.data() + Sym->st_name;
462 if (Sym->st_shndx == SHN_UNDEF)
464 Undefined(Name, /*IsLocal=*/true, StOther, Type, this);
466 return new (BAlloc) DefinedRegular<ELFT>(Name, /*IsLocal=*/true, StOther,
467 Type, Value, Size, Sec, this);
470 StringRef Name = check(Sym->getName(this->StringTable));
472 switch (Sym->st_shndx) {
474 return elf::Symtab<ELFT>::X
475 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type,
476 /*CanOmitFromDynSym=*/false, this)
479 if (Value == 0 || Value >= UINT32_MAX)
480 fatal(toString(this) + ": common symbol '" + Name +
481 "' has invalid alignment: " + Twine(Value));
482 return elf::Symtab<ELFT>::X
483 ->addCommon(Name, Size, Value, Binding, StOther, Type, this)
489 fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
493 if (Sec == &InputSection<ELFT>::Discarded)
494 return elf::Symtab<ELFT>::X
495 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type,
496 /*CanOmitFromDynSym=*/false, this)
498 return elf::Symtab<ELFT>::X
499 ->addRegular(Name, StOther, Type, Value, Size, Binding, Sec, this)
504 template <class ELFT> void ArchiveFile::parse() {
505 File = check(Archive::create(MB),
506 MB.getBufferIdentifier() + ": failed to parse archive");
508 // Read the symbol table to construct Lazy objects.
509 for (const Archive::Symbol &Sym : File->symbols())
510 Symtab<ELFT>::X->addLazyArchive(this, Sym);
513 // Returns a buffer pointing to a member file containing a given symbol.
514 std::pair<MemoryBufferRef, uint64_t>
515 ArchiveFile::getMember(const Archive::Symbol *Sym) {
517 check(Sym->getMember(),
518 "could not get the member for symbol " + Sym->getName());
520 if (!Seen.insert(C.getChildOffset()).second)
521 return {MemoryBufferRef(), 0};
523 MemoryBufferRef Ret =
524 check(C.getMemoryBufferRef(),
525 "could not get the buffer for the member defining symbol " +
528 if (C.getParent()->isThin() && Driver->Cpio)
529 Driver->Cpio->append(relativeToRoot(check(C.getFullName())),
531 if (C.getParent()->isThin())
533 return {Ret, C.getChildOffset()};
536 template <class ELFT>
537 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
538 : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {}
540 template <class ELFT>
541 const typename ELFT::Shdr *
542 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
544 this->getObj().getSection(&Sym, this->Symbols, this->SymtabSHNDX));
547 // Partially parse the shared object file so that we can call
548 // getSoName on this object.
549 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
550 const Elf_Shdr *DynamicSec = nullptr;
552 const ELFFile<ELFT> Obj = this->getObj();
553 ArrayRef<Elf_Shdr> Sections = check(Obj.sections());
554 for (const Elf_Shdr &Sec : Sections) {
555 switch (Sec.sh_type) {
559 this->initSymtab(Sections, &Sec);
564 case SHT_SYMTAB_SHNDX:
565 this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec, Sections));
568 this->VersymSec = &Sec;
571 this->VerdefSec = &Sec;
576 if (this->VersymSec && this->Symbols.empty())
577 error("SHT_GNU_versym should be associated with symbol table");
579 // DSOs are identified by soname, and they usually contain
580 // DT_SONAME tag in their header. But if they are missing,
581 // filenames are used as default sonames.
582 SoName = sys::path::filename(this->getName());
587 ArrayRef<Elf_Dyn> Arr =
588 check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec),
589 toString(this) + ": getSectionContentsAsArray failed");
590 for (const Elf_Dyn &Dyn : Arr) {
591 if (Dyn.d_tag == DT_SONAME) {
592 uintX_t Val = Dyn.getVal();
593 if (Val >= this->StringTable.size())
594 fatal(toString(this) + ": invalid DT_SONAME entry");
595 SoName = StringRef(this->StringTable.data() + Val);
601 // Parse the version definitions in the object file if present. Returns a vector
602 // whose nth element contains a pointer to the Elf_Verdef for version identifier
603 // n. Version identifiers that are not definitions map to nullptr. The array
604 // always has at least length 1.
605 template <class ELFT>
606 std::vector<const typename ELFT::Verdef *>
607 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
608 std::vector<const Elf_Verdef *> Verdefs(1);
609 // We only need to process symbol versions for this DSO if it has both a
610 // versym and a verdef section, which indicates that the DSO contains symbol
611 // version definitions.
612 if (!VersymSec || !VerdefSec)
615 // The location of the first global versym entry.
616 const char *Base = this->MB.getBuffer().data();
617 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
620 // We cannot determine the largest verdef identifier without inspecting
621 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
622 // sequentially starting from 1, so we predict that the largest identifier
623 // will be VerdefCount.
624 unsigned VerdefCount = VerdefSec->sh_info;
625 Verdefs.resize(VerdefCount + 1);
627 // Build the Verdefs array by following the chain of Elf_Verdef objects
628 // from the start of the .gnu.version_d section.
629 const char *Verdef = Base + VerdefSec->sh_offset;
630 for (unsigned I = 0; I != VerdefCount; ++I) {
631 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
632 Verdef += CurVerdef->vd_next;
633 unsigned VerdefIndex = CurVerdef->vd_ndx;
634 if (Verdefs.size() <= VerdefIndex)
635 Verdefs.resize(VerdefIndex + 1);
636 Verdefs[VerdefIndex] = CurVerdef;
642 // Fully parse the shared object file. This must be called after parseSoName().
643 template <class ELFT> void SharedFile<ELFT>::parseRest() {
644 // Create mapping from version identifiers to Elf_Verdef entries.
645 const Elf_Versym *Versym = nullptr;
646 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
648 Elf_Sym_Range Syms = this->getGlobalSymbols();
649 for (const Elf_Sym &Sym : Syms) {
650 unsigned VersymIndex = 0;
652 VersymIndex = Versym->vs_index;
656 StringRef Name = check(Sym.getName(this->StringTable));
657 if (Sym.isUndefined()) {
658 Undefs.push_back(Name);
663 // Ignore local symbols and non-default versions.
664 if (VersymIndex == VER_NDX_LOCAL || (VersymIndex & VERSYM_HIDDEN))
668 const Elf_Verdef *V =
669 VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
670 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
674 static ELFKind getBitcodeELFKind(MemoryBufferRef MB) {
675 Triple T(check(getBitcodeTargetTriple(MB)));
676 if (T.isLittleEndian())
677 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
678 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
681 static uint8_t getBitcodeMachineKind(MemoryBufferRef MB) {
682 Triple T(check(getBitcodeTargetTriple(MB)));
683 switch (T.getArch()) {
684 case Triple::aarch64:
691 case Triple::mips64el:
698 return T.isOSIAMCU() ? EM_IAMCU : EM_386;
702 fatal(MB.getBufferIdentifier() +
703 ": could not infer e_machine from bitcode target triple " + T.str());
707 BitcodeFile::BitcodeFile(MemoryBufferRef MB) : InputFile(BitcodeKind, MB) {
708 EKind = getBitcodeELFKind(MB);
709 EMachine = getBitcodeMachineKind(MB);
712 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
713 switch (GvVisibility) {
714 case GlobalValue::DefaultVisibility:
716 case GlobalValue::HiddenVisibility:
718 case GlobalValue::ProtectedVisibility:
719 return STV_PROTECTED;
721 llvm_unreachable("unknown visibility");
724 template <class ELFT>
725 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
726 const lto::InputFile::Symbol &ObjSym,
728 StringRef NameRef = Saver.save(ObjSym.getName());
729 uint32_t Flags = ObjSym.getFlags();
730 uint32_t Binding = (Flags & BasicSymbolRef::SF_Weak) ? STB_WEAK : STB_GLOBAL;
732 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
733 uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
734 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
736 int C = check(ObjSym.getComdatIndex());
737 if (C != -1 && !KeptComdats[C])
738 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding,
739 Visibility, Type, CanOmitFromDynSym,
742 if (Flags & BasicSymbolRef::SF_Undefined)
743 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding,
744 Visibility, Type, CanOmitFromDynSym,
747 if (Flags & BasicSymbolRef::SF_Common)
748 return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(),
749 ObjSym.getCommonAlignment(), Binding,
750 Visibility, STT_OBJECT, F);
752 return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type,
753 CanOmitFromDynSym, F);
756 template <class ELFT>
757 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
759 // Here we pass a new MemoryBufferRef which is identified by ArchiveName
760 // (the fully resolved path of the archive) + member name + offset of the
761 // member in the archive.
762 // ThinLTO uses the MemoryBufferRef identifier to access its internal
763 // data structures and if two archives define two members with the same name,
764 // this causes a collision which result in only one of the objects being
765 // taken into consideration at LTO time (which very likely causes undefined
766 // symbols later in the link stage).
767 Obj = check(lto::InputFile::create(MemoryBufferRef(
768 MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier() +
769 utostr(OffsetInArchive)))));
771 std::vector<bool> KeptComdats;
772 for (StringRef S : Obj->getComdatTable()) {
773 StringRef N = Saver.save(S);
774 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(N)).second);
777 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
778 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this));
781 template <template <class> class T>
782 static InputFile *createELFFile(MemoryBufferRef MB) {
784 unsigned char Endian;
785 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
786 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
787 fatal(MB.getBufferIdentifier() + ": invalid data encoding");
789 size_t BufSize = MB.getBuffer().size();
790 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
791 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
792 fatal(MB.getBufferIdentifier() + ": file is too short");
795 if (Size == ELFCLASS32 && Endian == ELFDATA2LSB)
796 Obj = make<T<ELF32LE>>(MB);
797 else if (Size == ELFCLASS32 && Endian == ELFDATA2MSB)
798 Obj = make<T<ELF32BE>>(MB);
799 else if (Size == ELFCLASS64 && Endian == ELFDATA2LSB)
800 Obj = make<T<ELF64LE>>(MB);
801 else if (Size == ELFCLASS64 && Endian == ELFDATA2MSB)
802 Obj = make<T<ELF64BE>>(MB);
804 fatal(MB.getBufferIdentifier() + ": invalid file class");
806 if (!Config->FirstElf)
807 Config->FirstElf = Obj;
811 template <class ELFT> void BinaryFile::parse() {
812 StringRef Buf = MB.getBuffer();
813 ArrayRef<uint8_t> Data =
814 makeArrayRef<uint8_t>((const uint8_t *)Buf.data(), Buf.size());
816 std::string Filename = MB.getBufferIdentifier();
817 std::transform(Filename.begin(), Filename.end(), Filename.begin(),
818 [](char C) { return isalnum(C) ? C : '_'; });
819 Filename = "_binary_" + Filename;
820 StringRef StartName = Saver.save(Twine(Filename) + "_start");
821 StringRef EndName = Saver.save(Twine(Filename) + "_end");
822 StringRef SizeName = Saver.save(Twine(Filename) + "_size");
825 make<InputSection<ELFT>>(SHF_ALLOC, SHT_PROGBITS, 8, Data, ".data");
826 Sections.push_back(Section);
828 elf::Symtab<ELFT>::X->addRegular(StartName, STV_DEFAULT, STT_OBJECT, 0, 0,
829 STB_GLOBAL, Section, nullptr);
830 elf::Symtab<ELFT>::X->addRegular(EndName, STV_DEFAULT, STT_OBJECT,
831 Data.size(), 0, STB_GLOBAL, Section,
833 elf::Symtab<ELFT>::X->addRegular(SizeName, STV_DEFAULT, STT_OBJECT,
834 Data.size(), 0, STB_GLOBAL, nullptr,
838 static bool isBitcode(MemoryBufferRef MB) {
839 using namespace sys::fs;
840 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
843 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
844 uint64_t OffsetInArchive) {
846 isBitcode(MB) ? make<BitcodeFile>(MB) : createELFFile<ObjectFile>(MB);
847 F->ArchiveName = ArchiveName;
848 F->OffsetInArchive = OffsetInArchive;
852 InputFile *elf::createSharedFile(MemoryBufferRef MB) {
853 return createELFFile<SharedFile>(MB);
856 MemoryBufferRef LazyObjectFile::getBuffer() {
858 return MemoryBufferRef();
863 template <class ELFT> void LazyObjectFile::parse() {
864 for (StringRef Sym : getSymbols())
865 Symtab<ELFT>::X->addLazyObject(Sym, *this);
868 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() {
869 typedef typename ELFT::Shdr Elf_Shdr;
870 typedef typename ELFT::Sym Elf_Sym;
871 typedef typename ELFT::SymRange Elf_Sym_Range;
873 const ELFFile<ELFT> Obj(this->MB.getBuffer());
874 ArrayRef<Elf_Shdr> Sections = check(Obj.sections());
875 for (const Elf_Shdr &Sec : Sections) {
876 if (Sec.sh_type != SHT_SYMTAB)
878 Elf_Sym_Range Syms = check(Obj.symbols(&Sec));
879 uint32_t FirstNonLocal = Sec.sh_info;
880 StringRef StringTable = check(Obj.getStringTableForSymtab(Sec, Sections));
881 std::vector<StringRef> V;
882 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
883 if (Sym.st_shndx != SHN_UNDEF)
884 V.push_back(check(Sym.getName(StringTable)));
890 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() {
891 std::unique_ptr<lto::InputFile> Obj = check(lto::InputFile::create(this->MB));
892 std::vector<StringRef> V;
893 for (const lto::InputFile::Symbol &Sym : Obj->symbols())
894 if (!(Sym.getFlags() & BasicSymbolRef::SF_Undefined))
895 V.push_back(Saver.save(Sym.getName()));
899 // Returns a vector of globally-visible defined symbol names.
900 std::vector<StringRef> LazyObjectFile::getSymbols() {
901 if (isBitcode(this->MB))
902 return getBitcodeSymbols();
905 unsigned char Endian;
906 std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer());
907 if (Size == ELFCLASS32) {
908 if (Endian == ELFDATA2LSB)
909 return getElfSymbols<ELF32LE>();
910 return getElfSymbols<ELF32BE>();
912 if (Endian == ELFDATA2LSB)
913 return getElfSymbols<ELF64LE>();
914 return getElfSymbols<ELF64BE>();
917 template void ArchiveFile::parse<ELF32LE>();
918 template void ArchiveFile::parse<ELF32BE>();
919 template void ArchiveFile::parse<ELF64LE>();
920 template void ArchiveFile::parse<ELF64BE>();
922 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
923 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
924 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
925 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
927 template void LazyObjectFile::parse<ELF32LE>();
928 template void LazyObjectFile::parse<ELF32BE>();
929 template void LazyObjectFile::parse<ELF64LE>();
930 template void LazyObjectFile::parse<ELF64BE>();
932 template class elf::ELFFileBase<ELF32LE>;
933 template class elf::ELFFileBase<ELF32BE>;
934 template class elf::ELFFileBase<ELF64LE>;
935 template class elf::ELFFileBase<ELF64BE>;
937 template class elf::ObjectFile<ELF32LE>;
938 template class elf::ObjectFile<ELF32BE>;
939 template class elf::ObjectFile<ELF64LE>;
940 template class elf::ObjectFile<ELF64BE>;
942 template class elf::SharedFile<ELF32LE>;
943 template class elf::SharedFile<ELF32BE>;
944 template class elf::SharedFile<ELF64LE>;
945 template class elf::SharedFile<ELF64BE>;
947 template void BinaryFile::parse<ELF32LE>();
948 template void BinaryFile::parse<ELF32BE>();
949 template void BinaryFile::parse<ELF64LE>();
950 template void BinaryFile::parse<ELF64BE>();