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 LoadedObjectInfoHelper<ObjectInfo> {
50 uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
51 return static_cast<const ELFSectionRef &>(Sec).getOffset();
56 Optional<MemoryBufferRef> elf::readFile(StringRef Path) {
58 auto MBOrErr = MemoryBuffer::getFile(Path);
59 if (auto EC = MBOrErr.getError()) {
60 error("cannot open " + Path + ": " + EC.message());
64 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
65 MemoryBufferRef MBRef = MB->getMemBufferRef();
66 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
69 Tar->append(relativeToRoot(Path), MBRef.getBuffer());
73 template <class ELFT> void elf::ObjectFile<ELFT>::initializeDwarfLine() {
74 std::unique_ptr<object::ObjectFile> Obj =
75 check(object::ObjectFile::createObjectFile(this->MB), toString(this));
78 DWARFContextInMemory Dwarf(*Obj, &ObjInfo);
79 DwarfLine.reset(new DWARFDebugLine);
80 DWARFDataExtractor LineData(Dwarf.getLineSection(), Config->IsLE,
83 // The second parameter is offset in .debug_line section
84 // for compilation unit (CU) of interest. We have only one
85 // CU (object file), so offset is always 0.
86 DwarfLine->getOrParseLineTable(LineData, 0);
89 // Returns source line information for a given offset
90 // using DWARF debug info.
92 Optional<DILineInfo> elf::ObjectFile<ELFT>::getDILineInfo(InputSectionBase *S,
94 llvm::call_once(InitDwarfLine, [this]() { initializeDwarfLine(); });
96 // The offset to CU is 0.
97 const DWARFDebugLine::LineTable *Tbl = DwarfLine->getLineTable(0);
101 // Use fake address calcuated by adding section file offset and offset in
102 // section. See comments for ObjectInfo class.
104 Tbl->getFileLineInfoForAddress(
105 S->getOffsetInFile() + Offset, nullptr,
106 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info);
112 // Returns source line information for a given offset
113 // using DWARF debug info.
114 template <class ELFT>
115 std::string elf::ObjectFile<ELFT>::getLineInfo(InputSectionBase *S,
117 if (Optional<DILineInfo> Info = getDILineInfo(S, Offset))
118 return Info->FileName + ":" + std::to_string(Info->Line);
122 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
123 std::string lld::toString(const InputFile *F) {
127 if (F->ToStringCache.empty()) {
128 if (F->ArchiveName.empty())
129 F->ToStringCache = F->getName();
131 F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str();
133 return F->ToStringCache;
136 template <class ELFT>
137 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
138 if (ELFT::TargetEndianness == support::little)
139 EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
141 EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
143 EMachine = getObj().getHeader()->e_machine;
144 OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
147 template <class ELFT>
148 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalSymbols() {
149 return makeArrayRef(Symbols.begin() + FirstNonLocal, Symbols.end());
152 template <class ELFT>
153 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
154 return check(getObj().getSectionIndex(&Sym, Symbols, SymtabSHNDX),
158 template <class ELFT>
159 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
160 const Elf_Shdr *Symtab) {
161 FirstNonLocal = Symtab->sh_info;
162 Symbols = check(getObj().symbols(Symtab), toString(this));
163 if (FirstNonLocal == 0 || FirstNonLocal > Symbols.size())
164 fatal(toString(this) + ": invalid sh_info in symbol table");
166 StringTable = check(getObj().getStringTableForSymtab(*Symtab, Sections),
170 template <class ELFT>
171 elf::ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M, StringRef ArchiveName)
172 : ELFFileBase<ELFT>(Base::ObjectKind, M) {
173 this->ArchiveName = ArchiveName;
176 template <class ELFT>
177 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getLocalSymbols() {
178 if (this->SymbolBodies.empty())
179 return this->SymbolBodies;
180 return makeArrayRef(this->SymbolBodies).slice(1, this->FirstNonLocal - 1);
183 template <class ELFT>
184 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getSymbols() {
185 if (this->SymbolBodies.empty())
186 return this->SymbolBodies;
187 return makeArrayRef(this->SymbolBodies).slice(1);
190 template <class ELFT>
191 void elf::ObjectFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
192 // Read section and symbol tables.
193 initializeSections(ComdatGroups);
197 // Sections with SHT_GROUP and comdat bits define comdat section groups.
198 // They are identified and deduplicated by group name. This function
199 // returns a group name.
200 template <class ELFT>
202 elf::ObjectFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
203 const Elf_Shdr &Sec) {
204 // Group signatures are stored as symbol names in object files.
205 // sh_info contains a symbol index, so we fetch a symbol and read its name.
206 if (this->Symbols.empty())
209 check(object::getSection<ELFT>(Sections, Sec.sh_link), toString(this)));
211 const Elf_Sym *Sym = check(
212 object::getSymbol<ELFT>(this->Symbols, Sec.sh_info), toString(this));
213 StringRef Signature = check(Sym->getName(this->StringTable), toString(this));
215 // As a special case, if a symbol is a section symbol and has no name,
216 // we use a section name as a signature.
218 // Such SHT_GROUP sections are invalid from the perspective of the ELF
219 // standard, but GNU gold 1.14 (the neweset version as of July 2017) or
220 // older produce such sections as outputs for the -r option, so we need
221 // a bug-compatibility.
222 if (Signature.empty() && Sym->getType() == STT_SECTION)
223 return getSectionName(Sec);
227 template <class ELFT>
228 ArrayRef<typename elf::ObjectFile<ELFT>::Elf_Word>
229 elf::ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
230 const ELFFile<ELFT> &Obj = this->getObj();
231 ArrayRef<Elf_Word> Entries = check(
232 Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), toString(this));
233 if (Entries.empty() || Entries[0] != GRP_COMDAT)
234 fatal(toString(this) + ": unsupported SHT_GROUP format");
235 return Entries.slice(1);
238 template <class ELFT>
239 bool elf::ObjectFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
240 // We don't merge sections if -O0 (default is -O1). This makes sometimes
241 // the linker significantly faster, although the output will be bigger.
242 if (Config->Optimize == 0)
245 // Do not merge sections if generating a relocatable object. It makes
246 // the code simpler because we do not need to update relocation addends
247 // to reflect changes introduced by merging. Instead of that we write
248 // such "merge" sections into separate OutputSections and keep SHF_MERGE
249 // / SHF_STRINGS flags and sh_entsize value to be able to perform merging
250 // later during a final linking.
251 if (Config->Relocatable)
254 // A mergeable section with size 0 is useless because they don't have
255 // any data to merge. A mergeable string section with size 0 can be
256 // argued as invalid because it doesn't end with a null character.
257 // We'll avoid a mess by handling them as if they were non-mergeable.
258 if (Sec.sh_size == 0)
261 // Check for sh_entsize. The ELF spec is not clear about the zero
262 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
263 // the section does not hold a table of fixed-size entries". We know
264 // that Rust 1.13 produces a string mergeable section with a zero
265 // sh_entsize. Here we just accept it rather than being picky about it.
266 uint64_t EntSize = Sec.sh_entsize;
269 if (Sec.sh_size % EntSize)
270 fatal(toString(this) +
271 ": SHF_MERGE section size must be a multiple of sh_entsize");
273 uint64_t Flags = Sec.sh_flags;
274 if (!(Flags & SHF_MERGE))
276 if (Flags & SHF_WRITE)
277 fatal(toString(this) + ": writable SHF_MERGE section is not supported");
279 // Don't try to merge if the alignment is larger than the sh_entsize and this
280 // is not SHF_STRINGS.
282 // Since this is not a SHF_STRINGS, we would need to pad after every entity.
283 // It would be equivalent for the producer of the .o to just set a larger
285 if (Flags & SHF_STRINGS)
288 return Sec.sh_addralign <= EntSize;
291 template <class ELFT>
292 void elf::ObjectFile<ELFT>::initializeSections(
293 DenseSet<CachedHashStringRef> &ComdatGroups) {
294 const ELFFile<ELFT> &Obj = this->getObj();
296 ArrayRef<Elf_Shdr> ObjSections =
297 check(this->getObj().sections(), toString(this));
298 uint64_t Size = ObjSections.size();
299 this->Sections.resize(Size);
300 this->SectionStringTable =
301 check(Obj.getSectionStringTable(ObjSections), toString(this));
303 for (size_t I = 0, E = ObjSections.size(); I < E; I++) {
304 if (this->Sections[I] == &InputSection::Discarded)
306 const Elf_Shdr &Sec = ObjSections[I];
308 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
309 // if -r is given, we'll let the final link discard such sections.
310 // This is compatible with GNU.
311 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
312 this->Sections[I] = &InputSection::Discarded;
316 switch (Sec.sh_type) {
318 // De-duplicate section groups by their signatures.
319 StringRef Signature = getShtGroupSignature(ObjSections, Sec);
320 bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second;
321 this->Sections[I] = &InputSection::Discarded;
323 // If it is a new section group, we want to keep group members.
324 // Group leader sections, which contain indices of group members, are
325 // discarded because they are useless beyond this point. The only
326 // exception is the -r option because in order to produce re-linkable
327 // object files, we want to pass through basically everything.
329 if (Config->Relocatable)
330 this->Sections[I] = createInputSection(Sec);
334 // Otherwise, discard group members.
335 for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
336 if (SecIndex >= Size)
337 fatal(toString(this) +
338 ": invalid section index in group: " + Twine(SecIndex));
339 this->Sections[SecIndex] = &InputSection::Discarded;
344 this->initSymtab(ObjSections, &Sec);
346 case SHT_SYMTAB_SHNDX:
348 check(Obj.getSHNDXTable(Sec, ObjSections), toString(this));
354 this->Sections[I] = createInputSection(Sec);
357 // .ARM.exidx sections have a reverse dependency on the InputSection they
358 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
359 if (Sec.sh_flags & SHF_LINK_ORDER) {
360 if (Sec.sh_link >= this->Sections.size())
361 fatal(toString(this) + ": invalid sh_link index: " +
363 this->Sections[Sec.sh_link]->DependentSections.push_back(
369 template <class ELFT>
370 InputSectionBase *elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
371 uint32_t Idx = Sec.sh_info;
372 if (Idx >= this->Sections.size())
373 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
374 InputSectionBase *Target = this->Sections[Idx];
376 // Strictly speaking, a relocation section must be included in the
377 // group of the section it relocates. However, LLVM 3.3 and earlier
378 // would fail to do so, so we gracefully handle that case.
379 if (Target == &InputSection::Discarded)
383 fatal(toString(this) + ": unsupported relocation reference");
387 // Create a regular InputSection class that has the same contents
388 // as a given section.
389 InputSectionBase *toRegularSection(MergeInputSection *Sec) {
390 auto *Ret = make<InputSection>(Sec->Flags, Sec->Type, Sec->Alignment,
391 Sec->Data, Sec->Name);
392 Ret->File = Sec->File;
396 template <class ELFT>
398 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
399 StringRef Name = getSectionName(Sec);
401 switch (Sec.sh_type) {
402 case SHT_ARM_ATTRIBUTES:
403 // FIXME: ARM meta-data section. Retain the first attribute section
404 // we see. The eglibc ARM dynamic loaders require the presence of an
405 // attribute section for dlopen to work.
406 // In a full implementation we would merge all attribute sections.
407 if (InX::ARMAttributes == nullptr) {
408 InX::ARMAttributes = make<InputSection>(this, &Sec, Name);
409 return InX::ARMAttributes;
411 return &InputSection::Discarded;
414 // Find the relocation target section and associate this
415 // section with it. Target can be discarded, for example
416 // if it is a duplicated member of SHT_GROUP section, we
417 // do not create or proccess relocatable sections then.
418 InputSectionBase *Target = getRelocTarget(Sec);
422 // This section contains relocation information.
423 // If -r is given, we do not interpret or apply relocation
424 // but just copy relocation sections to output.
425 if (Config->Relocatable)
426 return make<InputSection>(this, &Sec, Name);
428 if (Target->FirstRelocation)
429 fatal(toString(this) +
430 ": multiple relocation sections to one section are not supported");
432 // Mergeable sections with relocations are tricky because relocations
433 // need to be taken into account when comparing section contents for
434 // merging. It's not worth supporting such mergeable sections because
435 // they are rare and it'd complicates the internal design (we usually
436 // have to determine if two sections are mergeable early in the link
437 // process much before applying relocations). We simply handle mergeable
438 // sections with relocations as non-mergeable.
439 if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
440 Target = toRegularSection(MS);
441 this->Sections[Sec.sh_info] = Target;
444 size_t NumRelocations;
445 if (Sec.sh_type == SHT_RELA) {
446 ArrayRef<Elf_Rela> Rels =
447 check(this->getObj().relas(&Sec), toString(this));
448 Target->FirstRelocation = Rels.begin();
449 NumRelocations = Rels.size();
450 Target->AreRelocsRela = true;
452 ArrayRef<Elf_Rel> Rels = check(this->getObj().rels(&Sec), toString(this));
453 Target->FirstRelocation = Rels.begin();
454 NumRelocations = Rels.size();
455 Target->AreRelocsRela = false;
457 assert(isUInt<31>(NumRelocations));
458 Target->NumRelocations = NumRelocations;
460 // Relocation sections processed by the linker are usually removed
461 // from the output, so returning `nullptr` for the normal case.
462 // However, if -emit-relocs is given, we need to leave them in the output.
463 // (Some post link analysis tools need this information.)
464 if (Config->EmitRelocs) {
465 InputSection *RelocSec = make<InputSection>(this, &Sec, Name);
466 // We will not emit relocation section if target was discarded.
467 Target->DependentSections.push_back(RelocSec);
474 // The GNU linker uses .note.GNU-stack section as a marker indicating
475 // that the code in the object file does not expect that the stack is
476 // executable (in terms of NX bit). If all input files have the marker,
477 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
478 // make the stack non-executable. Most object files have this section as
481 // But making the stack non-executable is a norm today for security
482 // reasons. Failure to do so may result in a serious security issue.
483 // Therefore, we make LLD always add PT_GNU_STACK unless it is
484 // explicitly told to do otherwise (by -z execstack). Because the stack
485 // executable-ness is controlled solely by command line options,
486 // .note.GNU-stack sections are simply ignored.
487 if (Name == ".note.GNU-stack")
488 return &InputSection::Discarded;
490 // Split stacks is a feature to support a discontiguous stack. At least
491 // as of 2017, it seems that the feature is not being used widely.
492 // Only GNU gold supports that. We don't. For the details about that,
493 // see https://gcc.gnu.org/wiki/SplitStacks
494 if (Name == ".note.GNU-split-stack") {
495 error(toString(this) +
496 ": object file compiled with -fsplit-stack is not supported");
497 return &InputSection::Discarded;
500 if (Config->Strip != StripPolicy::None && Name.startswith(".debug"))
501 return &InputSection::Discarded;
503 // If -gdb-index is given, LLD creates .gdb_index section, and that
504 // section serves the same purpose as .debug_gnu_pub{names,types} sections.
505 // If that's the case, we want to eliminate .debug_gnu_pub{names,types}
506 // because they are redundant and can waste large amount of disk space
507 // (for example, they are about 400 MiB in total for a clang debug build.)
508 if (Config->GdbIndex &&
509 (Name == ".debug_gnu_pubnames" || Name == ".debug_gnu_pubtypes"))
510 return &InputSection::Discarded;
512 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
513 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
514 // sections. Drop those sections to avoid duplicate symbol errors.
515 // FIXME: This is glibc PR20543, we should remove this hack once that has been
516 // fixed for a while.
517 if (Name.startswith(".gnu.linkonce."))
518 return &InputSection::Discarded;
520 // The linker merges EH (exception handling) frames and creates a
521 // .eh_frame_hdr section for runtime. So we handle them with a special
522 // class. For relocatable outputs, they are just passed through.
523 if (Name == ".eh_frame" && !Config->Relocatable)
524 return make<EhInputSection>(this, &Sec, Name);
526 if (shouldMerge(Sec))
527 return make<MergeInputSection>(this, &Sec, Name);
528 return make<InputSection>(this, &Sec, Name);
531 template <class ELFT>
532 StringRef elf::ObjectFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
533 return check(this->getObj().getSectionName(&Sec, SectionStringTable),
537 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() {
538 SymbolBodies.reserve(this->Symbols.size());
539 for (const Elf_Sym &Sym : this->Symbols)
540 SymbolBodies.push_back(createSymbolBody(&Sym));
543 template <class ELFT>
544 InputSectionBase *elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
545 uint32_t Index = this->getSectionIndex(Sym);
546 if (Index >= this->Sections.size())
547 fatal(toString(this) + ": invalid section index: " + Twine(Index));
548 InputSectionBase *S = this->Sections[Index];
550 // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03 could
551 // generate broken objects. STT_SECTION/STT_NOTYPE symbols can be
552 // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections.
553 // In this case it is fine for section to be null here as we do not
554 // allocate sections of these types.
556 if (Index == 0 || Sym.getType() == STT_SECTION ||
557 Sym.getType() == STT_NOTYPE)
559 fatal(toString(this) + ": invalid section index: " + Twine(Index));
562 if (S == &InputSection::Discarded)
567 template <class ELFT>
568 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
569 int Binding = Sym->getBinding();
570 InputSectionBase *Sec = getSection(*Sym);
572 uint8_t StOther = Sym->st_other;
573 uint8_t Type = Sym->getType();
574 uint64_t Value = Sym->st_value;
575 uint64_t Size = Sym->st_size;
577 if (Binding == STB_LOCAL) {
578 if (Sym->getType() == STT_FILE)
579 SourceFile = check(Sym->getName(this->StringTable), toString(this));
581 if (this->StringTable.size() <= Sym->st_name)
582 fatal(toString(this) + ": invalid symbol name offset");
584 StringRefZ Name = this->StringTable.data() + Sym->st_name;
585 if (Sym->st_shndx == SHN_UNDEF)
586 return make<Undefined>(Name, /*IsLocal=*/true, StOther, Type, this);
588 return make<DefinedRegular>(Name, /*IsLocal=*/true, StOther, Type, Value,
592 StringRef Name = check(Sym->getName(this->StringTable), toString(this));
594 switch (Sym->st_shndx) {
596 return elf::Symtab<ELFT>::X
597 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type,
598 /*CanOmitFromDynSym=*/false, this)
601 if (Value == 0 || Value >= UINT32_MAX)
602 fatal(toString(this) + ": common symbol '" + Name +
603 "' has invalid alignment: " + Twine(Value));
604 return elf::Symtab<ELFT>::X
605 ->addCommon(Name, Size, Value, Binding, StOther, Type, this)
611 fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
615 if (Sec == &InputSection::Discarded)
616 return elf::Symtab<ELFT>::X
617 ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type,
618 /*CanOmitFromDynSym=*/false, this)
620 return elf::Symtab<ELFT>::X
621 ->addRegular(Name, StOther, Type, Value, Size, Binding, Sec, this)
626 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
627 : InputFile(ArchiveKind, File->getMemoryBufferRef()),
628 File(std::move(File)) {}
630 template <class ELFT> void ArchiveFile::parse() {
631 Symbols.reserve(File->getNumberOfSymbols());
632 for (const Archive::Symbol &Sym : File->symbols())
633 Symbols.push_back(Symtab<ELFT>::X->addLazyArchive(this, Sym));
636 // Returns a buffer pointing to a member file containing a given symbol.
637 std::pair<MemoryBufferRef, uint64_t>
638 ArchiveFile::getMember(const Archive::Symbol *Sym) {
640 check(Sym->getMember(), toString(this) +
641 ": could not get the member for symbol " +
644 if (!Seen.insert(C.getChildOffset()).second)
645 return {MemoryBufferRef(), 0};
647 MemoryBufferRef Ret =
648 check(C.getMemoryBufferRef(),
650 ": could not get the buffer for the member defining symbol " +
653 if (C.getParent()->isThin() && Tar)
654 Tar->append(relativeToRoot(check(C.getFullName(), toString(this))),
656 if (C.getParent()->isThin())
658 return {Ret, C.getChildOffset()};
661 template <class ELFT>
662 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
663 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
664 AsNeeded(Config->AsNeeded) {}
666 template <class ELFT>
667 const typename ELFT::Shdr *
668 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
670 this->getObj().getSection(&Sym, this->Symbols, this->SymtabSHNDX),
674 // Partially parse the shared object file so that we can call
675 // getSoName on this object.
676 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
677 const Elf_Shdr *DynamicSec = nullptr;
678 const ELFFile<ELFT> Obj = this->getObj();
679 ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this));
681 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
682 for (const Elf_Shdr &Sec : Sections) {
683 switch (Sec.sh_type) {
687 this->initSymtab(Sections, &Sec);
692 case SHT_SYMTAB_SHNDX:
694 check(Obj.getSHNDXTable(Sec, Sections), toString(this));
697 this->VersymSec = &Sec;
700 this->VerdefSec = &Sec;
705 if (this->VersymSec && this->Symbols.empty())
706 error("SHT_GNU_versym should be associated with symbol table");
708 // Search for a DT_SONAME tag to initialize this->SoName.
711 ArrayRef<Elf_Dyn> Arr =
712 check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec),
714 for (const Elf_Dyn &Dyn : Arr) {
715 if (Dyn.d_tag == DT_SONAME) {
716 uint64_t Val = Dyn.getVal();
717 if (Val >= this->StringTable.size())
718 fatal(toString(this) + ": invalid DT_SONAME entry");
719 SoName = this->StringTable.data() + Val;
725 // Parse the version definitions in the object file if present. Returns a vector
726 // whose nth element contains a pointer to the Elf_Verdef for version identifier
727 // n. Version identifiers that are not definitions map to nullptr. The array
728 // always has at least length 1.
729 template <class ELFT>
730 std::vector<const typename ELFT::Verdef *>
731 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
732 std::vector<const Elf_Verdef *> Verdefs(1);
733 // We only need to process symbol versions for this DSO if it has both a
734 // versym and a verdef section, which indicates that the DSO contains symbol
735 // version definitions.
736 if (!VersymSec || !VerdefSec)
739 // The location of the first global versym entry.
740 const char *Base = this->MB.getBuffer().data();
741 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
744 // We cannot determine the largest verdef identifier without inspecting
745 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
746 // sequentially starting from 1, so we predict that the largest identifier
747 // will be VerdefCount.
748 unsigned VerdefCount = VerdefSec->sh_info;
749 Verdefs.resize(VerdefCount + 1);
751 // Build the Verdefs array by following the chain of Elf_Verdef objects
752 // from the start of the .gnu.version_d section.
753 const char *Verdef = Base + VerdefSec->sh_offset;
754 for (unsigned I = 0; I != VerdefCount; ++I) {
755 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
756 Verdef += CurVerdef->vd_next;
757 unsigned VerdefIndex = CurVerdef->vd_ndx;
758 if (Verdefs.size() <= VerdefIndex)
759 Verdefs.resize(VerdefIndex + 1);
760 Verdefs[VerdefIndex] = CurVerdef;
766 // Fully parse the shared object file. This must be called after parseSoName().
767 template <class ELFT> void SharedFile<ELFT>::parseRest() {
768 // Create mapping from version identifiers to Elf_Verdef entries.
769 const Elf_Versym *Versym = nullptr;
770 std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
772 Elf_Sym_Range Syms = this->getGlobalSymbols();
773 for (const Elf_Sym &Sym : Syms) {
774 unsigned VersymIndex = 0;
776 VersymIndex = Versym->vs_index;
779 bool Hidden = VersymIndex & VERSYM_HIDDEN;
780 VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
782 StringRef Name = check(Sym.getName(this->StringTable), toString(this));
783 if (Sym.isUndefined()) {
784 Undefs.push_back(Name);
788 // Ignore local symbols.
789 if (Versym && VersymIndex == VER_NDX_LOCAL)
792 const Elf_Verdef *V =
793 VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
796 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
798 // Also add the symbol with the versioned name to handle undefined symbols
799 // with explicit versions.
801 StringRef VerName = this->StringTable.data() + V->getAux()->vda_name;
802 Name = Saver.save(Name + "@" + VerName);
803 elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
808 static ELFKind getBitcodeELFKind(const Triple &T) {
809 if (T.isLittleEndian())
810 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
811 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
814 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
815 switch (T.getArch()) {
816 case Triple::aarch64:
826 case Triple::mips64el:
833 return T.isOSIAMCU() ? EM_IAMCU : EM_386;
837 fatal(Path + ": could not infer e_machine from bitcode target triple " +
842 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
843 uint64_t OffsetInArchive)
844 : InputFile(BitcodeKind, MB) {
845 this->ArchiveName = ArchiveName;
847 // Here we pass a new MemoryBufferRef which is identified by ArchiveName
848 // (the fully resolved path of the archive) + member name + offset of the
849 // member in the archive.
850 // ThinLTO uses the MemoryBufferRef identifier to access its internal
851 // data structures and if two archives define two members with the same name,
852 // this causes a collision which result in only one of the objects being
853 // taken into consideration at LTO time (which very likely causes undefined
854 // symbols later in the link stage).
855 MemoryBufferRef MBRef(MB.getBuffer(),
856 Saver.save(ArchiveName + MB.getBufferIdentifier() +
857 utostr(OffsetInArchive)));
858 Obj = check(lto::InputFile::create(MBRef), toString(this));
860 Triple T(Obj->getTargetTriple());
861 EKind = getBitcodeELFKind(T);
862 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
865 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
866 switch (GvVisibility) {
867 case GlobalValue::DefaultVisibility:
869 case GlobalValue::HiddenVisibility:
871 case GlobalValue::ProtectedVisibility:
872 return STV_PROTECTED;
874 llvm_unreachable("unknown visibility");
877 template <class ELFT>
878 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
879 const lto::InputFile::Symbol &ObjSym,
881 StringRef NameRef = Saver.save(ObjSym.getName());
882 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
884 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
885 uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
886 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
888 int C = ObjSym.getComdatIndex();
889 if (C != -1 && !KeptComdats[C])
890 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding,
891 Visibility, Type, CanOmitFromDynSym,
894 if (ObjSym.isUndefined())
895 return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding,
896 Visibility, Type, CanOmitFromDynSym,
899 if (ObjSym.isCommon())
900 return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(),
901 ObjSym.getCommonAlignment(), Binding,
902 Visibility, STT_OBJECT, F);
904 return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type,
905 CanOmitFromDynSym, F);
908 template <class ELFT>
909 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
910 std::vector<bool> KeptComdats;
911 for (StringRef S : Obj->getComdatTable())
912 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
914 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
915 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this));
918 static ELFKind getELFKind(MemoryBufferRef MB) {
920 unsigned char Endian;
921 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
923 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
924 fatal(MB.getBufferIdentifier() + ": invalid data encoding");
925 if (Size != ELFCLASS32 && Size != ELFCLASS64)
926 fatal(MB.getBufferIdentifier() + ": invalid file class");
928 size_t BufSize = MB.getBuffer().size();
929 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
930 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
931 fatal(MB.getBufferIdentifier() + ": file is too short");
933 if (Size == ELFCLASS32)
934 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
935 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
938 template <class ELFT> void BinaryFile::parse() {
939 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
941 make<InputSection>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 8, Data, ".data");
942 Sections.push_back(Section);
944 // For each input file foo that is embedded to a result as a binary
945 // blob, we define _binary_foo_{start,end,size} symbols, so that
946 // user programs can access blobs by name. Non-alphanumeric
947 // characters in a filename are replaced with underscore.
948 std::string S = "_binary_" + MB.getBufferIdentifier().str();
949 for (size_t I = 0; I < S.size(); ++I)
953 elf::Symtab<ELFT>::X->addRegular(Saver.save(S + "_start"), STV_DEFAULT,
954 STT_OBJECT, 0, 0, STB_GLOBAL, Section,
956 elf::Symtab<ELFT>::X->addRegular(Saver.save(S + "_end"), STV_DEFAULT,
957 STT_OBJECT, Data.size(), 0, STB_GLOBAL,
959 elf::Symtab<ELFT>::X->addRegular(Saver.save(S + "_size"), STV_DEFAULT,
960 STT_OBJECT, Data.size(), 0, STB_GLOBAL,
964 static bool isBitcode(MemoryBufferRef MB) {
965 using namespace sys::fs;
966 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
969 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
970 uint64_t OffsetInArchive) {
972 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
974 switch (getELFKind(MB)) {
976 return make<ObjectFile<ELF32LE>>(MB, ArchiveName);
978 return make<ObjectFile<ELF32BE>>(MB, ArchiveName);
980 return make<ObjectFile<ELF64LE>>(MB, ArchiveName);
982 return make<ObjectFile<ELF64BE>>(MB, ArchiveName);
984 llvm_unreachable("getELFKind");
988 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
989 switch (getELFKind(MB)) {
991 return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
993 return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
995 return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
997 return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
999 llvm_unreachable("getELFKind");
1003 MemoryBufferRef LazyObjectFile::getBuffer() {
1005 return MemoryBufferRef();
1010 InputFile *LazyObjectFile::fetch() {
1011 MemoryBufferRef MBRef = getBuffer();
1012 if (MBRef.getBuffer().empty())
1014 return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1017 template <class ELFT> void LazyObjectFile::parse() {
1018 for (StringRef Sym : getSymbols())
1019 Symtab<ELFT>::X->addLazyObject(Sym, *this);
1022 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() {
1023 typedef typename ELFT::Shdr Elf_Shdr;
1024 typedef typename ELFT::Sym Elf_Sym;
1025 typedef typename ELFT::SymRange Elf_Sym_Range;
1027 const ELFFile<ELFT> Obj(this->MB.getBuffer());
1028 ArrayRef<Elf_Shdr> Sections = check(Obj.sections(), toString(this));
1029 for (const Elf_Shdr &Sec : Sections) {
1030 if (Sec.sh_type != SHT_SYMTAB)
1033 Elf_Sym_Range Syms = check(Obj.symbols(&Sec), toString(this));
1034 uint32_t FirstNonLocal = Sec.sh_info;
1035 StringRef StringTable =
1036 check(Obj.getStringTableForSymtab(Sec, Sections), toString(this));
1037 std::vector<StringRef> V;
1039 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1040 if (Sym.st_shndx != SHN_UNDEF)
1041 V.push_back(check(Sym.getName(StringTable), toString(this)));
1047 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() {
1048 std::unique_ptr<lto::InputFile> Obj =
1049 check(lto::InputFile::create(this->MB), toString(this));
1050 std::vector<StringRef> V;
1051 for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1052 if (!Sym.isUndefined())
1053 V.push_back(Saver.save(Sym.getName()));
1057 // Returns a vector of globally-visible defined symbol names.
1058 std::vector<StringRef> LazyObjectFile::getSymbols() {
1059 if (isBitcode(this->MB))
1060 return getBitcodeSymbols();
1062 switch (getELFKind(this->MB)) {
1064 return getElfSymbols<ELF32LE>();
1066 return getElfSymbols<ELF32BE>();
1068 return getElfSymbols<ELF64LE>();
1070 return getElfSymbols<ELF64BE>();
1072 llvm_unreachable("getELFKind");
1076 template void ArchiveFile::parse<ELF32LE>();
1077 template void ArchiveFile::parse<ELF32BE>();
1078 template void ArchiveFile::parse<ELF64LE>();
1079 template void ArchiveFile::parse<ELF64BE>();
1081 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1082 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1083 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1084 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1086 template void LazyObjectFile::parse<ELF32LE>();
1087 template void LazyObjectFile::parse<ELF32BE>();
1088 template void LazyObjectFile::parse<ELF64LE>();
1089 template void LazyObjectFile::parse<ELF64BE>();
1091 template class elf::ELFFileBase<ELF32LE>;
1092 template class elf::ELFFileBase<ELF32BE>;
1093 template class elf::ELFFileBase<ELF64LE>;
1094 template class elf::ELFFileBase<ELF64BE>;
1096 template class elf::ObjectFile<ELF32LE>;
1097 template class elf::ObjectFile<ELF32BE>;
1098 template class elf::ObjectFile<ELF64LE>;
1099 template class elf::ObjectFile<ELF64BE>;
1101 template class elf::SharedFile<ELF32LE>;
1102 template class elf::SharedFile<ELF32BE>;
1103 template class elf::SharedFile<ELF64LE>;
1104 template class elf::SharedFile<ELF64BE>;
1106 template void BinaryFile::parse<ELF32LE>();
1107 template void BinaryFile::parse<ELF32BE>();
1108 template void BinaryFile::parse<ELF64LE>();
1109 template void BinaryFile::parse<ELF64BE>();