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> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
285 return makeArrayRef(this->Symbols).slice(this->FirstNonLocal);
288 template <class ELFT>
289 void ObjFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
290 // Read section and symbol tables.
291 initializeSections(ComdatGroups);
295 // Sections with SHT_GROUP and comdat bits define comdat section groups.
296 // They are identified and deduplicated by group name. This function
297 // returns a group name.
298 template <class ELFT>
299 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
300 const Elf_Shdr &Sec) {
301 // Group signatures are stored as symbol names in object files.
302 // sh_info contains a symbol index, so we fetch a symbol and read its name.
303 if (this->ELFSyms.empty())
305 Sections, CHECK(object::getSection<ELFT>(Sections, Sec.sh_link), this));
308 CHECK(object::getSymbol<ELFT>(this->ELFSyms, Sec.sh_info), this);
309 StringRef Signature = CHECK(Sym->getName(this->StringTable), this);
311 // As a special case, if a symbol is a section symbol and has no name,
312 // we use a section name as a signature.
314 // Such SHT_GROUP sections are invalid from the perspective of the ELF
315 // standard, but GNU gold 1.14 (the neweset version as of July 2017) or
316 // older produce such sections as outputs for the -r option, so we need
317 // a bug-compatibility.
318 if (Signature.empty() && Sym->getType() == STT_SECTION)
319 return getSectionName(Sec);
323 template <class ELFT>
324 ArrayRef<typename ObjFile<ELFT>::Elf_Word>
325 ObjFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
326 const ELFFile<ELFT> &Obj = this->getObj();
327 ArrayRef<Elf_Word> Entries =
328 CHECK(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), this);
329 if (Entries.empty() || Entries[0] != GRP_COMDAT)
330 fatal(toString(this) + ": unsupported SHT_GROUP format");
331 return Entries.slice(1);
334 template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
335 // We don't merge sections if -O0 (default is -O1). This makes sometimes
336 // the linker significantly faster, although the output will be bigger.
337 if (Config->Optimize == 0)
340 // A mergeable section with size 0 is useless because they don't have
341 // any data to merge. A mergeable string section with size 0 can be
342 // argued as invalid because it doesn't end with a null character.
343 // We'll avoid a mess by handling them as if they were non-mergeable.
344 if (Sec.sh_size == 0)
347 // Check for sh_entsize. The ELF spec is not clear about the zero
348 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
349 // the section does not hold a table of fixed-size entries". We know
350 // that Rust 1.13 produces a string mergeable section with a zero
351 // sh_entsize. Here we just accept it rather than being picky about it.
352 uint64_t EntSize = Sec.sh_entsize;
355 if (Sec.sh_size % EntSize)
356 fatal(toString(this) +
357 ": SHF_MERGE section size must be a multiple of sh_entsize");
359 uint64_t Flags = Sec.sh_flags;
360 if (!(Flags & SHF_MERGE))
362 if (Flags & SHF_WRITE)
363 fatal(toString(this) + ": writable SHF_MERGE section is not supported");
368 template <class ELFT>
369 void ObjFile<ELFT>::initializeSections(
370 DenseSet<CachedHashStringRef> &ComdatGroups) {
371 const ELFFile<ELFT> &Obj = this->getObj();
373 ArrayRef<Elf_Shdr> ObjSections = CHECK(this->getObj().sections(), this);
374 uint64_t Size = ObjSections.size();
375 this->Sections.resize(Size);
376 this->SectionStringTable =
377 CHECK(Obj.getSectionStringTable(ObjSections), this);
379 for (size_t I = 0, E = ObjSections.size(); I < E; I++) {
380 if (this->Sections[I] == &InputSection::Discarded)
382 const Elf_Shdr &Sec = ObjSections[I];
384 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
385 // if -r is given, we'll let the final link discard such sections.
386 // This is compatible with GNU.
387 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
388 this->Sections[I] = &InputSection::Discarded;
392 switch (Sec.sh_type) {
394 // De-duplicate section groups by their signatures.
395 StringRef Signature = getShtGroupSignature(ObjSections, Sec);
396 bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second;
397 this->Sections[I] = &InputSection::Discarded;
399 // If it is a new section group, we want to keep group members.
400 // Group leader sections, which contain indices of group members, are
401 // discarded because they are useless beyond this point. The only
402 // exception is the -r option because in order to produce re-linkable
403 // object files, we want to pass through basically everything.
405 if (Config->Relocatable)
406 this->Sections[I] = createInputSection(Sec);
410 // Otherwise, discard group members.
411 for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
412 if (SecIndex >= Size)
413 fatal(toString(this) +
414 ": invalid section index in group: " + Twine(SecIndex));
415 this->Sections[SecIndex] = &InputSection::Discarded;
420 this->initSymtab(ObjSections, &Sec);
422 case SHT_SYMTAB_SHNDX:
423 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, ObjSections), this);
429 this->Sections[I] = createInputSection(Sec);
432 // .ARM.exidx sections have a reverse dependency on the InputSection they
433 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
434 if (Sec.sh_flags & SHF_LINK_ORDER) {
435 if (Sec.sh_link >= this->Sections.size())
436 fatal(toString(this) +
437 ": invalid sh_link index: " + Twine(Sec.sh_link));
438 this->Sections[Sec.sh_link]->DependentSections.push_back(
439 cast<InputSection>(this->Sections[I]));
444 // The ARM support in lld makes some use of instructions that are not available
445 // on all ARM architectures. Namely:
446 // - Use of BLX instruction for interworking between ARM and Thumb state.
447 // - Use of the extended Thumb branch encoding in relocation.
448 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
449 // The ARM Attributes section contains information about the architecture chosen
450 // at compile time. We follow the convention that if at least one input object
451 // is compiled with an architecture that supports these features then lld is
452 // permitted to use them.
453 static void updateSupportedARMFeatures(const ARMAttributeParser &Attributes) {
454 if (!Attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
456 auto Arch = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
458 case ARMBuildAttrs::Pre_v4:
459 case ARMBuildAttrs::v4:
460 case ARMBuildAttrs::v4T:
461 // Architectures prior to v5 do not support BLX instruction
463 case ARMBuildAttrs::v5T:
464 case ARMBuildAttrs::v5TE:
465 case ARMBuildAttrs::v5TEJ:
466 case ARMBuildAttrs::v6:
467 case ARMBuildAttrs::v6KZ:
468 case ARMBuildAttrs::v6K:
469 Config->ARMHasBlx = true;
470 // Architectures used in pre-Cortex processors do not support
471 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
472 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
475 // All other Architectures have BLX and extended branch encoding
476 Config->ARMHasBlx = true;
477 Config->ARMJ1J2BranchEncoding = true;
478 if (Arch != ARMBuildAttrs::v6_M && Arch != ARMBuildAttrs::v6S_M)
479 // All Architectures used in Cortex processors with the exception
480 // of v6-M and v6S-M have the MOVT and MOVW instructions.
481 Config->ARMHasMovtMovw = true;
486 template <class ELFT>
487 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
488 uint32_t Idx = Sec.sh_info;
489 if (Idx >= this->Sections.size())
490 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
491 InputSectionBase *Target = this->Sections[Idx];
493 // Strictly speaking, a relocation section must be included in the
494 // group of the section it relocates. However, LLVM 3.3 and earlier
495 // would fail to do so, so we gracefully handle that case.
496 if (Target == &InputSection::Discarded)
500 fatal(toString(this) + ": unsupported relocation reference");
504 // Create a regular InputSection class that has the same contents
505 // as a given section.
506 static InputSection *toRegularSection(MergeInputSection *Sec) {
507 return make<InputSection>(Sec->File, Sec->Flags, Sec->Type, Sec->Alignment,
508 Sec->Data, Sec->Name);
511 template <class ELFT>
512 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
513 StringRef Name = getSectionName(Sec);
515 switch (Sec.sh_type) {
516 case SHT_ARM_ATTRIBUTES: {
517 if (Config->EMachine != EM_ARM)
519 ARMAttributeParser Attributes;
520 ArrayRef<uint8_t> Contents = check(this->getObj().getSectionContents(&Sec));
521 Attributes.Parse(Contents, /*isLittle*/ Config->EKind == ELF32LEKind);
522 updateSupportedARMFeatures(Attributes);
523 // FIXME: Retain the first attribute section we see. The eglibc ARM
524 // dynamic loaders require the presence of an attribute section for dlopen
525 // to work. In a full implementation we would merge all attribute sections.
526 if (InX::ARMAttributes == nullptr) {
527 InX::ARMAttributes = make<InputSection>(*this, Sec, Name);
528 return InX::ARMAttributes;
530 return &InputSection::Discarded;
534 // Find the relocation target section and associate this
535 // section with it. Target can be discarded, for example
536 // if it is a duplicated member of SHT_GROUP section, we
537 // do not create or proccess relocatable sections then.
538 InputSectionBase *Target = getRelocTarget(Sec);
542 // This section contains relocation information.
543 // If -r is given, we do not interpret or apply relocation
544 // but just copy relocation sections to output.
545 if (Config->Relocatable)
546 return make<InputSection>(*this, Sec, Name);
548 if (Target->FirstRelocation)
549 fatal(toString(this) +
550 ": multiple relocation sections to one section are not supported");
552 // Mergeable sections with relocations are tricky because relocations
553 // need to be taken into account when comparing section contents for
554 // merging. It's not worth supporting such mergeable sections because
555 // they are rare and it'd complicates the internal design (we usually
556 // have to determine if two sections are mergeable early in the link
557 // process much before applying relocations). We simply handle mergeable
558 // sections with relocations as non-mergeable.
559 if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
560 Target = toRegularSection(MS);
561 this->Sections[Sec.sh_info] = Target;
564 size_t NumRelocations;
565 if (Sec.sh_type == SHT_RELA) {
566 ArrayRef<Elf_Rela> Rels = CHECK(this->getObj().relas(&Sec), this);
567 Target->FirstRelocation = Rels.begin();
568 NumRelocations = Rels.size();
569 Target->AreRelocsRela = true;
571 ArrayRef<Elf_Rel> Rels = CHECK(this->getObj().rels(&Sec), this);
572 Target->FirstRelocation = Rels.begin();
573 NumRelocations = Rels.size();
574 Target->AreRelocsRela = false;
576 assert(isUInt<31>(NumRelocations));
577 Target->NumRelocations = NumRelocations;
579 // Relocation sections processed by the linker are usually removed
580 // from the output, so returning `nullptr` for the normal case.
581 // However, if -emit-relocs is given, we need to leave them in the output.
582 // (Some post link analysis tools need this information.)
583 if (Config->EmitRelocs) {
584 InputSection *RelocSec = make<InputSection>(*this, Sec, Name);
585 // We will not emit relocation section if target was discarded.
586 Target->DependentSections.push_back(RelocSec);
593 // The GNU linker uses .note.GNU-stack section as a marker indicating
594 // that the code in the object file does not expect that the stack is
595 // executable (in terms of NX bit). If all input files have the marker,
596 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
597 // make the stack non-executable. Most object files have this section as
600 // But making the stack non-executable is a norm today for security
601 // reasons. Failure to do so may result in a serious security issue.
602 // Therefore, we make LLD always add PT_GNU_STACK unless it is
603 // explicitly told to do otherwise (by -z execstack). Because the stack
604 // executable-ness is controlled solely by command line options,
605 // .note.GNU-stack sections are simply ignored.
606 if (Name == ".note.GNU-stack")
607 return &InputSection::Discarded;
609 // Split stacks is a feature to support a discontiguous stack. At least
610 // as of 2017, it seems that the feature is not being used widely.
611 // Only GNU gold supports that. We don't. For the details about that,
612 // see https://gcc.gnu.org/wiki/SplitStacks
613 if (Name == ".note.GNU-split-stack") {
614 error(toString(this) +
615 ": object file compiled with -fsplit-stack is not supported");
616 return &InputSection::Discarded;
619 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
620 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
621 // sections. Drop those sections to avoid duplicate symbol errors.
622 // FIXME: This is glibc PR20543, we should remove this hack once that has been
623 // fixed for a while.
624 if (Name.startswith(".gnu.linkonce."))
625 return &InputSection::Discarded;
627 // The linker merges EH (exception handling) frames and creates a
628 // .eh_frame_hdr section for runtime. So we handle them with a special
629 // class. For relocatable outputs, they are just passed through.
630 if (Name == ".eh_frame" && !Config->Relocatable)
631 return make<EhInputSection>(*this, Sec, Name);
633 if (shouldMerge(Sec))
634 return make<MergeInputSection>(*this, Sec, Name);
635 return make<InputSection>(*this, Sec, Name);
638 template <class ELFT>
639 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
640 return CHECK(this->getObj().getSectionName(&Sec, SectionStringTable), this);
643 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
644 this->Symbols.reserve(this->ELFSyms.size());
645 for (const Elf_Sym &Sym : this->ELFSyms)
646 this->Symbols.push_back(createSymbol(&Sym));
649 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) {
650 int Binding = Sym->getBinding();
652 uint32_t SecIdx = this->getSectionIndex(*Sym);
653 if (SecIdx >= this->Sections.size())
654 fatal(toString(this) + ": invalid section index: " + Twine(SecIdx));
656 InputSectionBase *Sec = this->Sections[SecIdx];
657 uint8_t StOther = Sym->st_other;
658 uint8_t Type = Sym->getType();
659 uint64_t Value = Sym->st_value;
660 uint64_t Size = Sym->st_size;
662 if (Binding == STB_LOCAL) {
663 if (Sym->getType() == STT_FILE)
664 SourceFile = CHECK(Sym->getName(this->StringTable), this);
666 if (this->StringTable.size() <= Sym->st_name)
667 fatal(toString(this) + ": invalid symbol name offset");
669 StringRefZ Name = this->StringTable.data() + Sym->st_name;
670 if (Sym->st_shndx == SHN_UNDEF)
671 return make<Undefined>(this, Name, Binding, StOther, Type);
673 return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec);
676 StringRef Name = CHECK(Sym->getName(this->StringTable), this);
678 switch (Sym->st_shndx) {
680 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
681 /*CanOmitFromDynSym=*/false, this);
683 if (Value == 0 || Value >= UINT32_MAX)
684 fatal(toString(this) + ": common symbol '" + Name +
685 "' has invalid alignment: " + Twine(Value));
686 return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, *this);
691 fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
695 if (Sec == &InputSection::Discarded)
696 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
697 /*CanOmitFromDynSym=*/false, this);
698 return Symtab->addRegular(Name, StOther, Type, Value, Size, Binding, Sec,
703 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
704 : InputFile(ArchiveKind, File->getMemoryBufferRef()),
705 File(std::move(File)) {}
707 template <class ELFT> void ArchiveFile::parse() {
708 Symbols.reserve(File->getNumberOfSymbols());
709 for (const Archive::Symbol &Sym : File->symbols())
710 Symbols.push_back(Symtab->addLazyArchive<ELFT>(Sym.getName(), *this, Sym));
713 // Returns a buffer pointing to a member file containing a given symbol.
714 std::pair<MemoryBufferRef, uint64_t>
715 ArchiveFile::getMember(const Archive::Symbol *Sym) {
717 CHECK(Sym->getMember(), toString(this) +
718 ": could not get the member for symbol " +
721 if (!Seen.insert(C.getChildOffset()).second)
722 return {MemoryBufferRef(), 0};
724 MemoryBufferRef Ret =
725 CHECK(C.getMemoryBufferRef(),
727 ": could not get the buffer for the member defining symbol " +
730 if (C.getParent()->isThin() && Tar)
731 Tar->append(relativeToRoot(CHECK(C.getFullName(), this)), Ret.getBuffer());
732 if (C.getParent()->isThin())
734 return {Ret, C.getChildOffset()};
737 template <class ELFT>
738 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
739 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
740 IsNeeded(!Config->AsNeeded) {}
742 // Partially parse the shared object file so that we can call
743 // getSoName on this object.
744 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
745 const Elf_Shdr *DynamicSec = nullptr;
746 const ELFFile<ELFT> Obj = this->getObj();
747 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
749 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
750 for (const Elf_Shdr &Sec : Sections) {
751 switch (Sec.sh_type) {
755 this->initSymtab(Sections, &Sec);
760 case SHT_SYMTAB_SHNDX:
761 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this);
764 this->VersymSec = &Sec;
767 this->VerdefSec = &Sec;
772 if (this->VersymSec && this->ELFSyms.empty())
773 error("SHT_GNU_versym should be associated with symbol table");
775 // Search for a DT_SONAME tag to initialize this->SoName.
778 ArrayRef<Elf_Dyn> Arr =
779 CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this);
780 for (const Elf_Dyn &Dyn : Arr) {
781 if (Dyn.d_tag == DT_SONAME) {
782 uint64_t Val = Dyn.getVal();
783 if (Val >= this->StringTable.size())
784 fatal(toString(this) + ": invalid DT_SONAME entry");
785 SoName = this->StringTable.data() + Val;
791 // Parse the version definitions in the object file if present. Returns a vector
792 // whose nth element contains a pointer to the Elf_Verdef for version identifier
793 // n. Version identifiers that are not definitions map to nullptr. The array
794 // always has at least length 1.
795 template <class ELFT>
796 std::vector<const typename ELFT::Verdef *>
797 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
798 std::vector<const Elf_Verdef *> Verdefs(1);
799 // We only need to process symbol versions for this DSO if it has both a
800 // versym and a verdef section, which indicates that the DSO contains symbol
801 // version definitions.
802 if (!VersymSec || !VerdefSec)
805 // The location of the first global versym entry.
806 const char *Base = this->MB.getBuffer().data();
807 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
810 // We cannot determine the largest verdef identifier without inspecting
811 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
812 // sequentially starting from 1, so we predict that the largest identifier
813 // will be VerdefCount.
814 unsigned VerdefCount = VerdefSec->sh_info;
815 Verdefs.resize(VerdefCount + 1);
817 // Build the Verdefs array by following the chain of Elf_Verdef objects
818 // from the start of the .gnu.version_d section.
819 const char *Verdef = Base + VerdefSec->sh_offset;
820 for (unsigned I = 0; I != VerdefCount; ++I) {
821 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
822 Verdef += CurVerdef->vd_next;
823 unsigned VerdefIndex = CurVerdef->vd_ndx;
824 if (Verdefs.size() <= VerdefIndex)
825 Verdefs.resize(VerdefIndex + 1);
826 Verdefs[VerdefIndex] = CurVerdef;
832 // Fully parse the shared object file. This must be called after parseSoName().
833 template <class ELFT> void SharedFile<ELFT>::parseRest() {
834 // Create mapping from version identifiers to Elf_Verdef entries.
835 const Elf_Versym *Versym = nullptr;
836 Verdefs = parseVerdefs(Versym);
838 ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this);
840 // Add symbols to the symbol table.
841 Elf_Sym_Range Syms = this->getGlobalELFSyms();
842 for (const Elf_Sym &Sym : Syms) {
843 unsigned VersymIndex = VER_NDX_GLOBAL;
845 VersymIndex = Versym->vs_index;
848 bool Hidden = VersymIndex & VERSYM_HIDDEN;
849 VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
851 StringRef Name = CHECK(Sym.getName(this->StringTable), this);
852 if (Sym.isUndefined()) {
853 Undefs.push_back(Name);
857 if (Sym.getBinding() == STB_LOCAL) {
858 warn("found local symbol '" + Name +
859 "' in global part of symbol table in file " + toString(this));
863 if (Config->EMachine == EM_MIPS) {
864 // FIXME: MIPS BFD linker puts _gp_disp symbol into DSO files
865 // and incorrectly assigns VER_NDX_LOCAL to this section global
866 // symbol. Here is a workaround for this bug.
867 if (Versym && VersymIndex == VER_NDX_LOCAL && Name == "_gp_disp")
871 const Elf_Verdef *Ver = nullptr;
872 if (VersymIndex != VER_NDX_GLOBAL) {
873 if (VersymIndex >= Verdefs.size() || VersymIndex == VER_NDX_LOCAL) {
874 error("corrupt input file: version definition index " +
875 Twine(VersymIndex) + " for symbol " + Name +
876 " is out of bounds\n>>> defined in " + toString(this));
879 Ver = Verdefs[VersymIndex];
884 // We do not usually care about alignments of data in shared object
885 // files because the loader takes care of it. However, if we promote a
886 // DSO symbol to point to .bss due to copy relocation, we need to keep
887 // the original alignment requirements. We infer it here.
888 uint64_t Alignment = 1;
890 Alignment = 1ULL << countTrailingZeros((uint64_t)Sym.st_value);
891 if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) {
892 uint64_t SecAlign = Sections[Sym.st_shndx].sh_addralign;
893 Alignment = std::min(Alignment, SecAlign);
895 if (Alignment > UINT32_MAX)
896 error(toString(this) + ": alignment too large: " + Name);
899 Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
901 // Also add the symbol with the versioned name to handle undefined symbols
902 // with explicit versions.
904 StringRef VerName = this->StringTable.data() + Ver->getAux()->vda_name;
905 Name = Saver.save(Name + "@" + VerName);
906 Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
911 static ELFKind getBitcodeELFKind(const Triple &T) {
912 if (T.isLittleEndian())
913 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
914 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
917 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
918 switch (T.getArch()) {
919 case Triple::aarch64:
929 case Triple::mips64el:
936 return T.isOSIAMCU() ? EM_IAMCU : EM_386;
940 fatal(Path + ": could not infer e_machine from bitcode target triple " +
945 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
946 uint64_t OffsetInArchive)
947 : InputFile(BitcodeKind, MB) {
948 this->ArchiveName = ArchiveName;
950 // Here we pass a new MemoryBufferRef which is identified by ArchiveName
951 // (the fully resolved path of the archive) + member name + offset of the
952 // member in the archive.
953 // ThinLTO uses the MemoryBufferRef identifier to access its internal
954 // data structures and if two archives define two members with the same name,
955 // this causes a collision which result in only one of the objects being
956 // taken into consideration at LTO time (which very likely causes undefined
957 // symbols later in the link stage).
958 MemoryBufferRef MBRef(MB.getBuffer(),
959 Saver.save(ArchiveName + MB.getBufferIdentifier() +
960 utostr(OffsetInArchive)));
961 Obj = CHECK(lto::InputFile::create(MBRef), this);
963 Triple T(Obj->getTargetTriple());
964 EKind = getBitcodeELFKind(T);
965 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
968 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
969 switch (GvVisibility) {
970 case GlobalValue::DefaultVisibility:
972 case GlobalValue::HiddenVisibility:
974 case GlobalValue::ProtectedVisibility:
975 return STV_PROTECTED;
977 llvm_unreachable("unknown visibility");
980 template <class ELFT>
981 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
982 const lto::InputFile::Symbol &ObjSym,
984 StringRef NameRef = Saver.save(ObjSym.getName());
985 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
987 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
988 uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
989 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
991 int C = ObjSym.getComdatIndex();
992 if (C != -1 && !KeptComdats[C])
993 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
994 CanOmitFromDynSym, &F);
996 if (ObjSym.isUndefined())
997 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
998 CanOmitFromDynSym, &F);
1000 if (ObjSym.isCommon())
1001 return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
1002 ObjSym.getCommonAlignment(), Binding, Visibility,
1005 return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
1006 CanOmitFromDynSym, F);
1009 template <class ELFT>
1010 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
1011 std::vector<bool> KeptComdats;
1012 for (StringRef S : Obj->getComdatTable())
1013 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
1015 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
1016 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this));
1019 static ELFKind getELFKind(MemoryBufferRef MB) {
1021 unsigned char Endian;
1022 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
1024 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
1025 fatal(MB.getBufferIdentifier() + ": invalid data encoding");
1026 if (Size != ELFCLASS32 && Size != ELFCLASS64)
1027 fatal(MB.getBufferIdentifier() + ": invalid file class");
1029 size_t BufSize = MB.getBuffer().size();
1030 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
1031 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
1032 fatal(MB.getBufferIdentifier() + ": file is too short");
1034 if (Size == ELFCLASS32)
1035 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
1036 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
1039 void BinaryFile::parse() {
1040 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
1041 auto *Section = make<InputSection>(nullptr, SHF_ALLOC | SHF_WRITE,
1042 SHT_PROGBITS, 8, Data, ".data");
1043 Sections.push_back(Section);
1045 // For each input file foo that is embedded to a result as a binary
1046 // blob, we define _binary_foo_{start,end,size} symbols, so that
1047 // user programs can access blobs by name. Non-alphanumeric
1048 // characters in a filename are replaced with underscore.
1049 std::string S = "_binary_" + MB.getBufferIdentifier().str();
1050 for (size_t I = 0; I < S.size(); ++I)
1054 Symtab->addRegular(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 0, 0,
1055 STB_GLOBAL, Section, nullptr);
1056 Symtab->addRegular(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
1057 Data.size(), 0, STB_GLOBAL, Section, nullptr);
1058 Symtab->addRegular(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
1059 Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
1062 static bool isBitcode(MemoryBufferRef MB) {
1063 using namespace sys::fs;
1064 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
1067 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
1068 uint64_t OffsetInArchive) {
1070 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
1072 switch (getELFKind(MB)) {
1074 return make<ObjFile<ELF32LE>>(MB, ArchiveName);
1076 return make<ObjFile<ELF32BE>>(MB, ArchiveName);
1078 return make<ObjFile<ELF64LE>>(MB, ArchiveName);
1080 return make<ObjFile<ELF64BE>>(MB, ArchiveName);
1082 llvm_unreachable("getELFKind");
1086 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
1087 switch (getELFKind(MB)) {
1089 return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
1091 return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
1093 return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
1095 return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
1097 llvm_unreachable("getELFKind");
1101 MemoryBufferRef LazyObjFile::getBuffer() {
1103 return MemoryBufferRef();
1108 InputFile *LazyObjFile::fetch() {
1109 MemoryBufferRef MBRef = getBuffer();
1110 if (MBRef.getBuffer().empty())
1112 return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1115 template <class ELFT> void LazyObjFile::parse() {
1116 for (StringRef Sym : getSymbolNames())
1117 Symtab->addLazyObject<ELFT>(Sym, *this);
1120 template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
1121 typedef typename ELFT::Shdr Elf_Shdr;
1122 typedef typename ELFT::Sym Elf_Sym;
1123 typedef typename ELFT::SymRange Elf_Sym_Range;
1125 ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(this->MB.getBuffer()));
1126 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
1127 for (const Elf_Shdr &Sec : Sections) {
1128 if (Sec.sh_type != SHT_SYMTAB)
1131 Elf_Sym_Range Syms = CHECK(Obj.symbols(&Sec), this);
1132 uint32_t FirstNonLocal = Sec.sh_info;
1133 StringRef StringTable =
1134 CHECK(Obj.getStringTableForSymtab(Sec, Sections), this);
1135 std::vector<StringRef> V;
1137 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1138 if (Sym.st_shndx != SHN_UNDEF)
1139 V.push_back(CHECK(Sym.getName(StringTable), this));
1145 std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1146 std::unique_ptr<lto::InputFile> Obj =
1147 CHECK(lto::InputFile::create(this->MB), this);
1148 std::vector<StringRef> V;
1149 for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1150 if (!Sym.isUndefined())
1151 V.push_back(Saver.save(Sym.getName()));
1155 // Returns a vector of globally-visible defined symbol names.
1156 std::vector<StringRef> LazyObjFile::getSymbolNames() {
1157 if (isBitcode(this->MB))
1158 return getBitcodeSymbols();
1160 switch (getELFKind(this->MB)) {
1162 return getElfSymbols<ELF32LE>();
1164 return getElfSymbols<ELF32BE>();
1166 return getElfSymbols<ELF64LE>();
1168 return getElfSymbols<ELF64BE>();
1170 llvm_unreachable("getELFKind");
1174 template void ArchiveFile::parse<ELF32LE>();
1175 template void ArchiveFile::parse<ELF32BE>();
1176 template void ArchiveFile::parse<ELF64LE>();
1177 template void ArchiveFile::parse<ELF64BE>();
1179 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1180 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1181 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1182 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1184 template void LazyObjFile::parse<ELF32LE>();
1185 template void LazyObjFile::parse<ELF32BE>();
1186 template void LazyObjFile::parse<ELF64LE>();
1187 template void LazyObjFile::parse<ELF64BE>();
1189 template class elf::ELFFileBase<ELF32LE>;
1190 template class elf::ELFFileBase<ELF32BE>;
1191 template class elf::ELFFileBase<ELF64LE>;
1192 template class elf::ELFFileBase<ELF64BE>;
1194 template class elf::ObjFile<ELF32LE>;
1195 template class elf::ObjFile<ELF32BE>;
1196 template class elf::ObjFile<ELF64LE>;
1197 template class elf::ObjFile<ELF64BE>;
1199 template class elf::SharedFile<ELF32LE>;
1200 template class elf::SharedFile<ELF32BE>;
1201 template class elf::SharedFile<ELF64LE>;
1202 template class elf::SharedFile<ELF64BE>;