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"
11 #include "InputSection.h"
12 #include "LinkerScript.h"
13 #include "SymbolTable.h"
15 #include "SyntheticSections.h"
16 #include "lld/Common/ErrorHandler.h"
17 #include "lld/Common/Memory.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/ARMAttributeParser.h"
27 #include "llvm/Support/ARMBuildAttributes.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/TarWriter.h"
30 #include "llvm/Support/raw_ostream.h"
33 using namespace llvm::ELF;
34 using namespace llvm::object;
35 using namespace llvm::sys::fs;
38 using namespace lld::elf;
40 std::vector<BinaryFile *> elf::BinaryFiles;
41 std::vector<BitcodeFile *> elf::BitcodeFiles;
42 std::vector<InputFile *> elf::ObjectFiles;
43 std::vector<InputFile *> elf::SharedFiles;
47 InputFile::InputFile(Kind K, MemoryBufferRef M) : MB(M), FileKind(K) {}
49 Optional<MemoryBufferRef> elf::readFile(StringRef Path) {
50 // The --chroot option changes our virtual root directory.
51 // This is useful when you are dealing with files created by --reproduce.
52 if (!Config->Chroot.empty() && Path.startswith("/"))
53 Path = Saver.save(Config->Chroot + Path);
57 auto MBOrErr = MemoryBuffer::getFile(Path);
58 if (auto EC = MBOrErr.getError()) {
59 error("cannot open " + Path + ": " + EC.message());
63 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
64 MemoryBufferRef MBRef = MB->getMemBufferRef();
65 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
68 Tar->append(relativeToRoot(Path), MBRef.getBuffer());
72 template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
73 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(this));
74 const DWARFObject &Obj = Dwarf.getDWARFObj();
75 DwarfLine.reset(new DWARFDebugLine);
76 DWARFDataExtractor LineData(Obj, Obj.getLineSection(), Config->IsLE,
79 // The second parameter is offset in .debug_line section
80 // for compilation unit (CU) of interest. We have only one
81 // CU (object file), so offset is always 0.
82 // FIXME: Provide the associated DWARFUnit if there is one. DWARF v5
83 // needs it in order to find indirect strings.
84 const DWARFDebugLine::LineTable *LT =
85 DwarfLine->getOrParseLineTable(LineData, 0, nullptr);
87 // Return if there is no debug information about CU available.
88 if (!Dwarf.getNumCompileUnits())
91 // Loop over variable records and insert them to VariableLoc.
92 DWARFCompileUnit *CU = Dwarf.getCompileUnitAtIndex(0);
93 for (const auto &Entry : CU->dies()) {
94 DWARFDie Die(CU, &Entry);
95 // Skip all tags that are not variables.
96 if (Die.getTag() != dwarf::DW_TAG_variable)
99 // Skip if a local variable because we don't need them for generating error
100 // messages. In general, only non-local symbols can fail to be linked.
101 if (!dwarf::toUnsigned(Die.find(dwarf::DW_AT_external), 0))
104 // Get the source filename index for the variable.
105 unsigned File = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_file), 0);
106 if (!LT->hasFileAtIndex(File))
109 // Get the line number on which the variable is declared.
110 unsigned Line = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_line), 0);
112 // Get the name of the variable and add the collected information to
113 // VariableLoc. Usually Name is non-empty, but it can be empty if the input
114 // object file lacks some debug info.
115 StringRef Name = dwarf::toString(Die.find(dwarf::DW_AT_name), "");
117 VariableLoc.insert({Name, {File, Line}});
121 // Returns the pair of file name and line number describing location of data
122 // object (variable, array, etc) definition.
123 template <class ELFT>
124 Optional<std::pair<std::string, unsigned>>
125 ObjFile<ELFT>::getVariableLoc(StringRef Name) {
126 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
128 // There is always only one CU so it's offset is 0.
129 const DWARFDebugLine::LineTable *LT = DwarfLine->getLineTable(0);
133 // Return if we have no debug information about data object.
134 auto It = VariableLoc.find(Name);
135 if (It == VariableLoc.end())
138 // Take file name string from line table.
139 std::string FileName;
140 if (!LT->getFileNameByIndex(
141 It->second.first /* File */, nullptr,
142 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FileName))
145 return std::make_pair(FileName, It->second.second /*Line*/);
148 // Returns source line information for a given offset
149 // using DWARF debug info.
150 template <class ELFT>
151 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *S,
153 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
155 // The offset to CU is 0.
156 const DWARFDebugLine::LineTable *Tbl = DwarfLine->getLineTable(0);
160 // Use fake address calcuated by adding section file offset and offset in
161 // section. See comments for ObjectInfo class.
163 Tbl->getFileLineInfoForAddress(
164 S->getOffsetInFile() + Offset, nullptr,
165 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info);
171 // Returns source line information for a given offset
172 // using DWARF debug info.
173 template <class ELFT>
174 std::string ObjFile<ELFT>::getLineInfo(InputSectionBase *S, uint64_t Offset) {
175 if (Optional<DILineInfo> Info = getDILineInfo(S, Offset))
176 return Info->FileName + ":" + std::to_string(Info->Line);
180 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
181 std::string lld::toString(const InputFile *F) {
185 if (F->ToStringCache.empty()) {
186 if (F->ArchiveName.empty())
187 F->ToStringCache = F->getName();
189 F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str();
191 return F->ToStringCache;
194 template <class ELFT>
195 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
196 if (ELFT::TargetEndianness == support::little)
197 EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
199 EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
201 EMachine = getObj().getHeader()->e_machine;
202 OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
205 template <class ELFT>
206 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalELFSyms() {
207 return makeArrayRef(ELFSyms.begin() + FirstNonLocal, ELFSyms.end());
210 template <class ELFT>
211 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
212 return CHECK(getObj().getSectionIndex(&Sym, ELFSyms, SymtabSHNDX), this);
215 template <class ELFT>
216 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
217 const Elf_Shdr *Symtab) {
218 FirstNonLocal = Symtab->sh_info;
219 ELFSyms = CHECK(getObj().symbols(Symtab), this);
220 if (FirstNonLocal == 0 || FirstNonLocal > ELFSyms.size())
221 fatal(toString(this) + ": invalid sh_info in symbol table");
224 CHECK(getObj().getStringTableForSymtab(*Symtab, Sections), this);
227 template <class ELFT>
228 ObjFile<ELFT>::ObjFile(MemoryBufferRef M, StringRef ArchiveName)
229 : ELFFileBase<ELFT>(Base::ObjKind, M) {
230 this->ArchiveName = ArchiveName;
233 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
234 if (this->Symbols.empty())
236 return makeArrayRef(this->Symbols).slice(1, this->FirstNonLocal - 1);
239 template <class ELFT>
240 void ObjFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
241 // Read section and symbol tables.
242 initializeSections(ComdatGroups);
246 // Sections with SHT_GROUP and comdat bits define comdat section groups.
247 // They are identified and deduplicated by group name. This function
248 // returns a group name.
249 template <class ELFT>
250 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
251 const Elf_Shdr &Sec) {
252 // Group signatures are stored as symbol names in object files.
253 // sh_info contains a symbol index, so we fetch a symbol and read its name.
254 if (this->ELFSyms.empty())
256 Sections, CHECK(object::getSection<ELFT>(Sections, Sec.sh_link), this));
259 CHECK(object::getSymbol<ELFT>(this->ELFSyms, Sec.sh_info), this);
260 StringRef Signature = CHECK(Sym->getName(this->StringTable), this);
262 // As a special case, if a symbol is a section symbol and has no name,
263 // we use a section name as a signature.
265 // Such SHT_GROUP sections are invalid from the perspective of the ELF
266 // standard, but GNU gold 1.14 (the neweset version as of July 2017) or
267 // older produce such sections as outputs for the -r option, so we need
268 // a bug-compatibility.
269 if (Signature.empty() && Sym->getType() == STT_SECTION)
270 return getSectionName(Sec);
274 template <class ELFT>
275 ArrayRef<typename ObjFile<ELFT>::Elf_Word>
276 ObjFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
277 const ELFFile<ELFT> &Obj = this->getObj();
278 ArrayRef<Elf_Word> Entries =
279 CHECK(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), this);
280 if (Entries.empty() || Entries[0] != GRP_COMDAT)
281 fatal(toString(this) + ": unsupported SHT_GROUP format");
282 return Entries.slice(1);
285 template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
286 // We don't merge sections if -O0 (default is -O1). This makes sometimes
287 // the linker significantly faster, although the output will be bigger.
288 if (Config->Optimize == 0)
291 // A mergeable section with size 0 is useless because they don't have
292 // any data to merge. A mergeable string section with size 0 can be
293 // argued as invalid because it doesn't end with a null character.
294 // We'll avoid a mess by handling them as if they were non-mergeable.
295 if (Sec.sh_size == 0)
298 // Check for sh_entsize. The ELF spec is not clear about the zero
299 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
300 // the section does not hold a table of fixed-size entries". We know
301 // that Rust 1.13 produces a string mergeable section with a zero
302 // sh_entsize. Here we just accept it rather than being picky about it.
303 uint64_t EntSize = Sec.sh_entsize;
306 if (Sec.sh_size % EntSize)
307 fatal(toString(this) +
308 ": SHF_MERGE section size must be a multiple of sh_entsize");
310 uint64_t Flags = Sec.sh_flags;
311 if (!(Flags & SHF_MERGE))
313 if (Flags & SHF_WRITE)
314 fatal(toString(this) + ": writable SHF_MERGE section is not supported");
319 template <class ELFT>
320 void ObjFile<ELFT>::initializeSections(
321 DenseSet<CachedHashStringRef> &ComdatGroups) {
322 const ELFFile<ELFT> &Obj = this->getObj();
324 ArrayRef<Elf_Shdr> ObjSections = CHECK(this->getObj().sections(), this);
325 uint64_t Size = ObjSections.size();
326 this->Sections.resize(Size);
327 this->SectionStringTable =
328 CHECK(Obj.getSectionStringTable(ObjSections), this);
330 for (size_t I = 0, E = ObjSections.size(); I < E; I++) {
331 if (this->Sections[I] == &InputSection::Discarded)
333 const Elf_Shdr &Sec = ObjSections[I];
335 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
336 // if -r is given, we'll let the final link discard such sections.
337 // This is compatible with GNU.
338 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
339 this->Sections[I] = &InputSection::Discarded;
343 switch (Sec.sh_type) {
345 // De-duplicate section groups by their signatures.
346 StringRef Signature = getShtGroupSignature(ObjSections, Sec);
347 bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second;
348 this->Sections[I] = &InputSection::Discarded;
350 // If it is a new section group, we want to keep group members.
351 // Group leader sections, which contain indices of group members, are
352 // discarded because they are useless beyond this point. The only
353 // exception is the -r option because in order to produce re-linkable
354 // object files, we want to pass through basically everything.
356 if (Config->Relocatable)
357 this->Sections[I] = createInputSection(Sec);
361 // Otherwise, discard group members.
362 for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
363 if (SecIndex >= Size)
364 fatal(toString(this) +
365 ": invalid section index in group: " + Twine(SecIndex));
366 this->Sections[SecIndex] = &InputSection::Discarded;
371 this->initSymtab(ObjSections, &Sec);
373 case SHT_SYMTAB_SHNDX:
374 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, ObjSections), this);
380 this->Sections[I] = createInputSection(Sec);
383 // .ARM.exidx sections have a reverse dependency on the InputSection they
384 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
385 if (Sec.sh_flags & SHF_LINK_ORDER) {
386 if (Sec.sh_link >= this->Sections.size())
387 fatal(toString(this) + ": invalid sh_link index: " +
389 this->Sections[Sec.sh_link]->DependentSections.push_back(
390 cast<InputSection>(this->Sections[I]));
395 // The ARM support in lld makes some use of instructions that are not available
396 // on all ARM architectures. Namely:
397 // - Use of BLX instruction for interworking between ARM and Thumb state.
398 // - Use of the extended Thumb branch encoding in relocation.
399 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
400 // The ARM Attributes section contains information about the architecture chosen
401 // at compile time. We follow the convention that if at least one input object
402 // is compiled with an architecture that supports these features then lld is
403 // permitted to use them.
404 static void updateSupportedARMFeatures(const ARMAttributeParser &Attributes) {
405 if (!Attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
407 auto Arch = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
409 case ARMBuildAttrs::Pre_v4:
410 case ARMBuildAttrs::v4:
411 case ARMBuildAttrs::v4T:
412 // Architectures prior to v5 do not support BLX instruction
414 case ARMBuildAttrs::v5T:
415 case ARMBuildAttrs::v5TE:
416 case ARMBuildAttrs::v5TEJ:
417 case ARMBuildAttrs::v6:
418 case ARMBuildAttrs::v6KZ:
419 case ARMBuildAttrs::v6K:
420 Config->ARMHasBlx = true;
421 // Architectures used in pre-Cortex processors do not support
422 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
423 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
426 // All other Architectures have BLX and extended branch encoding
427 Config->ARMHasBlx = true;
428 Config->ARMJ1J2BranchEncoding = true;
429 if (Arch != ARMBuildAttrs::v6_M && Arch != ARMBuildAttrs::v6S_M)
430 // All Architectures used in Cortex processors with the exception
431 // of v6-M and v6S-M have the MOVT and MOVW instructions.
432 Config->ARMHasMovtMovw = true;
437 template <class ELFT>
438 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
439 uint32_t Idx = Sec.sh_info;
440 if (Idx >= this->Sections.size())
441 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
442 InputSectionBase *Target = this->Sections[Idx];
444 // Strictly speaking, a relocation section must be included in the
445 // group of the section it relocates. However, LLVM 3.3 and earlier
446 // would fail to do so, so we gracefully handle that case.
447 if (Target == &InputSection::Discarded)
451 fatal(toString(this) + ": unsupported relocation reference");
455 // Create a regular InputSection class that has the same contents
456 // as a given section.
457 InputSectionBase *toRegularSection(MergeInputSection *Sec) {
458 auto *Ret = make<InputSection>(Sec->Flags, Sec->Type, Sec->Alignment,
459 Sec->Data, Sec->Name);
460 Ret->File = Sec->File;
464 template <class ELFT>
465 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
466 StringRef Name = getSectionName(Sec);
468 switch (Sec.sh_type) {
469 case SHT_ARM_ATTRIBUTES: {
470 if (Config->EMachine != EM_ARM)
472 ARMAttributeParser Attributes;
473 ArrayRef<uint8_t> Contents = check(this->getObj().getSectionContents(&Sec));
474 Attributes.Parse(Contents, /*isLittle*/Config->EKind == ELF32LEKind);
475 updateSupportedARMFeatures(Attributes);
476 // FIXME: Retain the first attribute section we see. The eglibc ARM
477 // dynamic loaders require the presence of an attribute section for dlopen
478 // to work. In a full implementation we would merge all attribute sections.
479 if (InX::ARMAttributes == nullptr) {
480 InX::ARMAttributes = make<InputSection>(this, &Sec, Name);
481 return InX::ARMAttributes;
483 return &InputSection::Discarded;
487 // Find the relocation target section and associate this
488 // section with it. Target can be discarded, for example
489 // if it is a duplicated member of SHT_GROUP section, we
490 // do not create or proccess relocatable sections then.
491 InputSectionBase *Target = getRelocTarget(Sec);
495 // This section contains relocation information.
496 // If -r is given, we do not interpret or apply relocation
497 // but just copy relocation sections to output.
498 if (Config->Relocatable)
499 return make<InputSection>(this, &Sec, Name);
501 if (Target->FirstRelocation)
502 fatal(toString(this) +
503 ": multiple relocation sections to one section are not supported");
505 // Mergeable sections with relocations are tricky because relocations
506 // need to be taken into account when comparing section contents for
507 // merging. It's not worth supporting such mergeable sections because
508 // they are rare and it'd complicates the internal design (we usually
509 // have to determine if two sections are mergeable early in the link
510 // process much before applying relocations). We simply handle mergeable
511 // sections with relocations as non-mergeable.
512 if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
513 Target = toRegularSection(MS);
514 this->Sections[Sec.sh_info] = Target;
517 size_t NumRelocations;
518 if (Sec.sh_type == SHT_RELA) {
519 ArrayRef<Elf_Rela> Rels = CHECK(this->getObj().relas(&Sec), this);
520 Target->FirstRelocation = Rels.begin();
521 NumRelocations = Rels.size();
522 Target->AreRelocsRela = true;
524 ArrayRef<Elf_Rel> Rels = CHECK(this->getObj().rels(&Sec), this);
525 Target->FirstRelocation = Rels.begin();
526 NumRelocations = Rels.size();
527 Target->AreRelocsRela = false;
529 assert(isUInt<31>(NumRelocations));
530 Target->NumRelocations = NumRelocations;
532 // Relocation sections processed by the linker are usually removed
533 // from the output, so returning `nullptr` for the normal case.
534 // However, if -emit-relocs is given, we need to leave them in the output.
535 // (Some post link analysis tools need this information.)
536 if (Config->EmitRelocs) {
537 InputSection *RelocSec = make<InputSection>(this, &Sec, Name);
538 // We will not emit relocation section if target was discarded.
539 Target->DependentSections.push_back(RelocSec);
546 // The GNU linker uses .note.GNU-stack section as a marker indicating
547 // that the code in the object file does not expect that the stack is
548 // executable (in terms of NX bit). If all input files have the marker,
549 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
550 // make the stack non-executable. Most object files have this section as
553 // But making the stack non-executable is a norm today for security
554 // reasons. Failure to do so may result in a serious security issue.
555 // Therefore, we make LLD always add PT_GNU_STACK unless it is
556 // explicitly told to do otherwise (by -z execstack). Because the stack
557 // executable-ness is controlled solely by command line options,
558 // .note.GNU-stack sections are simply ignored.
559 if (Name == ".note.GNU-stack")
560 return &InputSection::Discarded;
562 // Split stacks is a feature to support a discontiguous stack. At least
563 // as of 2017, it seems that the feature is not being used widely.
564 // Only GNU gold supports that. We don't. For the details about that,
565 // see https://gcc.gnu.org/wiki/SplitStacks
566 if (Name == ".note.GNU-split-stack") {
567 error(toString(this) +
568 ": object file compiled with -fsplit-stack is not supported");
569 return &InputSection::Discarded;
572 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
573 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
574 // sections. Drop those sections to avoid duplicate symbol errors.
575 // FIXME: This is glibc PR20543, we should remove this hack once that has been
576 // fixed for a while.
577 if (Name.startswith(".gnu.linkonce."))
578 return &InputSection::Discarded;
580 // The linker merges EH (exception handling) frames and creates a
581 // .eh_frame_hdr section for runtime. So we handle them with a special
582 // class. For relocatable outputs, they are just passed through.
583 if (Name == ".eh_frame" && !Config->Relocatable)
584 return make<EhInputSection>(this, &Sec, Name);
586 if (shouldMerge(Sec))
587 return make<MergeInputSection>(this, &Sec, Name);
588 return make<InputSection>(this, &Sec, Name);
591 template <class ELFT>
592 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
593 return CHECK(this->getObj().getSectionName(&Sec, SectionStringTable), this);
596 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
597 this->Symbols.reserve(this->ELFSyms.size());
598 for (const Elf_Sym &Sym : this->ELFSyms)
599 this->Symbols.push_back(createSymbol(&Sym));
602 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) {
603 int Binding = Sym->getBinding();
605 uint32_t SecIdx = this->getSectionIndex(*Sym);
606 if (SecIdx >= this->Sections.size())
607 fatal(toString(this) + ": invalid section index: " + Twine(SecIdx));
609 InputSectionBase *Sec = this->Sections[SecIdx];
610 uint8_t StOther = Sym->st_other;
611 uint8_t Type = Sym->getType();
612 uint64_t Value = Sym->st_value;
613 uint64_t Size = Sym->st_size;
615 if (Binding == STB_LOCAL) {
616 if (Sym->getType() == STT_FILE)
617 SourceFile = CHECK(Sym->getName(this->StringTable), this);
619 if (this->StringTable.size() <= Sym->st_name)
620 fatal(toString(this) + ": invalid symbol name offset");
622 StringRefZ Name = this->StringTable.data() + Sym->st_name;
623 if (Sym->st_shndx == SHN_UNDEF)
624 return make<Undefined>(this, Name, Binding, StOther, Type);
626 return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec);
629 StringRef Name = CHECK(Sym->getName(this->StringTable), this);
631 switch (Sym->st_shndx) {
633 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
634 /*CanOmitFromDynSym=*/false, this);
636 if (Value == 0 || Value >= UINT32_MAX)
637 fatal(toString(this) + ": common symbol '" + Name +
638 "' has invalid alignment: " + Twine(Value));
639 return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, this);
644 fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
648 if (Sec == &InputSection::Discarded)
649 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
650 /*CanOmitFromDynSym=*/false, this);
651 return Symtab->addRegular<ELFT>(Name, StOther, Type, Value, Size, Binding,
656 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
657 : InputFile(ArchiveKind, File->getMemoryBufferRef()),
658 File(std::move(File)) {}
660 template <class ELFT> void ArchiveFile::parse() {
661 Symbols.reserve(File->getNumberOfSymbols());
662 for (const Archive::Symbol &Sym : File->symbols())
663 Symbols.push_back(Symtab->addLazyArchive<ELFT>(Sym.getName(), this, Sym));
666 // Returns a buffer pointing to a member file containing a given symbol.
667 std::pair<MemoryBufferRef, uint64_t>
668 ArchiveFile::getMember(const Archive::Symbol *Sym) {
670 CHECK(Sym->getMember(), toString(this) +
671 ": could not get the member for symbol " +
674 if (!Seen.insert(C.getChildOffset()).second)
675 return {MemoryBufferRef(), 0};
677 MemoryBufferRef Ret =
678 CHECK(C.getMemoryBufferRef(),
680 ": could not get the buffer for the member defining symbol " +
683 if (C.getParent()->isThin() && Tar)
684 Tar->append(relativeToRoot(CHECK(C.getFullName(), this)), Ret.getBuffer());
685 if (C.getParent()->isThin())
687 return {Ret, C.getChildOffset()};
690 template <class ELFT>
691 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
692 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
693 IsNeeded(!Config->AsNeeded) {}
695 // Partially parse the shared object file so that we can call
696 // getSoName on this object.
697 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
698 const Elf_Shdr *DynamicSec = nullptr;
699 const ELFFile<ELFT> Obj = this->getObj();
700 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
702 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
703 for (const Elf_Shdr &Sec : Sections) {
704 switch (Sec.sh_type) {
708 this->initSymtab(Sections, &Sec);
713 case SHT_SYMTAB_SHNDX:
714 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this);
717 this->VersymSec = &Sec;
720 this->VerdefSec = &Sec;
725 if (this->VersymSec && this->ELFSyms.empty())
726 error("SHT_GNU_versym should be associated with symbol table");
728 // Search for a DT_SONAME tag to initialize this->SoName.
731 ArrayRef<Elf_Dyn> Arr =
732 CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this);
733 for (const Elf_Dyn &Dyn : Arr) {
734 if (Dyn.d_tag == DT_SONAME) {
735 uint64_t Val = Dyn.getVal();
736 if (Val >= this->StringTable.size())
737 fatal(toString(this) + ": invalid DT_SONAME entry");
738 SoName = this->StringTable.data() + Val;
744 // Parse the version definitions in the object file if present. Returns a vector
745 // whose nth element contains a pointer to the Elf_Verdef for version identifier
746 // n. Version identifiers that are not definitions map to nullptr. The array
747 // always has at least length 1.
748 template <class ELFT>
749 std::vector<const typename ELFT::Verdef *>
750 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
751 std::vector<const Elf_Verdef *> Verdefs(1);
752 // We only need to process symbol versions for this DSO if it has both a
753 // versym and a verdef section, which indicates that the DSO contains symbol
754 // version definitions.
755 if (!VersymSec || !VerdefSec)
758 // The location of the first global versym entry.
759 const char *Base = this->MB.getBuffer().data();
760 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
763 // We cannot determine the largest verdef identifier without inspecting
764 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
765 // sequentially starting from 1, so we predict that the largest identifier
766 // will be VerdefCount.
767 unsigned VerdefCount = VerdefSec->sh_info;
768 Verdefs.resize(VerdefCount + 1);
770 // Build the Verdefs array by following the chain of Elf_Verdef objects
771 // from the start of the .gnu.version_d section.
772 const char *Verdef = Base + VerdefSec->sh_offset;
773 for (unsigned I = 0; I != VerdefCount; ++I) {
774 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
775 Verdef += CurVerdef->vd_next;
776 unsigned VerdefIndex = CurVerdef->vd_ndx;
777 if (Verdefs.size() <= VerdefIndex)
778 Verdefs.resize(VerdefIndex + 1);
779 Verdefs[VerdefIndex] = CurVerdef;
785 // Fully parse the shared object file. This must be called after parseSoName().
786 template <class ELFT> void SharedFile<ELFT>::parseRest() {
787 // Create mapping from version identifiers to Elf_Verdef entries.
788 const Elf_Versym *Versym = nullptr;
789 Verdefs = parseVerdefs(Versym);
791 ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this);
793 // Add symbols to the symbol table.
794 Elf_Sym_Range Syms = this->getGlobalELFSyms();
795 for (const Elf_Sym &Sym : Syms) {
796 unsigned VersymIndex = VER_NDX_GLOBAL;
798 VersymIndex = Versym->vs_index;
801 bool Hidden = VersymIndex & VERSYM_HIDDEN;
802 VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
804 StringRef Name = CHECK(Sym.getName(this->StringTable), this);
805 if (Sym.isUndefined()) {
806 Undefs.push_back(Name);
810 if (Sym.getBinding() == STB_LOCAL) {
811 warn("found local symbol '" + Name +
812 "' in global part of symbol table in file " + toString(this));
816 const Elf_Verdef *Ver = nullptr;
817 if (VersymIndex != VER_NDX_GLOBAL) {
818 if (VersymIndex >= Verdefs.size() || VersymIndex == VER_NDX_LOCAL) {
819 error("corrupt input file: version definition index " +
820 Twine(VersymIndex) + " for symbol " + Name +
821 " is out of bounds\n>>> defined in " + toString(this));
824 Ver = Verdefs[VersymIndex];
829 // We do not usually care about alignments of data in shared object
830 // files because the loader takes care of it. However, if we promote a
831 // DSO symbol to point to .bss due to copy relocation, we need to keep
832 // the original alignment requirements. We infer it here.
833 uint64_t Alignment = 1;
835 Alignment = 1ULL << countTrailingZeros((uint64_t)Sym.st_value);
836 if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) {
837 uint64_t SecAlign = Sections[Sym.st_shndx].sh_addralign;
838 Alignment = std::min(Alignment, SecAlign);
840 if (Alignment > UINT32_MAX)
841 error(toString(this) + ": alignment too large: " + Name);
844 Symtab->addShared(Name, this, Sym, Alignment, VersymIndex);
846 // Also add the symbol with the versioned name to handle undefined symbols
847 // with explicit versions.
849 StringRef VerName = this->StringTable.data() + Ver->getAux()->vda_name;
850 Name = Saver.save(Name + "@" + VerName);
851 Symtab->addShared(Name, this, Sym, Alignment, VersymIndex);
856 static ELFKind getBitcodeELFKind(const Triple &T) {
857 if (T.isLittleEndian())
858 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
859 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
862 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
863 switch (T.getArch()) {
864 case Triple::aarch64:
874 case Triple::mips64el:
881 return T.isOSIAMCU() ? EM_IAMCU : EM_386;
885 fatal(Path + ": could not infer e_machine from bitcode target triple " +
890 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
891 uint64_t OffsetInArchive)
892 : InputFile(BitcodeKind, MB) {
893 this->ArchiveName = ArchiveName;
895 // Here we pass a new MemoryBufferRef which is identified by ArchiveName
896 // (the fully resolved path of the archive) + member name + offset of the
897 // member in the archive.
898 // ThinLTO uses the MemoryBufferRef identifier to access its internal
899 // data structures and if two archives define two members with the same name,
900 // this causes a collision which result in only one of the objects being
901 // taken into consideration at LTO time (which very likely causes undefined
902 // symbols later in the link stage).
903 MemoryBufferRef MBRef(MB.getBuffer(),
904 Saver.save(ArchiveName + MB.getBufferIdentifier() +
905 utostr(OffsetInArchive)));
906 Obj = CHECK(lto::InputFile::create(MBRef), this);
908 Triple T(Obj->getTargetTriple());
909 EKind = getBitcodeELFKind(T);
910 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
913 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
914 switch (GvVisibility) {
915 case GlobalValue::DefaultVisibility:
917 case GlobalValue::HiddenVisibility:
919 case GlobalValue::ProtectedVisibility:
920 return STV_PROTECTED;
922 llvm_unreachable("unknown visibility");
925 template <class ELFT>
926 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
927 const lto::InputFile::Symbol &ObjSym,
929 StringRef NameRef = Saver.save(ObjSym.getName());
930 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
932 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
933 uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
934 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
936 int C = ObjSym.getComdatIndex();
937 if (C != -1 && !KeptComdats[C])
938 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
939 CanOmitFromDynSym, F);
941 if (ObjSym.isUndefined())
942 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
943 CanOmitFromDynSym, F);
945 if (ObjSym.isCommon())
946 return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
947 ObjSym.getCommonAlignment(), Binding, Visibility,
950 return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
951 CanOmitFromDynSym, F);
954 template <class ELFT>
955 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
956 std::vector<bool> KeptComdats;
957 for (StringRef S : Obj->getComdatTable())
958 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
960 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
961 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this));
964 static ELFKind getELFKind(MemoryBufferRef MB) {
966 unsigned char Endian;
967 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
969 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
970 fatal(MB.getBufferIdentifier() + ": invalid data encoding");
971 if (Size != ELFCLASS32 && Size != ELFCLASS64)
972 fatal(MB.getBufferIdentifier() + ": invalid file class");
974 size_t BufSize = MB.getBuffer().size();
975 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
976 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
977 fatal(MB.getBufferIdentifier() + ": file is too short");
979 if (Size == ELFCLASS32)
980 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
981 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
984 template <class ELFT> void BinaryFile::parse() {
985 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
987 make<InputSection>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, 8, Data, ".data");
988 Sections.push_back(Section);
990 // For each input file foo that is embedded to a result as a binary
991 // blob, we define _binary_foo_{start,end,size} symbols, so that
992 // user programs can access blobs by name. Non-alphanumeric
993 // characters in a filename are replaced with underscore.
994 std::string S = "_binary_" + MB.getBufferIdentifier().str();
995 for (size_t I = 0; I < S.size(); ++I)
999 Symtab->addRegular<ELFT>(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT,
1000 0, 0, STB_GLOBAL, Section, nullptr);
1001 Symtab->addRegular<ELFT>(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
1002 Data.size(), 0, STB_GLOBAL, Section, nullptr);
1003 Symtab->addRegular<ELFT>(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
1004 Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
1007 static bool isBitcode(MemoryBufferRef MB) {
1008 using namespace sys::fs;
1009 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
1012 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
1013 uint64_t OffsetInArchive) {
1015 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
1017 switch (getELFKind(MB)) {
1019 return make<ObjFile<ELF32LE>>(MB, ArchiveName);
1021 return make<ObjFile<ELF32BE>>(MB, ArchiveName);
1023 return make<ObjFile<ELF64LE>>(MB, ArchiveName);
1025 return make<ObjFile<ELF64BE>>(MB, ArchiveName);
1027 llvm_unreachable("getELFKind");
1031 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
1032 switch (getELFKind(MB)) {
1034 return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
1036 return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
1038 return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
1040 return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
1042 llvm_unreachable("getELFKind");
1046 MemoryBufferRef LazyObjFile::getBuffer() {
1048 return MemoryBufferRef();
1053 InputFile *LazyObjFile::fetch() {
1054 MemoryBufferRef MBRef = getBuffer();
1055 if (MBRef.getBuffer().empty())
1057 return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1060 template <class ELFT> void LazyObjFile::parse() {
1061 for (StringRef Sym : getSymbolNames())
1062 Symtab->addLazyObject<ELFT>(Sym, *this);
1065 template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
1066 typedef typename ELFT::Shdr Elf_Shdr;
1067 typedef typename ELFT::Sym Elf_Sym;
1068 typedef typename ELFT::SymRange Elf_Sym_Range;
1070 ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(this->MB.getBuffer()));
1071 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
1072 for (const Elf_Shdr &Sec : Sections) {
1073 if (Sec.sh_type != SHT_SYMTAB)
1076 Elf_Sym_Range Syms = CHECK(Obj.symbols(&Sec), this);
1077 uint32_t FirstNonLocal = Sec.sh_info;
1078 StringRef StringTable =
1079 CHECK(Obj.getStringTableForSymtab(Sec, Sections), this);
1080 std::vector<StringRef> V;
1082 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1083 if (Sym.st_shndx != SHN_UNDEF)
1084 V.push_back(CHECK(Sym.getName(StringTable), this));
1090 std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1091 std::unique_ptr<lto::InputFile> Obj =
1092 CHECK(lto::InputFile::create(this->MB), this);
1093 std::vector<StringRef> V;
1094 for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1095 if (!Sym.isUndefined())
1096 V.push_back(Saver.save(Sym.getName()));
1100 // Returns a vector of globally-visible defined symbol names.
1101 std::vector<StringRef> LazyObjFile::getSymbolNames() {
1102 if (isBitcode(this->MB))
1103 return getBitcodeSymbols();
1105 switch (getELFKind(this->MB)) {
1107 return getElfSymbols<ELF32LE>();
1109 return getElfSymbols<ELF32BE>();
1111 return getElfSymbols<ELF64LE>();
1113 return getElfSymbols<ELF64BE>();
1115 llvm_unreachable("getELFKind");
1119 template void ArchiveFile::parse<ELF32LE>();
1120 template void ArchiveFile::parse<ELF32BE>();
1121 template void ArchiveFile::parse<ELF64LE>();
1122 template void ArchiveFile::parse<ELF64BE>();
1124 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1125 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1126 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1127 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1129 template void LazyObjFile::parse<ELF32LE>();
1130 template void LazyObjFile::parse<ELF32BE>();
1131 template void LazyObjFile::parse<ELF64LE>();
1132 template void LazyObjFile::parse<ELF64BE>();
1134 template class elf::ELFFileBase<ELF32LE>;
1135 template class elf::ELFFileBase<ELF32BE>;
1136 template class elf::ELFFileBase<ELF64LE>;
1137 template class elf::ELFFileBase<ELF64BE>;
1139 template class elf::ObjFile<ELF32LE>;
1140 template class elf::ObjFile<ELF32BE>;
1141 template class elf::ObjFile<ELF64LE>;
1142 template class elf::ObjFile<ELF64BE>;
1144 template class elf::SharedFile<ELF32LE>;
1145 template class elf::SharedFile<ELF32BE>;
1146 template class elf::SharedFile<ELF64LE>;
1147 template class elf::SharedFile<ELF64BE>;
1149 template void BinaryFile::parse<ELF32LE>();
1150 template void BinaryFile::parse<ELF32BE>();
1151 template void BinaryFile::parse<ELF64LE>();
1152 template void BinaryFile::parse<ELF64BE>();