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 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
445 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
446 // the input objects have been compiled.
447 static void updateARMVFPArgs(const ARMAttributeParser &Attributes,
448 const InputFile *F) {
449 if (!Attributes.hasAttribute(ARMBuildAttrs::ABI_VFP_args))
450 // If an ABI tag isn't present then it is implicitly given the value of 0
451 // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
452 // including some in glibc that don't use FP args (and should have value 3)
453 // don't have the attribute so we do not consider an implicit value of 0
457 unsigned VFPArgs = Attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
460 case ARMBuildAttrs::BaseAAPCS:
461 Arg = ARMVFPArgKind::Base;
463 case ARMBuildAttrs::HardFPAAPCS:
464 Arg = ARMVFPArgKind::VFP;
466 case ARMBuildAttrs::ToolChainFPPCS:
467 // Tool chain specific convention that conforms to neither AAPCS variant.
468 Arg = ARMVFPArgKind::ToolChain;
470 case ARMBuildAttrs::CompatibleFPAAPCS:
471 // Object compatible with all conventions.
474 error(toString(F) + ": unknown Tag_ABI_VFP_args value: " + Twine(VFPArgs));
477 // Follow ld.bfd and error if there is a mix of calling conventions.
478 if (Config->ARMVFPArgs != Arg && Config->ARMVFPArgs != ARMVFPArgKind::Default)
479 error(toString(F) + ": incompatible Tag_ABI_VFP_args");
481 Config->ARMVFPArgs = Arg;
484 // The ARM support in lld makes some use of instructions that are not available
485 // on all ARM architectures. Namely:
486 // - Use of BLX instruction for interworking between ARM and Thumb state.
487 // - Use of the extended Thumb branch encoding in relocation.
488 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
489 // The ARM Attributes section contains information about the architecture chosen
490 // at compile time. We follow the convention that if at least one input object
491 // is compiled with an architecture that supports these features then lld is
492 // permitted to use them.
493 static void updateSupportedARMFeatures(const ARMAttributeParser &Attributes) {
494 if (!Attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
496 auto Arch = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
498 case ARMBuildAttrs::Pre_v4:
499 case ARMBuildAttrs::v4:
500 case ARMBuildAttrs::v4T:
501 // Architectures prior to v5 do not support BLX instruction
503 case ARMBuildAttrs::v5T:
504 case ARMBuildAttrs::v5TE:
505 case ARMBuildAttrs::v5TEJ:
506 case ARMBuildAttrs::v6:
507 case ARMBuildAttrs::v6KZ:
508 case ARMBuildAttrs::v6K:
509 Config->ARMHasBlx = true;
510 // Architectures used in pre-Cortex processors do not support
511 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
512 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
515 // All other Architectures have BLX and extended branch encoding
516 Config->ARMHasBlx = true;
517 Config->ARMJ1J2BranchEncoding = true;
518 if (Arch != ARMBuildAttrs::v6_M && Arch != ARMBuildAttrs::v6S_M)
519 // All Architectures used in Cortex processors with the exception
520 // of v6-M and v6S-M have the MOVT and MOVW instructions.
521 Config->ARMHasMovtMovw = true;
526 template <class ELFT>
527 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
528 uint32_t Idx = Sec.sh_info;
529 if (Idx >= this->Sections.size())
530 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
531 InputSectionBase *Target = this->Sections[Idx];
533 // Strictly speaking, a relocation section must be included in the
534 // group of the section it relocates. However, LLVM 3.3 and earlier
535 // would fail to do so, so we gracefully handle that case.
536 if (Target == &InputSection::Discarded)
540 fatal(toString(this) + ": unsupported relocation reference");
544 // Create a regular InputSection class that has the same contents
545 // as a given section.
546 static InputSection *toRegularSection(MergeInputSection *Sec) {
547 return make<InputSection>(Sec->File, Sec->Flags, Sec->Type, Sec->Alignment,
548 Sec->Data, Sec->Name);
551 template <class ELFT>
552 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
553 StringRef Name = getSectionName(Sec);
555 switch (Sec.sh_type) {
556 case SHT_ARM_ATTRIBUTES: {
557 if (Config->EMachine != EM_ARM)
559 ARMAttributeParser Attributes;
560 ArrayRef<uint8_t> Contents = check(this->getObj().getSectionContents(&Sec));
561 Attributes.Parse(Contents, /*isLittle*/ Config->EKind == ELF32LEKind);
562 updateSupportedARMFeatures(Attributes);
563 updateARMVFPArgs(Attributes, this);
565 // FIXME: Retain the first attribute section we see. The eglibc ARM
566 // dynamic loaders require the presence of an attribute section for dlopen
567 // to work. In a full implementation we would merge all attribute sections.
568 if (InX::ARMAttributes == nullptr) {
569 InX::ARMAttributes = make<InputSection>(*this, Sec, Name);
570 return InX::ARMAttributes;
572 return &InputSection::Discarded;
576 // Find the relocation target section and associate this
577 // section with it. Target can be discarded, for example
578 // if it is a duplicated member of SHT_GROUP section, we
579 // do not create or proccess relocatable sections then.
580 InputSectionBase *Target = getRelocTarget(Sec);
584 // This section contains relocation information.
585 // If -r is given, we do not interpret or apply relocation
586 // but just copy relocation sections to output.
587 if (Config->Relocatable)
588 return make<InputSection>(*this, Sec, Name);
590 if (Target->FirstRelocation)
591 fatal(toString(this) +
592 ": multiple relocation sections to one section are not supported");
594 // Mergeable sections with relocations are tricky because relocations
595 // need to be taken into account when comparing section contents for
596 // merging. It's not worth supporting such mergeable sections because
597 // they are rare and it'd complicates the internal design (we usually
598 // have to determine if two sections are mergeable early in the link
599 // process much before applying relocations). We simply handle mergeable
600 // sections with relocations as non-mergeable.
601 if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
602 Target = toRegularSection(MS);
603 this->Sections[Sec.sh_info] = Target;
606 size_t NumRelocations;
607 if (Sec.sh_type == SHT_RELA) {
608 ArrayRef<Elf_Rela> Rels = CHECK(this->getObj().relas(&Sec), this);
609 Target->FirstRelocation = Rels.begin();
610 NumRelocations = Rels.size();
611 Target->AreRelocsRela = true;
613 ArrayRef<Elf_Rel> Rels = CHECK(this->getObj().rels(&Sec), this);
614 Target->FirstRelocation = Rels.begin();
615 NumRelocations = Rels.size();
616 Target->AreRelocsRela = false;
618 assert(isUInt<31>(NumRelocations));
619 Target->NumRelocations = NumRelocations;
621 // Relocation sections processed by the linker are usually removed
622 // from the output, so returning `nullptr` for the normal case.
623 // However, if -emit-relocs is given, we need to leave them in the output.
624 // (Some post link analysis tools need this information.)
625 if (Config->EmitRelocs) {
626 InputSection *RelocSec = make<InputSection>(*this, Sec, Name);
627 // We will not emit relocation section if target was discarded.
628 Target->DependentSections.push_back(RelocSec);
635 // The GNU linker uses .note.GNU-stack section as a marker indicating
636 // that the code in the object file does not expect that the stack is
637 // executable (in terms of NX bit). If all input files have the marker,
638 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
639 // make the stack non-executable. Most object files have this section as
642 // But making the stack non-executable is a norm today for security
643 // reasons. Failure to do so may result in a serious security issue.
644 // Therefore, we make LLD always add PT_GNU_STACK unless it is
645 // explicitly told to do otherwise (by -z execstack). Because the stack
646 // executable-ness is controlled solely by command line options,
647 // .note.GNU-stack sections are simply ignored.
648 if (Name == ".note.GNU-stack")
649 return &InputSection::Discarded;
651 // Split stacks is a feature to support a discontiguous stack. At least
652 // as of 2017, it seems that the feature is not being used widely.
653 // Only GNU gold supports that. We don't. For the details about that,
654 // see https://gcc.gnu.org/wiki/SplitStacks
655 if (Name == ".note.GNU-split-stack") {
656 error(toString(this) +
657 ": object file compiled with -fsplit-stack is not supported");
658 return &InputSection::Discarded;
661 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
662 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
663 // sections. Drop those sections to avoid duplicate symbol errors.
664 // FIXME: This is glibc PR20543, we should remove this hack once that has been
665 // fixed for a while.
666 if (Name.startswith(".gnu.linkonce."))
667 return &InputSection::Discarded;
669 // The linker merges EH (exception handling) frames and creates a
670 // .eh_frame_hdr section for runtime. So we handle them with a special
671 // class. For relocatable outputs, they are just passed through.
672 if (Name == ".eh_frame" && !Config->Relocatable)
673 return make<EhInputSection>(*this, Sec, Name);
675 if (shouldMerge(Sec))
676 return make<MergeInputSection>(*this, Sec, Name);
677 return make<InputSection>(*this, Sec, Name);
680 template <class ELFT>
681 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
682 return CHECK(this->getObj().getSectionName(&Sec, SectionStringTable), this);
685 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
686 this->Symbols.reserve(this->ELFSyms.size());
687 for (const Elf_Sym &Sym : this->ELFSyms)
688 this->Symbols.push_back(createSymbol(&Sym));
691 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) {
692 int Binding = Sym->getBinding();
694 uint32_t SecIdx = this->getSectionIndex(*Sym);
695 if (SecIdx >= this->Sections.size())
696 fatal(toString(this) + ": invalid section index: " + Twine(SecIdx));
698 InputSectionBase *Sec = this->Sections[SecIdx];
699 uint8_t StOther = Sym->st_other;
700 uint8_t Type = Sym->getType();
701 uint64_t Value = Sym->st_value;
702 uint64_t Size = Sym->st_size;
704 if (Binding == STB_LOCAL) {
705 if (Sym->getType() == STT_FILE)
706 SourceFile = CHECK(Sym->getName(this->StringTable), this);
708 if (this->StringTable.size() <= Sym->st_name)
709 fatal(toString(this) + ": invalid symbol name offset");
711 StringRefZ Name = this->StringTable.data() + Sym->st_name;
712 if (Sym->st_shndx == SHN_UNDEF)
713 return make<Undefined>(this, Name, Binding, StOther, Type);
715 return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec);
718 StringRef Name = CHECK(Sym->getName(this->StringTable), this);
720 switch (Sym->st_shndx) {
722 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
723 /*CanOmitFromDynSym=*/false, this);
725 if (Value == 0 || Value >= UINT32_MAX)
726 fatal(toString(this) + ": common symbol '" + Name +
727 "' has invalid alignment: " + Twine(Value));
728 return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, *this);
733 fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
737 if (Sec == &InputSection::Discarded)
738 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
739 /*CanOmitFromDynSym=*/false, this);
740 return Symtab->addRegular(Name, StOther, Type, Value, Size, Binding, Sec,
745 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
746 : InputFile(ArchiveKind, File->getMemoryBufferRef()),
747 File(std::move(File)) {}
749 template <class ELFT> void ArchiveFile::parse() {
750 Symbols.reserve(File->getNumberOfSymbols());
751 for (const Archive::Symbol &Sym : File->symbols())
752 Symbols.push_back(Symtab->addLazyArchive<ELFT>(Sym.getName(), *this, Sym));
755 // Returns a buffer pointing to a member file containing a given symbol.
756 std::pair<MemoryBufferRef, uint64_t>
757 ArchiveFile::getMember(const Archive::Symbol *Sym) {
759 CHECK(Sym->getMember(), toString(this) +
760 ": could not get the member for symbol " +
763 if (!Seen.insert(C.getChildOffset()).second)
764 return {MemoryBufferRef(), 0};
766 MemoryBufferRef Ret =
767 CHECK(C.getMemoryBufferRef(),
769 ": could not get the buffer for the member defining symbol " +
772 if (C.getParent()->isThin() && Tar)
773 Tar->append(relativeToRoot(CHECK(C.getFullName(), this)), Ret.getBuffer());
774 if (C.getParent()->isThin())
776 return {Ret, C.getChildOffset()};
779 template <class ELFT>
780 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
781 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
782 IsNeeded(!Config->AsNeeded) {}
784 // Partially parse the shared object file so that we can call
785 // getSoName on this object.
786 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
787 const Elf_Shdr *DynamicSec = nullptr;
788 const ELFFile<ELFT> Obj = this->getObj();
789 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
791 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
792 for (const Elf_Shdr &Sec : Sections) {
793 switch (Sec.sh_type) {
797 this->initSymtab(Sections, &Sec);
802 case SHT_SYMTAB_SHNDX:
803 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this);
806 this->VersymSec = &Sec;
809 this->VerdefSec = &Sec;
814 if (this->VersymSec && this->ELFSyms.empty())
815 error("SHT_GNU_versym should be associated with symbol table");
817 // Search for a DT_SONAME tag to initialize this->SoName.
820 ArrayRef<Elf_Dyn> Arr =
821 CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this);
822 for (const Elf_Dyn &Dyn : Arr) {
823 if (Dyn.d_tag == DT_SONAME) {
824 uint64_t Val = Dyn.getVal();
825 if (Val >= this->StringTable.size())
826 fatal(toString(this) + ": invalid DT_SONAME entry");
827 SoName = this->StringTable.data() + Val;
833 // Parse the version definitions in the object file if present. Returns a vector
834 // whose nth element contains a pointer to the Elf_Verdef for version identifier
835 // n. Version identifiers that are not definitions map to nullptr. The array
836 // always has at least length 1.
837 template <class ELFT>
838 std::vector<const typename ELFT::Verdef *>
839 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
840 std::vector<const Elf_Verdef *> Verdefs(1);
841 // We only need to process symbol versions for this DSO if it has both a
842 // versym and a verdef section, which indicates that the DSO contains symbol
843 // version definitions.
844 if (!VersymSec || !VerdefSec)
847 // The location of the first global versym entry.
848 const char *Base = this->MB.getBuffer().data();
849 Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
852 // We cannot determine the largest verdef identifier without inspecting
853 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
854 // sequentially starting from 1, so we predict that the largest identifier
855 // will be VerdefCount.
856 unsigned VerdefCount = VerdefSec->sh_info;
857 Verdefs.resize(VerdefCount + 1);
859 // Build the Verdefs array by following the chain of Elf_Verdef objects
860 // from the start of the .gnu.version_d section.
861 const char *Verdef = Base + VerdefSec->sh_offset;
862 for (unsigned I = 0; I != VerdefCount; ++I) {
863 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
864 Verdef += CurVerdef->vd_next;
865 unsigned VerdefIndex = CurVerdef->vd_ndx;
866 if (Verdefs.size() <= VerdefIndex)
867 Verdefs.resize(VerdefIndex + 1);
868 Verdefs[VerdefIndex] = CurVerdef;
874 // Fully parse the shared object file. This must be called after parseSoName().
875 template <class ELFT> void SharedFile<ELFT>::parseRest() {
876 // Create mapping from version identifiers to Elf_Verdef entries.
877 const Elf_Versym *Versym = nullptr;
878 Verdefs = parseVerdefs(Versym);
880 ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this);
882 // Add symbols to the symbol table.
883 Elf_Sym_Range Syms = this->getGlobalELFSyms();
884 for (const Elf_Sym &Sym : Syms) {
885 unsigned VersymIndex = VER_NDX_GLOBAL;
887 VersymIndex = Versym->vs_index;
890 bool Hidden = VersymIndex & VERSYM_HIDDEN;
891 VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
893 StringRef Name = CHECK(Sym.getName(this->StringTable), this);
894 if (Sym.isUndefined()) {
895 Undefs.push_back(Name);
899 if (Sym.getBinding() == STB_LOCAL) {
900 warn("found local symbol '" + Name +
901 "' in global part of symbol table in file " + toString(this));
905 if (Config->EMachine == EM_MIPS) {
906 // FIXME: MIPS BFD linker puts _gp_disp symbol into DSO files
907 // and incorrectly assigns VER_NDX_LOCAL to this section global
908 // symbol. Here is a workaround for this bug.
909 if (Versym && VersymIndex == VER_NDX_LOCAL && Name == "_gp_disp")
913 const Elf_Verdef *Ver = nullptr;
914 if (VersymIndex != VER_NDX_GLOBAL) {
915 if (VersymIndex >= Verdefs.size() || VersymIndex == VER_NDX_LOCAL) {
916 error("corrupt input file: version definition index " +
917 Twine(VersymIndex) + " for symbol " + Name +
918 " is out of bounds\n>>> defined in " + toString(this));
921 Ver = Verdefs[VersymIndex];
926 // We do not usually care about alignments of data in shared object
927 // files because the loader takes care of it. However, if we promote a
928 // DSO symbol to point to .bss due to copy relocation, we need to keep
929 // the original alignment requirements. We infer it here.
930 uint64_t Alignment = 1;
932 Alignment = 1ULL << countTrailingZeros((uint64_t)Sym.st_value);
933 if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) {
934 uint64_t SecAlign = Sections[Sym.st_shndx].sh_addralign;
935 Alignment = std::min(Alignment, SecAlign);
937 if (Alignment > UINT32_MAX)
938 error(toString(this) + ": alignment too large: " + Name);
941 Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
943 // Also add the symbol with the versioned name to handle undefined symbols
944 // with explicit versions.
946 StringRef VerName = this->StringTable.data() + Ver->getAux()->vda_name;
947 Name = Saver.save(Name + "@" + VerName);
948 Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
953 static ELFKind getBitcodeELFKind(const Triple &T) {
954 if (T.isLittleEndian())
955 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
956 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
959 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
960 switch (T.getArch()) {
961 case Triple::aarch64:
971 case Triple::mips64el:
978 return T.isOSIAMCU() ? EM_IAMCU : EM_386;
982 fatal(Path + ": could not infer e_machine from bitcode target triple " +
987 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
988 uint64_t OffsetInArchive)
989 : InputFile(BitcodeKind, MB) {
990 this->ArchiveName = ArchiveName;
992 // Here we pass a new MemoryBufferRef which is identified by ArchiveName
993 // (the fully resolved path of the archive) + member name + offset of the
994 // member in the archive.
995 // ThinLTO uses the MemoryBufferRef identifier to access its internal
996 // data structures and if two archives define two members with the same name,
997 // this causes a collision which result in only one of the objects being
998 // taken into consideration at LTO time (which very likely causes undefined
999 // symbols later in the link stage).
1000 MemoryBufferRef MBRef(MB.getBuffer(),
1001 Saver.save(ArchiveName + MB.getBufferIdentifier() +
1002 utostr(OffsetInArchive)));
1003 Obj = CHECK(lto::InputFile::create(MBRef), this);
1005 Triple T(Obj->getTargetTriple());
1006 EKind = getBitcodeELFKind(T);
1007 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
1010 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
1011 switch (GvVisibility) {
1012 case GlobalValue::DefaultVisibility:
1014 case GlobalValue::HiddenVisibility:
1016 case GlobalValue::ProtectedVisibility:
1017 return STV_PROTECTED;
1019 llvm_unreachable("unknown visibility");
1022 template <class ELFT>
1023 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
1024 const lto::InputFile::Symbol &ObjSym,
1026 StringRef NameRef = Saver.save(ObjSym.getName());
1027 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1029 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
1030 uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
1031 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
1033 int C = ObjSym.getComdatIndex();
1034 if (C != -1 && !KeptComdats[C])
1035 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
1036 CanOmitFromDynSym, &F);
1038 if (ObjSym.isUndefined())
1039 return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
1040 CanOmitFromDynSym, &F);
1042 if (ObjSym.isCommon())
1043 return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
1044 ObjSym.getCommonAlignment(), Binding, Visibility,
1047 return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
1048 CanOmitFromDynSym, F);
1051 template <class ELFT>
1052 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
1053 std::vector<bool> KeptComdats;
1054 for (StringRef S : Obj->getComdatTable())
1055 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
1057 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
1058 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this));
1061 static ELFKind getELFKind(MemoryBufferRef MB) {
1063 unsigned char Endian;
1064 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
1066 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
1067 fatal(MB.getBufferIdentifier() + ": invalid data encoding");
1068 if (Size != ELFCLASS32 && Size != ELFCLASS64)
1069 fatal(MB.getBufferIdentifier() + ": invalid file class");
1071 size_t BufSize = MB.getBuffer().size();
1072 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
1073 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
1074 fatal(MB.getBufferIdentifier() + ": file is too short");
1076 if (Size == ELFCLASS32)
1077 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
1078 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
1081 void BinaryFile::parse() {
1082 ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
1083 auto *Section = make<InputSection>(nullptr, SHF_ALLOC | SHF_WRITE,
1084 SHT_PROGBITS, 8, Data, ".data");
1085 Sections.push_back(Section);
1087 // For each input file foo that is embedded to a result as a binary
1088 // blob, we define _binary_foo_{start,end,size} symbols, so that
1089 // user programs can access blobs by name. Non-alphanumeric
1090 // characters in a filename are replaced with underscore.
1091 std::string S = "_binary_" + MB.getBufferIdentifier().str();
1092 for (size_t I = 0; I < S.size(); ++I)
1096 Symtab->addRegular(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 0, 0,
1097 STB_GLOBAL, Section, nullptr);
1098 Symtab->addRegular(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
1099 Data.size(), 0, STB_GLOBAL, Section, nullptr);
1100 Symtab->addRegular(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
1101 Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
1104 static bool isBitcode(MemoryBufferRef MB) {
1105 using namespace sys::fs;
1106 return identify_magic(MB.getBuffer()) == file_magic::bitcode;
1109 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
1110 uint64_t OffsetInArchive) {
1112 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
1114 switch (getELFKind(MB)) {
1116 return make<ObjFile<ELF32LE>>(MB, ArchiveName);
1118 return make<ObjFile<ELF32BE>>(MB, ArchiveName);
1120 return make<ObjFile<ELF64LE>>(MB, ArchiveName);
1122 return make<ObjFile<ELF64BE>>(MB, ArchiveName);
1124 llvm_unreachable("getELFKind");
1128 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
1129 switch (getELFKind(MB)) {
1131 return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
1133 return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
1135 return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
1137 return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
1139 llvm_unreachable("getELFKind");
1143 MemoryBufferRef LazyObjFile::getBuffer() {
1145 return MemoryBufferRef();
1150 InputFile *LazyObjFile::fetch() {
1151 MemoryBufferRef MBRef = getBuffer();
1152 if (MBRef.getBuffer().empty())
1154 return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1157 template <class ELFT> void LazyObjFile::parse() {
1158 for (StringRef Sym : getSymbolNames())
1159 Symtab->addLazyObject<ELFT>(Sym, *this);
1162 template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
1163 typedef typename ELFT::Shdr Elf_Shdr;
1164 typedef typename ELFT::Sym Elf_Sym;
1165 typedef typename ELFT::SymRange Elf_Sym_Range;
1167 ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(this->MB.getBuffer()));
1168 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
1169 for (const Elf_Shdr &Sec : Sections) {
1170 if (Sec.sh_type != SHT_SYMTAB)
1173 Elf_Sym_Range Syms = CHECK(Obj.symbols(&Sec), this);
1174 uint32_t FirstNonLocal = Sec.sh_info;
1175 StringRef StringTable =
1176 CHECK(Obj.getStringTableForSymtab(Sec, Sections), this);
1177 std::vector<StringRef> V;
1179 for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1180 if (Sym.st_shndx != SHN_UNDEF)
1181 V.push_back(CHECK(Sym.getName(StringTable), this));
1187 std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1188 std::unique_ptr<lto::InputFile> Obj =
1189 CHECK(lto::InputFile::create(this->MB), this);
1190 std::vector<StringRef> V;
1191 for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1192 if (!Sym.isUndefined())
1193 V.push_back(Saver.save(Sym.getName()));
1197 // Returns a vector of globally-visible defined symbol names.
1198 std::vector<StringRef> LazyObjFile::getSymbolNames() {
1199 if (isBitcode(this->MB))
1200 return getBitcodeSymbols();
1202 switch (getELFKind(this->MB)) {
1204 return getElfSymbols<ELF32LE>();
1206 return getElfSymbols<ELF32BE>();
1208 return getElfSymbols<ELF64LE>();
1210 return getElfSymbols<ELF64BE>();
1212 llvm_unreachable("getELFKind");
1216 template void ArchiveFile::parse<ELF32LE>();
1217 template void ArchiveFile::parse<ELF32BE>();
1218 template void ArchiveFile::parse<ELF64LE>();
1219 template void ArchiveFile::parse<ELF64BE>();
1221 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1222 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1223 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1224 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1226 template void LazyObjFile::parse<ELF32LE>();
1227 template void LazyObjFile::parse<ELF32BE>();
1228 template void LazyObjFile::parse<ELF64LE>();
1229 template void LazyObjFile::parse<ELF64BE>();
1231 template class elf::ELFFileBase<ELF32LE>;
1232 template class elf::ELFFileBase<ELF32BE>;
1233 template class elf::ELFFileBase<ELF64LE>;
1234 template class elf::ELFFileBase<ELF64BE>;
1236 template class elf::ObjFile<ELF32LE>;
1237 template class elf::ObjFile<ELF32BE>;
1238 template class elf::ObjFile<ELF64LE>;
1239 template class elf::ObjFile<ELF64BE>;
1241 template class elf::SharedFile<ELF32LE>;
1242 template class elf::SharedFile<ELF32BE>;
1243 template class elf::SharedFile<ELF64LE>;
1244 template class elf::SharedFile<ELF64BE>;