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