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;
36 using namespace llvm::sys::fs;
39 using namespace lld::elf;
41 std::vector<BinaryFile *> elf::BinaryFiles;
42 std::vector<BitcodeFile *> elf::BitcodeFiles;
43 std::vector<InputFile *> elf::ObjectFiles;
44 std::vector<InputFile *> elf::SharedFiles;
48 InputFile::InputFile(Kind K, MemoryBufferRef M) : MB(M), FileKind(K) {}
50 Optional<MemoryBufferRef> elf::readFile(StringRef Path) {
51 // The --chroot option changes our virtual root directory.
52 // This is useful when you are dealing with files created by --reproduce.
53 if (!Config->Chroot.empty() && Path.startswith("/"))
54 Path = Saver.save(Config->Chroot + 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 // Concatenates arguments to construct a string representing an error location.
74 static std::string createFileLineMsg(StringRef Path, unsigned Line) {
75 std::string Filename = path::filename(Path);
76 std::string Lineno = ":" + std::to_string(Line);
78 return Filename + Lineno;
79 return Filename + Lineno + " (" + Path.str() + Lineno + ")";
83 static std::string getSrcMsgAux(ObjFile<ELFT> &File, const Symbol &Sym,
84 InputSectionBase &Sec, uint64_t Offset) {
85 // In DWARF, functions and variables are stored to different places.
86 // First, lookup a function for a given offset.
87 if (Optional<DILineInfo> Info = File.getDILineInfo(&Sec, Offset))
88 return createFileLineMsg(Info->FileName, Info->Line);
90 // If it failed, lookup again as a variable.
91 if (Optional<std::pair<std::string, unsigned>> FileLine =
92 File.getVariableLoc(Sym.getName()))
93 return createFileLineMsg(FileLine->first, FileLine->second);
95 // File.SourceFile contains STT_FILE symbol, and that is a last resort.
96 return File.SourceFile;
99 std::string InputFile::getSrcMsg(const Symbol &Sym, InputSectionBase &Sec,
101 if (kind() != ObjKind)
103 switch (Config->EKind) {
105 llvm_unreachable("Invalid kind");
107 return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), Sym, Sec, Offset);
109 return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), Sym, Sec, Offset);
111 return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), Sym, Sec, Offset);
113 return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), Sym, Sec, Offset);
117 template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
118 DWARFContext Dwarf(make_unique<LLDDwarfObj<ELFT>>(this));
119 const DWARFObject &Obj = Dwarf.getDWARFObj();
120 DwarfLine.reset(new DWARFDebugLine);
121 DWARFDataExtractor LineData(Obj, Obj.getLineSection(), Config->IsLE,
124 // The second parameter is offset in .debug_line section
125 // for compilation unit (CU) of interest. We have only one
126 // CU (object file), so offset is always 0.
127 // FIXME: Provide the associated DWARFUnit if there is one. DWARF v5
128 // needs it in order to find indirect strings.
129 const DWARFDebugLine::LineTable *LT =
130 DwarfLine->getOrParseLineTable(LineData, 0, nullptr);
132 // Return if there is no debug information about CU available.
133 if (!Dwarf.getNumCompileUnits())
136 // Loop over variable records and insert them to VariableLoc.
137 DWARFCompileUnit *CU = Dwarf.getCompileUnitAtIndex(0);
138 for (const auto &Entry : CU->dies()) {
139 DWARFDie Die(CU, &Entry);
140 // Skip all tags that are not variables.
141 if (Die.getTag() != dwarf::DW_TAG_variable)
144 // Skip if a local variable because we don't need them for generating error
145 // messages. In general, only non-local symbols can fail to be linked.
146 if (!dwarf::toUnsigned(Die.find(dwarf::DW_AT_external), 0))
149 // Get the source filename index for the variable.
150 unsigned File = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_file), 0);
151 if (!LT->hasFileAtIndex(File))
154 // Get the line number on which the variable is declared.
155 unsigned Line = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_line), 0);
157 // Get the name of the variable and add the collected information to
158 // VariableLoc. Usually Name is non-empty, but it can be empty if the input
159 // object file lacks some debug info.
160 StringRef Name = dwarf::toString(Die.find(dwarf::DW_AT_name), "");
162 VariableLoc.insert({Name, {File, Line}});
166 // Returns the pair of file name and line number describing location of data
167 // object (variable, array, etc) definition.
168 template <class ELFT>
169 Optional<std::pair<std::string, unsigned>>
170 ObjFile<ELFT>::getVariableLoc(StringRef Name) {
171 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
173 // There is always only one CU so it's offset is 0.
174 const DWARFDebugLine::LineTable *LT = DwarfLine->getLineTable(0);
178 // Return if we have no debug information about data object.
179 auto It = VariableLoc.find(Name);
180 if (It == VariableLoc.end())
183 // Take file name string from line table.
184 std::string FileName;
185 if (!LT->getFileNameByIndex(
186 It->second.first /* File */, nullptr,
187 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FileName))
190 return std::make_pair(FileName, It->second.second /*Line*/);
193 // Returns source line information for a given offset
194 // using DWARF debug info.
195 template <class ELFT>
196 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *S,
198 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
200 // The offset to CU is 0.
201 const DWARFDebugLine::LineTable *Tbl = DwarfLine->getLineTable(0);
205 // Use fake address calcuated by adding section file offset and offset in
206 // section. See comments for ObjectInfo class.
208 Tbl->getFileLineInfoForAddress(
209 S->getOffsetInFile() + Offset, nullptr,
210 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info);
216 // Returns source line information for a given offset
217 // using DWARF debug info.
218 template <class ELFT>
219 std::string ObjFile<ELFT>::getLineInfo(InputSectionBase *S, uint64_t Offset) {
220 if (Optional<DILineInfo> Info = getDILineInfo(S, Offset))
221 return Info->FileName + ":" + std::to_string(Info->Line);
225 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
226 std::string lld::toString(const InputFile *F) {
230 if (F->ToStringCache.empty()) {
231 if (F->ArchiveName.empty())
232 F->ToStringCache = F->getName();
234 F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str();
236 return F->ToStringCache;
239 template <class ELFT>
240 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
241 if (ELFT::TargetEndianness == support::little)
242 EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
244 EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
246 EMachine = getObj().getHeader()->e_machine;
247 OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
250 template <class ELFT>
251 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalELFSyms() {
252 return makeArrayRef(ELFSyms.begin() + FirstNonLocal, ELFSyms.end());
255 template <class ELFT>
256 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
257 return CHECK(getObj().getSectionIndex(&Sym, ELFSyms, SymtabSHNDX), this);
260 template <class ELFT>
261 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
262 const Elf_Shdr *Symtab) {
263 FirstNonLocal = Symtab->sh_info;
264 ELFSyms = CHECK(getObj().symbols(Symtab), this);
265 if (FirstNonLocal == 0 || FirstNonLocal > ELFSyms.size())
266 fatal(toString(this) + ": invalid sh_info in symbol table");
269 CHECK(getObj().getStringTableForSymtab(*Symtab, Sections), this);
272 template <class ELFT>
273 ObjFile<ELFT>::ObjFile(MemoryBufferRef M, StringRef ArchiveName)
274 : ELFFileBase<ELFT>(Base::ObjKind, M) {
275 this->ArchiveName = ArchiveName;
278 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
279 if (this->Symbols.empty())
281 return makeArrayRef(this->Symbols).slice(1, this->FirstNonLocal - 1);
284 template <class ELFT>
285 void ObjFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
286 // Read section and symbol tables.
287 initializeSections(ComdatGroups);
291 // Sections with SHT_GROUP and comdat bits define comdat section groups.
292 // They are identified and deduplicated by group name. This function
293 // returns a group name.
294 template <class ELFT>
295 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
296 const Elf_Shdr &Sec) {
297 // Group signatures are stored as symbol names in object files.
298 // sh_info contains a symbol index, so we fetch a symbol and read its name.
299 if (this->ELFSyms.empty())
301 Sections, CHECK(object::getSection<ELFT>(Sections, Sec.sh_link), this));
304 CHECK(object::getSymbol<ELFT>(this->ELFSyms, Sec.sh_info), this);
305 StringRef Signature = CHECK(Sym->getName(this->StringTable), this);
307 // As a special case, if a symbol is a section symbol and has no name,
308 // we use a section name as a signature.
310 // Such SHT_GROUP sections are invalid from the perspective of the ELF
311 // standard, but GNU gold 1.14 (the neweset version as of July 2017) or
312 // older produce such sections as outputs for the -r option, so we need
313 // a bug-compatibility.
314 if (Signature.empty() && Sym->getType() == STT_SECTION)
315 return getSectionName(Sec);
319 template <class ELFT>
320 ArrayRef<typename ObjFile<ELFT>::Elf_Word>
321 ObjFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
322 const ELFFile<ELFT> &Obj = this->getObj();
323 ArrayRef<Elf_Word> Entries =
324 CHECK(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), this);
325 if (Entries.empty() || Entries[0] != GRP_COMDAT)
326 fatal(toString(this) + ": unsupported SHT_GROUP format");
327 return Entries.slice(1);
330 template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
331 // We don't merge sections if -O0 (default is -O1). This makes sometimes
332 // the linker significantly faster, although the output will be bigger.
333 if (Config->Optimize == 0)
336 // A mergeable section with size 0 is useless because they don't have
337 // any data to merge. A mergeable string section with size 0 can be
338 // argued as invalid because it doesn't end with a null character.
339 // We'll avoid a mess by handling them as if they were non-mergeable.
340 if (Sec.sh_size == 0)
343 // Check for sh_entsize. The ELF spec is not clear about the zero
344 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
345 // the section does not hold a table of fixed-size entries". We know
346 // that Rust 1.13 produces a string mergeable section with a zero
347 // sh_entsize. Here we just accept it rather than being picky about it.
348 uint64_t EntSize = Sec.sh_entsize;
351 if (Sec.sh_size % EntSize)
352 fatal(toString(this) +
353 ": SHF_MERGE section size must be a multiple of sh_entsize");
355 uint64_t Flags = Sec.sh_flags;
356 if (!(Flags & SHF_MERGE))
358 if (Flags & SHF_WRITE)
359 fatal(toString(this) + ": writable SHF_MERGE section is not supported");
364 template <class ELFT>
365 void ObjFile<ELFT>::initializeSections(
366 DenseSet<CachedHashStringRef> &ComdatGroups) {
367 const ELFFile<ELFT> &Obj = this->getObj();
369 ArrayRef<Elf_Shdr> ObjSections = CHECK(this->getObj().sections(), this);
370 uint64_t Size = ObjSections.size();
371 this->Sections.resize(Size);
372 this->SectionStringTable =
373 CHECK(Obj.getSectionStringTable(ObjSections), this);
375 for (size_t I = 0, E = ObjSections.size(); I < E; I++) {
376 if (this->Sections[I] == &InputSection::Discarded)
378 const Elf_Shdr &Sec = ObjSections[I];
380 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
381 // if -r is given, we'll let the final link discard such sections.
382 // This is compatible with GNU.
383 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
384 this->Sections[I] = &InputSection::Discarded;
388 switch (Sec.sh_type) {
390 // De-duplicate section groups by their signatures.
391 StringRef Signature = getShtGroupSignature(ObjSections, Sec);
392 bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second;
393 this->Sections[I] = &InputSection::Discarded;
395 // If it is a new section group, we want to keep group members.
396 // Group leader sections, which contain indices of group members, are
397 // discarded because they are useless beyond this point. The only
398 // exception is the -r option because in order to produce re-linkable
399 // object files, we want to pass through basically everything.
401 if (Config->Relocatable)
402 this->Sections[I] = createInputSection(Sec);
406 // Otherwise, discard group members.
407 for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
408 if (SecIndex >= Size)
409 fatal(toString(this) +
410 ": invalid section index in group: " + Twine(SecIndex));
411 this->Sections[SecIndex] = &InputSection::Discarded;
416 this->initSymtab(ObjSections, &Sec);
418 case SHT_SYMTAB_SHNDX:
419 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, ObjSections), this);
425 this->Sections[I] = createInputSection(Sec);
428 // .ARM.exidx sections have a reverse dependency on the InputSection they
429 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
430 if (Sec.sh_flags & SHF_LINK_ORDER) {
431 if (Sec.sh_link >= this->Sections.size())
432 fatal(toString(this) +
433 ": invalid sh_link index: " + Twine(Sec.sh_link));
434 this->Sections[Sec.sh_link]->DependentSections.push_back(
435 cast<InputSection>(this->Sections[I]));
440 // The ARM support in lld makes some use of instructions that are not available
441 // on all ARM architectures. Namely:
442 // - Use of BLX instruction for interworking between ARM and Thumb state.
443 // - Use of the extended Thumb branch encoding in relocation.
444 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
445 // The ARM Attributes section contains information about the architecture chosen
446 // at compile time. We follow the convention that if at least one input object
447 // is compiled with an architecture that supports these features then lld is
448 // permitted to use them.
449 static void updateSupportedARMFeatures(const ARMAttributeParser &Attributes) {
450 if (!Attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
452 auto Arch = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
454 case ARMBuildAttrs::Pre_v4:
455 case ARMBuildAttrs::v4:
456 case ARMBuildAttrs::v4T:
457 // Architectures prior to v5 do not support BLX instruction
459 case ARMBuildAttrs::v5T:
460 case ARMBuildAttrs::v5TE:
461 case ARMBuildAttrs::v5TEJ:
462 case ARMBuildAttrs::v6:
463 case ARMBuildAttrs::v6KZ:
464 case ARMBuildAttrs::v6K:
465 Config->ARMHasBlx = true;
466 // Architectures used in pre-Cortex processors do not support
467 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
468 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
471 // All other Architectures have BLX and extended branch encoding
472 Config->ARMHasBlx = true;
473 Config->ARMJ1J2BranchEncoding = true;
474 if (Arch != ARMBuildAttrs::v6_M && Arch != ARMBuildAttrs::v6S_M)
475 // All Architectures used in Cortex processors with the exception
476 // of v6-M and v6S-M have the MOVT and MOVW instructions.
477 Config->ARMHasMovtMovw = true;
482 template <class ELFT>
483 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
484 uint32_t Idx = Sec.sh_info;
485 if (Idx >= this->Sections.size())
486 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
487 InputSectionBase *Target = this->Sections[Idx];
489 // Strictly speaking, a relocation section must be included in the
490 // group of the section it relocates. However, LLVM 3.3 and earlier
491 // would fail to do so, so we gracefully handle that case.
492 if (Target == &InputSection::Discarded)
496 fatal(toString(this) + ": unsupported relocation reference");
500 // Create a regular InputSection class that has the same contents
501 // as a given section.
502 static InputSection *toRegularSection(MergeInputSection *Sec) {
503 return make<InputSection>(Sec->File, Sec->Flags, Sec->Type, Sec->Alignment,
504 Sec->Data, Sec->Name);
507 template <class ELFT>
508 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
509 StringRef Name = getSectionName(Sec);
511 switch (Sec.sh_type) {
512 case SHT_ARM_ATTRIBUTES: {
513 if (Config->EMachine != EM_ARM)
515 ARMAttributeParser Attributes;
516 ArrayRef<uint8_t> Contents = check(this->getObj().getSectionContents(&Sec));
517 Attributes.Parse(Contents, /*isLittle*/ Config->EKind == ELF32LEKind);
518 updateSupportedARMFeatures(Attributes);
519 // FIXME: Retain the first attribute section we see. The eglibc ARM
520 // dynamic loaders require the presence of an attribute section for dlopen
521 // to work. In a full implementation we would merge all attribute sections.
522 if (InX::ARMAttributes == nullptr) {
523 InX::ARMAttributes = make<InputSection>(*this, Sec, Name);
524 return InX::ARMAttributes;
526 return &InputSection::Discarded;
530 // Find the relocation target section and associate this
531 // section with it. Target can be discarded, for example
532 // if it is a duplicated member of SHT_GROUP section, we
533 // do not create or proccess relocatable sections then.
534 InputSectionBase *Target = getRelocTarget(Sec);
538 // This section contains relocation information.
539 // If -r is given, we do not interpret or apply relocation
540 // but just copy relocation sections to output.
541 if (Config->Relocatable)
542 return make<InputSection>(*this, Sec, Name);
544 if (Target->FirstRelocation)
545 fatal(toString(this) +
546 ": multiple relocation sections to one section are not supported");
548 // Mergeable sections with relocations are tricky because relocations
549 // need to be taken into account when comparing section contents for
550 // merging. It's not worth supporting such mergeable sections because
551 // they are rare and it'd complicates the internal design (we usually
552 // have to determine if two sections are mergeable early in the link
553 // process much before applying relocations). We simply handle mergeable
554 // sections with relocations as non-mergeable.
555 if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
556 Target = toRegularSection(MS);
557 this->Sections[Sec.sh_info] = Target;
560 size_t NumRelocations;
561 if (Sec.sh_type == SHT_RELA) {
562 ArrayRef<Elf_Rela> Rels = CHECK(this->getObj().relas(&Sec), this);
563 Target->FirstRelocation = Rels.begin();
564 NumRelocations = Rels.size();
565 Target->AreRelocsRela = true;
567 ArrayRef<Elf_Rel> Rels = CHECK(this->getObj().rels(&Sec), this);
568 Target->FirstRelocation = Rels.begin();
569 NumRelocations = Rels.size();
570 Target->AreRelocsRela = false;
572 assert(isUInt<31>(NumRelocations));
573 Target->NumRelocations = NumRelocations;
575 // Relocation sections processed by the linker are usually removed
576 // from the output, so returning `nullptr` for the normal case.
577 // However, if -emit-relocs is given, we need to leave them in the output.
578 // (Some post link analysis tools need this information.)
579 if (Config->EmitRelocs) {
580 InputSection *RelocSec = make<InputSection>(*this, Sec, Name);
581 // We will not emit relocation section if target was discarded.
582 Target->DependentSections.push_back(RelocSec);
589 // The GNU linker uses .note.GNU-stack section as a marker indicating
590 // that the code in the object file does not expect that the stack is
591 // executable (in terms of NX bit). If all input files have the marker,
592 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
593 // make the stack non-executable. Most object files have this section as
596 // But making the stack non-executable is a norm today for security
597 // reasons. Failure to do so may result in a serious security issue.
598 // Therefore, we make LLD always add PT_GNU_STACK unless it is
599 // explicitly told to do otherwise (by -z execstack). Because the stack
600 // executable-ness is controlled solely by command line options,
601 // .note.GNU-stack sections are simply ignored.
602 if (Name == ".note.GNU-stack")
603 return &InputSection::Discarded;
605 // Split stacks is a feature to support a discontiguous stack. At least
606 // as of 2017, it seems that the feature is not being used widely.
607 // Only GNU gold supports that. We don't. For the details about that,
608 // see https://gcc.gnu.org/wiki/SplitStacks
609 if (Name == ".note.GNU-split-stack") {
610 error(toString(this) +
611 ": object file compiled with -fsplit-stack is not supported");
612 return &InputSection::Discarded;
615 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
616 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
617 // sections. Drop those sections to avoid duplicate symbol errors.
618 // FIXME: This is glibc PR20543, we should remove this hack once that has been
619 // fixed for a while.
620 if (Name.startswith(".gnu.linkonce."))
621 return &InputSection::Discarded;
623 // The linker merges EH (exception handling) frames and creates a
624 // .eh_frame_hdr section for runtime. So we handle them with a special
625 // class. For relocatable outputs, they are just passed through.
626 if (Name == ".eh_frame" && !Config->Relocatable)
627 return make<EhInputSection>(*this, Sec, Name);
629 if (shouldMerge(Sec))
630 return make<MergeInputSection>(*this, Sec, Name);
631 return make<InputSection>(*this, Sec, Name);
634 template <class ELFT>
635 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
636 return CHECK(this->getObj().getSectionName(&Sec, SectionStringTable), this);
639 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
640 this->Symbols.reserve(this->ELFSyms.size());
641 for (const Elf_Sym &Sym : this->ELFSyms)
642 this->Symbols.push_back(createSymbol(&Sym));
645 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) {
646 int Binding = Sym->getBinding();
648 uint32_t SecIdx = this->getSectionIndex(*Sym);
649 if (SecIdx >= this->Sections.size())
650 fatal(toString(this) + ": invalid section index: " + Twine(SecIdx));
652 InputSectionBase *Sec = this->Sections[SecIdx];
653 uint8_t StOther = Sym->st_other;
654 uint8_t Type = Sym->getType();
655 uint64_t Value = Sym->st_value;
656 uint64_t Size = Sym->st_size;
658 if (Binding == STB_LOCAL) {
659 if (Sym->getType() == STT_FILE)
660 SourceFile = CHECK(Sym->getName(this->StringTable), this);
662 if (this->StringTable.size() <= Sym->st_name)
663 fatal(toString(this) + ": invalid symbol name offset");
665 StringRefZ Name = this->StringTable.data() + Sym->st_name;
666 if (Sym->st_shndx == SHN_UNDEF)
667 return make<Undefined>(this, Name, Binding, StOther, Type);
669 return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec);
672 StringRef Name = CHECK(Sym->getName(this->StringTable), this);
674 switch (Sym->st_shndx) {
676 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
677 /*CanOmitFromDynSym=*/false, this);
679 if (Value == 0 || Value >= UINT32_MAX)
680 fatal(toString(this) + ": common symbol '" + Name +
681 "' has invalid alignment: " + Twine(Value));
682 return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, *this);
687 fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
691 if (Sec == &InputSection::Discarded)
692 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
693 /*CanOmitFromDynSym=*/false, this);
694 return Symtab->addRegular(Name, StOther, Type, Value, Size, Binding, Sec,
699 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
700 : InputFile(ArchiveKind, File->getMemoryBufferRef()),
701 File(std::move(File)) {}
703 template <class ELFT> void ArchiveFile::parse() {
704 Symbols.reserve(File->getNumberOfSymbols());
705 for (const Archive::Symbol &Sym : File->symbols())
706 Symbols.push_back(Symtab->addLazyArchive<ELFT>(Sym.getName(), *this, Sym));
709 // Returns a buffer pointing to a member file containing a given symbol.
710 std::pair<MemoryBufferRef, uint64_t>
711 ArchiveFile::getMember(const Archive::Symbol *Sym) {
713 CHECK(Sym->getMember(), toString(this) +
714 ": could not get the member for symbol " +
717 if (!Seen.insert(C.getChildOffset()).second)
718 return {MemoryBufferRef(), 0};
720 MemoryBufferRef Ret =
721 CHECK(C.getMemoryBufferRef(),
723 ": could not get the buffer for the member defining symbol " +
726 if (C.getParent()->isThin() && Tar)
727 Tar->append(relativeToRoot(CHECK(C.getFullName(), this)), Ret.getBuffer());
728 if (C.getParent()->isThin())
730 return {Ret, C.getChildOffset()};
733 template <class ELFT>
734 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
735 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
736 IsNeeded(!Config->AsNeeded) {}
738 // Partially parse the shared object file so that we can call
739 // getSoName on this object.
740 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
741 const Elf_Shdr *DynamicSec = nullptr;
742 const ELFFile<ELFT> Obj = this->getObj();
743 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
745 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
746 for (const Elf_Shdr &Sec : Sections) {
747 switch (Sec.sh_type) {
751 this->initSymtab(Sections, &Sec);
756 case SHT_SYMTAB_SHNDX:
757 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this);
760 this->VersymSec = &Sec;
763 this->VerdefSec = &Sec;
768 if (this->VersymSec && this->ELFSyms.empty())
769 error("SHT_GNU_versym should be associated with symbol table");
771 // Search for a DT_SONAME tag to initialize this->SoName.
774 ArrayRef<Elf_Dyn> Arr =
775 CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this);
776 for (const Elf_Dyn &Dyn : Arr) {
777 if (Dyn.d_tag == DT_SONAME) {
778 uint64_t Val = Dyn.getVal();
779 if (Val >= this->StringTable.size())
780 fatal(toString(this) + ": invalid DT_SONAME entry");
781 SoName = this->StringTable.data() + Val;
787 // Parse the version definitions in the object file if present. Returns a vector
788 // whose nth element contains a pointer to the Elf_Verdef for version identifier
789 // n. Version identifiers that are not definitions map to nullptr. The array
790 // always has at least length 1.
791 template <class ELFT>
792 std::vector<const typename ELFT::Verdef *>
793 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
794 std::vector<const Elf_Verdef *> Verdefs(1);
795 // We only need to process symbol versions for this DSO if it has both a
796 // versym and a verdef section, which indicates that the DSO contains symbol
797 // version definitions.
798 if (!VersymSec || !VerdefSec)
801 // The location of the first global versym entry.
802 const char *Base = this->MB.getBuffer().data();
803 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
806 // We cannot determine the largest verdef identifier without inspecting
807 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
808 // sequentially starting from 1, so we predict that the largest identifier
809 // will be VerdefCount.
810 unsigned VerdefCount = VerdefSec->sh_info;
811 Verdefs.resize(VerdefCount + 1);
813 // Build the Verdefs array by following the chain of Elf_Verdef objects
814 // from the start of the .gnu.version_d section.
815 const char *Verdef = Base + VerdefSec->sh_offset;
816 for (unsigned I = 0; I != VerdefCount; ++I) {
817 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
818 Verdef += CurVerdef->vd_next;
819 unsigned VerdefIndex = CurVerdef->vd_ndx;
820 if (Verdefs.size() <= VerdefIndex)
821 Verdefs.resize(VerdefIndex + 1);
822 Verdefs[VerdefIndex] = CurVerdef;
828 // Fully parse the shared object file. This must be called after parseSoName().
829 template <class ELFT> void SharedFile<ELFT>::parseRest() {
830 // Create mapping from version identifiers to Elf_Verdef entries.
831 const Elf_Versym *Versym = nullptr;
832 Verdefs = parseVerdefs(Versym);
834 ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this);
836 // Add symbols to the symbol table.
837 Elf_Sym_Range Syms = this->getGlobalELFSyms();
838 for (const Elf_Sym &Sym : Syms) {
839 unsigned VersymIndex = VER_NDX_GLOBAL;
841 VersymIndex = Versym->vs_index;
844 bool Hidden = VersymIndex & VERSYM_HIDDEN;
845 VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
847 StringRef Name = CHECK(Sym.getName(this->StringTable), this);
848 if (Sym.isUndefined()) {
849 Undefs.push_back(Name);
853 if (Sym.getBinding() == STB_LOCAL) {
854 warn("found local symbol '" + Name +
855 "' in global part of symbol table in file " + toString(this));
859 if (Config->EMachine == EM_MIPS) {
860 // FIXME: MIPS BFD linker puts _gp_disp symbol into DSO files
861 // and incorrectly assigns VER_NDX_LOCAL to this section global
862 // symbol. Here is a workaround for this bug.
863 if (Versym && VersymIndex == VER_NDX_LOCAL && Name == "_gp_disp")
867 const Elf_Verdef *Ver = nullptr;
868 if (VersymIndex != VER_NDX_GLOBAL) {
869 if (VersymIndex >= Verdefs.size() || VersymIndex == VER_NDX_LOCAL) {
870 error("corrupt input file: version definition index " +
871 Twine(VersymIndex) + " for symbol " + Name +
872 " is out of bounds\n>>> defined in " + toString(this));
875 Ver = Verdefs[VersymIndex];
880 // We do not usually care about alignments of data in shared object
881 // files because the loader takes care of it. However, if we promote a
882 // DSO symbol to point to .bss due to copy relocation, we need to keep
883 // the original alignment requirements. We infer it here.
884 uint64_t Alignment = 1;
886 Alignment = 1ULL << countTrailingZeros((uint64_t)Sym.st_value);
887 if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) {
888 uint64_t SecAlign = Sections[Sym.st_shndx].sh_addralign;
889 Alignment = std::min(Alignment, SecAlign);
891 if (Alignment > UINT32_MAX)
892 error(toString(this) + ": alignment too large: " + Name);
895 Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
897 // Also add the symbol with the versioned name to handle undefined symbols
898 // with explicit versions.
900 StringRef VerName = this->StringTable.data() + Ver->getAux()->vda_name;
901 Name = Saver.save(Name + "@" + VerName);
902 Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
907 static ELFKind getBitcodeELFKind(const Triple &T) {
908 if (T.isLittleEndian())
909 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
910 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
913 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
914 switch (T.getArch()) {
915 case Triple::aarch64:
925 case Triple::mips64el:
932 return T.isOSIAMCU() ? EM_IAMCU : EM_386;
936 fatal(Path + ": could not infer e_machine from bitcode target triple " +
941 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
942 uint64_t OffsetInArchive)
943 : InputFile(BitcodeKind, MB) {
944 this->ArchiveName = ArchiveName;
946 // Here we pass a new MemoryBufferRef which is identified by ArchiveName
947 // (the fully resolved path of the archive) + member name + offset of the
948 // member in the archive.
949 // ThinLTO uses the MemoryBufferRef identifier to access its internal
950 // data structures and if two archives define two members with the same name,
951 // this causes a collision which result in only one of the objects being
952 // taken into consideration at LTO time (which very likely causes undefined
953 // symbols later in the link stage).
954 MemoryBufferRef MBRef(MB.getBuffer(),
955 Saver.save(ArchiveName + MB.getBufferIdentifier() +
956 utostr(OffsetInArchive)));
957 Obj = CHECK(lto::InputFile::create(MBRef), this);
959 Triple T(Obj->getTargetTriple());
960 EKind = getBitcodeELFKind(T);
961 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
964 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
965 switch (GvVisibility) {
966 case GlobalValue::DefaultVisibility:
968 case GlobalValue::HiddenVisibility:
970 case GlobalValue::ProtectedVisibility:
971 return STV_PROTECTED;
973 llvm_unreachable("unknown visibility");
976 template <class ELFT>
977 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
978 const lto::InputFile::Symbol &ObjSym,
980 StringRef NameRef = Saver.save(ObjSym.getName());
981 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
983 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
984 uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
985 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
987 int C = ObjSym.getComdatIndex();
988 if (C != -1 && !KeptComdats[C])
989 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
990 CanOmitFromDynSym, &F);
992 if (ObjSym.isUndefined())
993 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
994 CanOmitFromDynSym, &F);
996 if (ObjSym.isCommon())
997 return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
998 ObjSym.getCommonAlignment(), Binding, Visibility,
1001 return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
1002 CanOmitFromDynSym, F);
1005 template <class ELFT>
1006 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
1007 std::vector<bool> KeptComdats;
1008 for (StringRef S : Obj->getComdatTable())
1009 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
1011 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
1012 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this));
1015 static ELFKind getELFKind(MemoryBufferRef MB) {
1017 unsigned char Endian;
1018 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
1020 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
1021 fatal(MB.getBufferIdentifier() + ": invalid data encoding");
1022 if (Size != ELFCLASS32 && Size != ELFCLASS64)
1023 fatal(MB.getBufferIdentifier() + ": invalid file class");
1025 size_t BufSize = MB.getBuffer().size();
1026 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
1027 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
1028 fatal(MB.getBufferIdentifier() + ": file is too short");
1030 if (Size == ELFCLASS32)
1031 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
1032 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
1035 void BinaryFile::parse() {
1036 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
1037 auto *Section = make<InputSection>(nullptr, SHF_ALLOC | SHF_WRITE,
1038 SHT_PROGBITS, 8, Data, ".data");
1039 Sections.push_back(Section);
1041 // For each input file foo that is embedded to a result as a binary
1042 // blob, we define _binary_foo_{start,end,size} symbols, so that
1043 // user programs can access blobs by name. Non-alphanumeric
1044 // characters in a filename are replaced with underscore.
1045 std::string S = "_binary_" + MB.getBufferIdentifier().str();
1046 for (size_t I = 0; I < S.size(); ++I)
1050 Symtab->addRegular(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 0, 0,
1051 STB_GLOBAL, Section, nullptr);
1052 Symtab->addRegular(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
1053 Data.size(), 0, STB_GLOBAL, Section, nullptr);
1054 Symtab->addRegular(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
1055 Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
1058 static bool isBitcode(MemoryBufferRef MB) {
1059 using namespace sys::fs;
1060 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
1063 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
1064 uint64_t OffsetInArchive) {
1066 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
1068 switch (getELFKind(MB)) {
1070 return make<ObjFile<ELF32LE>>(MB, ArchiveName);
1072 return make<ObjFile<ELF32BE>>(MB, ArchiveName);
1074 return make<ObjFile<ELF64LE>>(MB, ArchiveName);
1076 return make<ObjFile<ELF64BE>>(MB, ArchiveName);
1078 llvm_unreachable("getELFKind");
1082 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
1083 switch (getELFKind(MB)) {
1085 return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
1087 return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
1089 return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
1091 return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
1093 llvm_unreachable("getELFKind");
1097 MemoryBufferRef LazyObjFile::getBuffer() {
1099 return MemoryBufferRef();
1104 InputFile *LazyObjFile::fetch() {
1105 MemoryBufferRef MBRef = getBuffer();
1106 if (MBRef.getBuffer().empty())
1108 return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1111 template <class ELFT> void LazyObjFile::parse() {
1112 for (StringRef Sym : getSymbolNames())
1113 Symtab->addLazyObject<ELFT>(Sym, *this);
1116 template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
1117 typedef typename ELFT::Shdr Elf_Shdr;
1118 typedef typename ELFT::Sym Elf_Sym;
1119 typedef typename ELFT::SymRange Elf_Sym_Range;
1121 ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(this->MB.getBuffer()));
1122 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
1123 for (const Elf_Shdr &Sec : Sections) {
1124 if (Sec.sh_type != SHT_SYMTAB)
1127 Elf_Sym_Range Syms = CHECK(Obj.symbols(&Sec), this);
1128 uint32_t FirstNonLocal = Sec.sh_info;
1129 StringRef StringTable =
1130 CHECK(Obj.getStringTableForSymtab(Sec, Sections), this);
1131 std::vector<StringRef> V;
1133 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1134 if (Sym.st_shndx != SHN_UNDEF)
1135 V.push_back(CHECK(Sym.getName(StringTable), this));
1141 std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1142 std::unique_ptr<lto::InputFile> Obj =
1143 CHECK(lto::InputFile::create(this->MB), this);
1144 std::vector<StringRef> V;
1145 for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1146 if (!Sym.isUndefined())
1147 V.push_back(Saver.save(Sym.getName()));
1151 // Returns a vector of globally-visible defined symbol names.
1152 std::vector<StringRef> LazyObjFile::getSymbolNames() {
1153 if (isBitcode(this->MB))
1154 return getBitcodeSymbols();
1156 switch (getELFKind(this->MB)) {
1158 return getElfSymbols<ELF32LE>();
1160 return getElfSymbols<ELF32BE>();
1162 return getElfSymbols<ELF64LE>();
1164 return getElfSymbols<ELF64BE>();
1166 llvm_unreachable("getELFKind");
1170 template void ArchiveFile::parse<ELF32LE>();
1171 template void ArchiveFile::parse<ELF32BE>();
1172 template void ArchiveFile::parse<ELF64LE>();
1173 template void ArchiveFile::parse<ELF64BE>();
1175 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1176 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1177 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1178 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1180 template void LazyObjFile::parse<ELF32LE>();
1181 template void LazyObjFile::parse<ELF32BE>();
1182 template void LazyObjFile::parse<ELF64LE>();
1183 template void LazyObjFile::parse<ELF64BE>();
1185 template class elf::ELFFileBase<ELF32LE>;
1186 template class elf::ELFFileBase<ELF32BE>;
1187 template class elf::ELFFileBase<ELF64LE>;
1188 template class elf::ELFFileBase<ELF64BE>;
1190 template class elf::ObjFile<ELF32LE>;
1191 template class elf::ObjFile<ELF32BE>;
1192 template class elf::ObjFile<ELF64LE>;
1193 template class elf::ObjFile<ELF64BE>;
1195 template class elf::SharedFile<ELF32LE>;
1196 template class elf::SharedFile<ELF32BE>;
1197 template class elf::SharedFile<ELF64LE>;
1198 template class elf::SharedFile<ELF64BE>;