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 bool InputFile::IsInGroup;
42 uint32_t InputFile::NextGroupId;
43 std::vector<BinaryFile *> elf::BinaryFiles;
44 std::vector<BitcodeFile *> elf::BitcodeFiles;
45 std::vector<LazyObjFile *> elf::LazyObjFiles;
46 std::vector<InputFile *> elf::ObjectFiles;
47 std::vector<InputFile *> elf::SharedFiles;
49 std::unique_ptr<TarWriter> elf::Tar;
51 InputFile::InputFile(Kind K, MemoryBufferRef M)
52 : MB(M), GroupId(NextGroupId), FileKind(K) {
53 // All files within the same --{start,end}-group get the same group ID.
54 // Otherwise, a new file will get a new group ID.
59 Optional<MemoryBufferRef> elf::readFile(StringRef Path) {
60 // The --chroot option changes our virtual root directory.
61 // This is useful when you are dealing with files created by --reproduce.
62 if (!Config->Chroot.empty() && Path.startswith("/"))
63 Path = Saver.save(Config->Chroot + Path);
67 auto MBOrErr = MemoryBuffer::getFile(Path, -1, false);
68 if (auto EC = MBOrErr.getError()) {
69 error("cannot open " + Path + ": " + EC.message());
73 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
74 MemoryBufferRef MBRef = MB->getMemBufferRef();
75 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
78 Tar->append(relativeToRoot(Path), MBRef.getBuffer());
82 // Concatenates arguments to construct a string representing an error location.
83 static std::string createFileLineMsg(StringRef Path, unsigned Line) {
84 std::string Filename = path::filename(Path);
85 std::string Lineno = ":" + std::to_string(Line);
87 return Filename + Lineno;
88 return Filename + Lineno + " (" + Path.str() + Lineno + ")";
92 static std::string getSrcMsgAux(ObjFile<ELFT> &File, const Symbol &Sym,
93 InputSectionBase &Sec, uint64_t Offset) {
94 // In DWARF, functions and variables are stored to different places.
95 // First, lookup a function for a given offset.
96 if (Optional<DILineInfo> Info = File.getDILineInfo(&Sec, Offset))
97 return createFileLineMsg(Info->FileName, Info->Line);
99 // If it failed, lookup again as a variable.
100 if (Optional<std::pair<std::string, unsigned>> FileLine =
101 File.getVariableLoc(Sym.getName()))
102 return createFileLineMsg(FileLine->first, FileLine->second);
104 // File.SourceFile contains STT_FILE symbol, and that is a last resort.
105 return File.SourceFile;
108 std::string InputFile::getSrcMsg(const Symbol &Sym, InputSectionBase &Sec,
110 if (kind() != ObjKind)
112 switch (Config->EKind) {
114 llvm_unreachable("Invalid kind");
116 return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), Sym, Sec, Offset);
118 return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), Sym, Sec, Offset);
120 return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), Sym, Sec, Offset);
122 return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), Sym, Sec, Offset);
126 template <class ELFT> void ObjFile<ELFT>::initializeDwarf() {
127 Dwarf = llvm::make_unique<DWARFContext>(make_unique<LLDDwarfObj<ELFT>>(this));
128 for (std::unique_ptr<DWARFUnit> &CU : Dwarf->compile_units()) {
129 auto Report = [](Error Err) {
130 handleAllErrors(std::move(Err),
131 [](ErrorInfoBase &Info) { warn(Info.message()); });
133 Expected<const DWARFDebugLine::LineTable *> ExpectedLT =
134 Dwarf->getLineTableForUnit(CU.get(), Report);
135 const DWARFDebugLine::LineTable *LT = nullptr;
139 Report(ExpectedLT.takeError());
142 LineTables.push_back(LT);
144 // Loop over variable records and insert them to VariableLoc.
145 for (const auto &Entry : CU->dies()) {
146 DWARFDie Die(CU.get(), &Entry);
147 // Skip all tags that are not variables.
148 if (Die.getTag() != dwarf::DW_TAG_variable)
151 // Skip if a local variable because we don't need them for generating
152 // error messages. In general, only non-local symbols can fail to be
154 if (!dwarf::toUnsigned(Die.find(dwarf::DW_AT_external), 0))
157 // Get the source filename index for the variable.
158 unsigned File = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_file), 0);
159 if (!LT->hasFileAtIndex(File))
162 // Get the line number on which the variable is declared.
163 unsigned Line = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_line), 0);
165 // Here we want to take the variable name to add it into VariableLoc.
166 // Variable can have regular and linkage name associated. At first, we try
167 // to get linkage name as it can be different, for example when we have
168 // two variables in different namespaces of the same object. Use common
169 // name otherwise, but handle the case when it also absent in case if the
170 // input object file lacks some debug info.
172 dwarf::toString(Die.find(dwarf::DW_AT_linkage_name),
173 dwarf::toString(Die.find(dwarf::DW_AT_name), ""));
175 VariableLoc.insert({Name, {LT, File, Line}});
180 // Returns the pair of file name and line number describing location of data
181 // object (variable, array, etc) definition.
182 template <class ELFT>
183 Optional<std::pair<std::string, unsigned>>
184 ObjFile<ELFT>::getVariableLoc(StringRef Name) {
185 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
187 // Return if we have no debug information about data object.
188 auto It = VariableLoc.find(Name);
189 if (It == VariableLoc.end())
192 // Take file name string from line table.
193 std::string FileName;
194 if (!It->second.LT->getFileNameByIndex(
195 It->second.File, nullptr,
196 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FileName))
199 return std::make_pair(FileName, It->second.Line);
202 // Returns source line information for a given offset
203 // using DWARF debug info.
204 template <class ELFT>
205 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *S,
207 llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
209 // Use fake address calcuated by adding section file offset and offset in
210 // section. See comments for ObjectInfo class.
212 for (const llvm::DWARFDebugLine::LineTable *LT : LineTables)
213 if (LT->getFileLineInfoForAddress(
214 S->getOffsetInFile() + Offset, nullptr,
215 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info))
220 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
221 std::string lld::toString(const InputFile *F) {
225 if (F->ToStringCache.empty()) {
226 if (F->ArchiveName.empty())
227 F->ToStringCache = F->getName();
229 F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str();
231 return F->ToStringCache;
234 template <class ELFT>
235 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
236 if (ELFT::TargetEndianness == support::little)
237 EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
239 EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
241 EMachine = getObj().getHeader()->e_machine;
242 OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
245 template <class ELFT>
246 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalELFSyms() {
247 return makeArrayRef(ELFSyms.begin() + FirstGlobal, ELFSyms.end());
250 template <class ELFT>
251 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
252 return CHECK(getObj().getSectionIndex(&Sym, ELFSyms, SymtabSHNDX), this);
255 template <class ELFT>
256 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
257 const Elf_Shdr *Symtab) {
258 FirstGlobal = Symtab->sh_info;
259 ELFSyms = CHECK(getObj().symbols(Symtab), this);
260 if (FirstGlobal == 0 || FirstGlobal > ELFSyms.size())
261 fatal(toString(this) + ": invalid sh_info in symbol table");
264 CHECK(getObj().getStringTableForSymtab(*Symtab, Sections), this);
267 template <class ELFT>
268 ObjFile<ELFT>::ObjFile(MemoryBufferRef M, StringRef ArchiveName)
269 : ELFFileBase<ELFT>(Base::ObjKind, M) {
270 this->ArchiveName = ArchiveName;
273 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
274 if (this->Symbols.empty())
276 return makeArrayRef(this->Symbols).slice(1, this->FirstGlobal - 1);
279 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getGlobalSymbols() {
280 return makeArrayRef(this->Symbols).slice(this->FirstGlobal);
283 template <class ELFT>
284 void ObjFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
285 // Read a section table. JustSymbols is usually false.
286 if (this->JustSymbols)
287 initializeJustSymbols();
289 initializeSections(ComdatGroups);
291 // Read a symbol table.
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 newest 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> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
324 // On a regular link we don't merge sections if -O0 (default is -O1). This
325 // sometimes makes the linker significantly faster, although the output will
328 // Doing the same for -r would create a problem as it would combine sections
329 // with different sh_entsize. One option would be to just copy every SHF_MERGE
330 // section as is to the output. While this would produce a valid ELF file with
331 // usable SHF_MERGE sections, tools like (llvm-)?dwarfdump get confused when
332 // they see two .debug_str. We could have separate logic for combining
333 // SHF_MERGE sections based both on their name and sh_entsize, but that seems
334 // to be more trouble than it is worth. Instead, we just use the regular (-O1)
336 if (Config->Optimize == 0 && !Config->Relocatable)
339 // A mergeable section with size 0 is useless because they don't have
340 // any data to merge. A mergeable string section with size 0 can be
341 // argued as invalid because it doesn't end with a null character.
342 // We'll avoid a mess by handling them as if they were non-mergeable.
343 if (Sec.sh_size == 0)
346 // Check for sh_entsize. The ELF spec is not clear about the zero
347 // sh_entsize. It says that "the member [sh_entsize] contains 0 if
348 // the section does not hold a table of fixed-size entries". We know
349 // that Rust 1.13 produces a string mergeable section with a zero
350 // sh_entsize. Here we just accept it rather than being picky about it.
351 uint64_t EntSize = Sec.sh_entsize;
354 if (Sec.sh_size % EntSize)
355 fatal(toString(this) +
356 ": SHF_MERGE section size must be a multiple of sh_entsize");
358 uint64_t Flags = Sec.sh_flags;
359 if (!(Flags & SHF_MERGE))
361 if (Flags & SHF_WRITE)
362 fatal(toString(this) + ": writable SHF_MERGE section is not supported");
367 // This is for --just-symbols.
369 // --just-symbols is a very minor feature that allows you to link your
370 // output against other existing program, so that if you load both your
371 // program and the other program into memory, your output can refer the
372 // other program's symbols.
374 // When the option is given, we link "just symbols". The section table is
375 // initialized with null pointers.
376 template <class ELFT> void ObjFile<ELFT>::initializeJustSymbols() {
377 ArrayRef<Elf_Shdr> ObjSections = CHECK(this->getObj().sections(), this);
378 this->Sections.resize(ObjSections.size());
380 for (const Elf_Shdr &Sec : ObjSections) {
381 if (Sec.sh_type != SHT_SYMTAB)
383 this->initSymtab(ObjSections, &Sec);
388 template <class ELFT>
389 void ObjFile<ELFT>::initializeSections(
390 DenseSet<CachedHashStringRef> &ComdatGroups) {
391 const ELFFile<ELFT> &Obj = this->getObj();
393 ArrayRef<Elf_Shdr> ObjSections = CHECK(Obj.sections(), this);
394 uint64_t Size = ObjSections.size();
395 this->Sections.resize(Size);
396 this->SectionStringTable =
397 CHECK(Obj.getSectionStringTable(ObjSections), this);
399 for (size_t I = 0, E = ObjSections.size(); I < E; I++) {
400 if (this->Sections[I] == &InputSection::Discarded)
402 const Elf_Shdr &Sec = ObjSections[I];
404 if (Sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE)
406 this->getObj().template getSectionContentsAsArray<Elf_CGProfile>(
409 // SHF_EXCLUDE'ed sections are discarded by the linker. However,
410 // if -r is given, we'll let the final link discard such sections.
411 // This is compatible with GNU.
412 if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
413 if (Sec.sh_type == SHT_LLVM_ADDRSIG) {
414 // We ignore the address-significance table if we know that the object
415 // file was created by objcopy or ld -r. This is because these tools
416 // will reorder the symbols in the symbol table, invalidating the data
417 // in the address-significance table, which refers to symbols by index.
418 if (Sec.sh_link != 0)
419 this->AddrsigSec = &Sec;
420 else if (Config->ICF == ICFLevel::Safe)
421 warn(toString(this) + ": --icf=safe is incompatible with object "
422 "files created using objcopy or ld -r");
424 this->Sections[I] = &InputSection::Discarded;
428 switch (Sec.sh_type) {
430 // De-duplicate section groups by their signatures.
431 StringRef Signature = getShtGroupSignature(ObjSections, Sec);
432 this->Sections[I] = &InputSection::Discarded;
435 ArrayRef<Elf_Word> Entries =
436 CHECK(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), this);
438 fatal(toString(this) + ": empty SHT_GROUP");
440 // The first word of a SHT_GROUP section contains flags. Currently,
441 // the standard defines only "GRP_COMDAT" flag for the COMDAT group.
442 // An group with the empty flag doesn't define anything; such sections
447 if (Entries[0] != GRP_COMDAT)
448 fatal(toString(this) + ": unsupported SHT_GROUP format");
450 bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second;
452 if (Config->Relocatable)
453 this->Sections[I] = createInputSection(Sec);
458 // Otherwise, discard group members.
459 for (uint32_t SecIndex : Entries.slice(1)) {
460 if (SecIndex >= Size)
461 fatal(toString(this) +
462 ": invalid section index in group: " + Twine(SecIndex));
463 this->Sections[SecIndex] = &InputSection::Discarded;
468 this->initSymtab(ObjSections, &Sec);
470 case SHT_SYMTAB_SHNDX:
471 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, ObjSections), this);
477 this->Sections[I] = createInputSection(Sec);
480 // .ARM.exidx sections have a reverse dependency on the InputSection they
481 // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
482 if (Sec.sh_flags & SHF_LINK_ORDER) {
483 InputSectionBase *LinkSec = nullptr;
484 if (Sec.sh_link < this->Sections.size())
485 LinkSec = this->Sections[Sec.sh_link];
487 fatal(toString(this) +
488 ": invalid sh_link index: " + Twine(Sec.sh_link));
490 InputSection *IS = cast<InputSection>(this->Sections[I]);
491 LinkSec->DependentSections.push_back(IS);
492 if (!isa<InputSection>(LinkSec))
493 error("a section " + IS->Name +
494 " with SHF_LINK_ORDER should not refer a non-regular "
501 // For ARM only, to set the EF_ARM_ABI_FLOAT_SOFT or EF_ARM_ABI_FLOAT_HARD
502 // flag in the ELF Header we need to look at Tag_ABI_VFP_args to find out how
503 // the input objects have been compiled.
504 static void updateARMVFPArgs(const ARMAttributeParser &Attributes,
505 const InputFile *F) {
506 if (!Attributes.hasAttribute(ARMBuildAttrs::ABI_VFP_args))
507 // If an ABI tag isn't present then it is implicitly given the value of 0
508 // which maps to ARMBuildAttrs::BaseAAPCS. However many assembler files,
509 // including some in glibc that don't use FP args (and should have value 3)
510 // don't have the attribute so we do not consider an implicit value of 0
514 unsigned VFPArgs = Attributes.getAttributeValue(ARMBuildAttrs::ABI_VFP_args);
517 case ARMBuildAttrs::BaseAAPCS:
518 Arg = ARMVFPArgKind::Base;
520 case ARMBuildAttrs::HardFPAAPCS:
521 Arg = ARMVFPArgKind::VFP;
523 case ARMBuildAttrs::ToolChainFPPCS:
524 // Tool chain specific convention that conforms to neither AAPCS variant.
525 Arg = ARMVFPArgKind::ToolChain;
527 case ARMBuildAttrs::CompatibleFPAAPCS:
528 // Object compatible with all conventions.
531 error(toString(F) + ": unknown Tag_ABI_VFP_args value: " + Twine(VFPArgs));
534 // Follow ld.bfd and error if there is a mix of calling conventions.
535 if (Config->ARMVFPArgs != Arg && Config->ARMVFPArgs != ARMVFPArgKind::Default)
536 error(toString(F) + ": incompatible Tag_ABI_VFP_args");
538 Config->ARMVFPArgs = Arg;
541 // The ARM support in lld makes some use of instructions that are not available
542 // on all ARM architectures. Namely:
543 // - Use of BLX instruction for interworking between ARM and Thumb state.
544 // - Use of the extended Thumb branch encoding in relocation.
545 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
546 // The ARM Attributes section contains information about the architecture chosen
547 // at compile time. We follow the convention that if at least one input object
548 // is compiled with an architecture that supports these features then lld is
549 // permitted to use them.
550 static void updateSupportedARMFeatures(const ARMAttributeParser &Attributes) {
551 if (!Attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
553 auto Arch = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
555 case ARMBuildAttrs::Pre_v4:
556 case ARMBuildAttrs::v4:
557 case ARMBuildAttrs::v4T:
558 // Architectures prior to v5 do not support BLX instruction
560 case ARMBuildAttrs::v5T:
561 case ARMBuildAttrs::v5TE:
562 case ARMBuildAttrs::v5TEJ:
563 case ARMBuildAttrs::v6:
564 case ARMBuildAttrs::v6KZ:
565 case ARMBuildAttrs::v6K:
566 Config->ARMHasBlx = true;
567 // Architectures used in pre-Cortex processors do not support
568 // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
569 // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
572 // All other Architectures have BLX and extended branch encoding
573 Config->ARMHasBlx = true;
574 Config->ARMJ1J2BranchEncoding = true;
575 if (Arch != ARMBuildAttrs::v6_M && Arch != ARMBuildAttrs::v6S_M)
576 // All Architectures used in Cortex processors with the exception
577 // of v6-M and v6S-M have the MOVT and MOVW instructions.
578 Config->ARMHasMovtMovw = true;
583 template <class ELFT>
584 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
585 uint32_t Idx = Sec.sh_info;
586 if (Idx >= this->Sections.size())
587 fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
588 InputSectionBase *Target = this->Sections[Idx];
590 // Strictly speaking, a relocation section must be included in the
591 // group of the section it relocates. However, LLVM 3.3 and earlier
592 // would fail to do so, so we gracefully handle that case.
593 if (Target == &InputSection::Discarded)
597 fatal(toString(this) + ": unsupported relocation reference");
601 // Create a regular InputSection class that has the same contents
602 // as a given section.
603 static InputSection *toRegularSection(MergeInputSection *Sec) {
604 return make<InputSection>(Sec->File, Sec->Flags, Sec->Type, Sec->Alignment,
605 Sec->data(), Sec->Name);
608 template <class ELFT>
609 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
610 StringRef Name = getSectionName(Sec);
612 switch (Sec.sh_type) {
613 case SHT_ARM_ATTRIBUTES: {
614 if (Config->EMachine != EM_ARM)
616 ARMAttributeParser Attributes;
617 ArrayRef<uint8_t> Contents = check(this->getObj().getSectionContents(&Sec));
618 Attributes.Parse(Contents, /*isLittle*/ Config->EKind == ELF32LEKind);
619 updateSupportedARMFeatures(Attributes);
620 updateARMVFPArgs(Attributes, this);
622 // FIXME: Retain the first attribute section we see. The eglibc ARM
623 // dynamic loaders require the presence of an attribute section for dlopen
624 // to work. In a full implementation we would merge all attribute sections.
625 if (In.ARMAttributes == nullptr) {
626 In.ARMAttributes = make<InputSection>(*this, Sec, Name);
627 return In.ARMAttributes;
629 return &InputSection::Discarded;
633 // Find a relocation target section and associate this section with that.
634 // Target may have been discarded if it is in a different section group
635 // and the group is discarded, even though it's a violation of the
636 // spec. We handle that situation gracefully by discarding dangling
637 // relocation sections.
638 InputSectionBase *Target = getRelocTarget(Sec);
642 // This section contains relocation information.
643 // If -r is given, we do not interpret or apply relocation
644 // but just copy relocation sections to output.
645 if (Config->Relocatable) {
646 InputSection *RelocSec = make<InputSection>(*this, Sec, Name);
647 // We want to add a dependency to target, similar like we do for
648 // -emit-relocs below. This is useful for the case when linker script
649 // contains the "/DISCARD/". It is perhaps uncommon to use a script with
650 // -r, but we faced it in the Linux kernel and have to handle such case
652 Target->DependentSections.push_back(RelocSec);
656 if (Target->FirstRelocation)
657 fatal(toString(this) +
658 ": multiple relocation sections to one section are not supported");
660 // ELF spec allows mergeable sections with relocations, but they are
661 // rare, and it is in practice hard to merge such sections by contents,
662 // because applying relocations at end of linking changes section
663 // contents. So, we simply handle such sections as non-mergeable ones.
664 // Degrading like this is acceptable because section merging is optional.
665 if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
666 Target = toRegularSection(MS);
667 this->Sections[Sec.sh_info] = Target;
670 if (Sec.sh_type == SHT_RELA) {
671 ArrayRef<Elf_Rela> Rels = CHECK(this->getObj().relas(&Sec), this);
672 Target->FirstRelocation = Rels.begin();
673 Target->NumRelocations = Rels.size();
674 Target->AreRelocsRela = true;
676 ArrayRef<Elf_Rel> Rels = CHECK(this->getObj().rels(&Sec), this);
677 Target->FirstRelocation = Rels.begin();
678 Target->NumRelocations = Rels.size();
679 Target->AreRelocsRela = false;
681 assert(isUInt<31>(Target->NumRelocations));
683 // Relocation sections processed by the linker are usually removed
684 // from the output, so returning `nullptr` for the normal case.
685 // However, if -emit-relocs is given, we need to leave them in the output.
686 // (Some post link analysis tools need this information.)
687 if (Config->EmitRelocs) {
688 InputSection *RelocSec = make<InputSection>(*this, Sec, Name);
689 // We will not emit relocation section if target was discarded.
690 Target->DependentSections.push_back(RelocSec);
697 // The GNU linker uses .note.GNU-stack section as a marker indicating
698 // that the code in the object file does not expect that the stack is
699 // executable (in terms of NX bit). If all input files have the marker,
700 // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
701 // make the stack non-executable. Most object files have this section as
704 // But making the stack non-executable is a norm today for security
705 // reasons. Failure to do so may result in a serious security issue.
706 // Therefore, we make LLD always add PT_GNU_STACK unless it is
707 // explicitly told to do otherwise (by -z execstack). Because the stack
708 // executable-ness is controlled solely by command line options,
709 // .note.GNU-stack sections are simply ignored.
710 if (Name == ".note.GNU-stack")
711 return &InputSection::Discarded;
713 // Split stacks is a feature to support a discontiguous stack,
714 // commonly used in the programming language Go. For the details,
715 // see https://gcc.gnu.org/wiki/SplitStacks. An object file compiled
716 // for split stack will include a .note.GNU-split-stack section.
717 if (Name == ".note.GNU-split-stack") {
718 if (Config->Relocatable) {
719 error("cannot mix split-stack and non-split-stack in a relocatable link");
720 return &InputSection::Discarded;
722 this->SplitStack = true;
723 return &InputSection::Discarded;
726 // An object file cmpiled for split stack, but where some of the
727 // functions were compiled with the no_split_stack_attribute will
728 // include a .note.GNU-no-split-stack section.
729 if (Name == ".note.GNU-no-split-stack") {
730 this->SomeNoSplitStack = true;
731 return &InputSection::Discarded;
734 // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
735 // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
736 // sections. Drop those sections to avoid duplicate symbol errors.
737 // FIXME: This is glibc PR20543, we should remove this hack once that has been
738 // fixed for a while.
739 if (Name == ".gnu.linkonce.t.__x86.get_pc_thunk.bx" ||
740 Name == ".gnu.linkonce.t.__i686.get_pc_thunk.bx")
741 return &InputSection::Discarded;
743 // If we are creating a new .build-id section, strip existing .build-id
744 // sections so that the output won't have more than one .build-id.
745 // This is not usually a problem because input object files normally don't
746 // have .build-id sections, but you can create such files by
747 // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
748 if (Name == ".note.gnu.build-id" && Config->BuildId != BuildIdKind::None)
749 return &InputSection::Discarded;
751 // The linker merges EH (exception handling) frames and creates a
752 // .eh_frame_hdr section for runtime. So we handle them with a special
753 // class. For relocatable outputs, they are just passed through.
754 if (Name == ".eh_frame" && !Config->Relocatable)
755 return make<EhInputSection>(*this, Sec, Name);
757 if (shouldMerge(Sec))
758 return make<MergeInputSection>(*this, Sec, Name);
759 return make<InputSection>(*this, Sec, Name);
762 template <class ELFT>
763 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
764 return CHECK(this->getObj().getSectionName(&Sec, SectionStringTable), this);
767 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
768 this->Symbols.reserve(this->ELFSyms.size());
769 for (const Elf_Sym &Sym : this->ELFSyms)
770 this->Symbols.push_back(createSymbol(&Sym));
773 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) {
774 int Binding = Sym->getBinding();
776 uint32_t SecIdx = this->getSectionIndex(*Sym);
777 if (SecIdx >= this->Sections.size())
778 fatal(toString(this) + ": invalid section index: " + Twine(SecIdx));
780 InputSectionBase *Sec = this->Sections[SecIdx];
781 uint8_t StOther = Sym->st_other;
782 uint8_t Type = Sym->getType();
783 uint64_t Value = Sym->st_value;
784 uint64_t Size = Sym->st_size;
786 if (Binding == STB_LOCAL) {
787 if (Sym->getType() == STT_FILE)
788 SourceFile = CHECK(Sym->getName(this->StringTable), this);
790 if (this->StringTable.size() <= Sym->st_name)
791 fatal(toString(this) + ": invalid symbol name offset");
793 StringRefZ Name = this->StringTable.data() + Sym->st_name;
794 if (Sym->st_shndx == SHN_UNDEF)
795 return make<Undefined>(this, Name, Binding, StOther, Type);
797 return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec);
800 StringRef Name = CHECK(Sym->getName(this->StringTable), this);
802 switch (Sym->st_shndx) {
804 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
805 /*CanOmitFromDynSym=*/false, this);
807 if (Value == 0 || Value >= UINT32_MAX)
808 fatal(toString(this) + ": common symbol '" + Name +
809 "' has invalid alignment: " + Twine(Value));
810 return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, *this);
815 fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
819 if (Sec == &InputSection::Discarded)
820 return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
821 /*CanOmitFromDynSym=*/false, this);
822 return Symtab->addDefined(Name, StOther, Type, Value, Size, Binding, Sec,
827 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
828 : InputFile(ArchiveKind, File->getMemoryBufferRef()),
829 File(std::move(File)) {}
831 template <class ELFT> void ArchiveFile::parse() {
832 for (const Archive::Symbol &Sym : File->symbols())
833 Symtab->addLazyArchive<ELFT>(Sym.getName(), *this, Sym);
836 // Returns a buffer pointing to a member file containing a given symbol.
837 InputFile *ArchiveFile::fetch(const Archive::Symbol &Sym) {
839 CHECK(Sym.getMember(), toString(this) +
840 ": could not get the member for symbol " +
843 if (!Seen.insert(C.getChildOffset()).second)
847 CHECK(C.getMemoryBufferRef(),
849 ": could not get the buffer for the member defining symbol " +
852 if (Tar && C.getParent()->isThin())
853 Tar->append(relativeToRoot(CHECK(C.getFullName(), this)), MB.getBuffer());
855 InputFile *File = createObjectFile(
856 MB, getName(), C.getParent()->isThin() ? 0 : C.getChildOffset());
857 File->GroupId = GroupId;
861 template <class ELFT>
862 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
863 : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
864 IsNeeded(!Config->AsNeeded) {}
866 // Partially parse the shared object file so that we can call
867 // getSoName on this object.
868 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
869 const Elf_Shdr *DynamicSec = nullptr;
870 const ELFFile<ELFT> Obj = this->getObj();
871 ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
873 // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
874 for (const Elf_Shdr &Sec : Sections) {
875 switch (Sec.sh_type) {
879 this->initSymtab(Sections, &Sec);
884 case SHT_SYMTAB_SHNDX:
885 this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this);
888 this->VersymSec = &Sec;
891 this->VerdefSec = &Sec;
896 if (this->VersymSec && this->ELFSyms.empty())
897 error("SHT_GNU_versym should be associated with symbol table");
899 // Search for a DT_SONAME tag to initialize this->SoName.
902 ArrayRef<Elf_Dyn> Arr =
903 CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this);
904 for (const Elf_Dyn &Dyn : Arr) {
905 if (Dyn.d_tag == DT_SONAME) {
906 uint64_t Val = Dyn.getVal();
907 if (Val >= this->StringTable.size())
908 fatal(toString(this) + ": invalid DT_SONAME entry");
909 SoName = this->StringTable.data() + Val;
915 // Parses ".gnu.version" section which is a parallel array for the symbol table.
916 // If a given file doesn't have ".gnu.version" section, returns VER_NDX_GLOBAL.
917 template <class ELFT> std::vector<uint32_t> SharedFile<ELFT>::parseVersyms() {
918 size_t Size = this->ELFSyms.size() - this->FirstGlobal;
920 return std::vector<uint32_t>(Size, VER_NDX_GLOBAL);
922 const char *Base = this->MB.getBuffer().data();
923 const Elf_Versym *Versym =
924 reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
927 std::vector<uint32_t> Ret(Size);
928 for (size_t I = 0; I < Size; ++I)
929 Ret[I] = Versym[I].vs_index;
933 // Parse the version definitions in the object file if present. Returns a vector
934 // whose nth element contains a pointer to the Elf_Verdef for version identifier
935 // n. Version identifiers that are not definitions map to nullptr.
936 template <class ELFT>
937 std::vector<const typename ELFT::Verdef *> SharedFile<ELFT>::parseVerdefs() {
941 // We cannot determine the largest verdef identifier without inspecting
942 // every Elf_Verdef, but both bfd and gold assign verdef identifiers
943 // sequentially starting from 1, so we predict that the largest identifier
944 // will be VerdefCount.
945 unsigned VerdefCount = VerdefSec->sh_info;
946 std::vector<const Elf_Verdef *> Verdefs(VerdefCount + 1);
948 // Build the Verdefs array by following the chain of Elf_Verdef objects
949 // from the start of the .gnu.version_d section.
950 const char *Base = this->MB.getBuffer().data();
951 const char *Verdef = Base + VerdefSec->sh_offset;
952 for (unsigned I = 0; I != VerdefCount; ++I) {
953 auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
954 Verdef += CurVerdef->vd_next;
955 unsigned VerdefIndex = CurVerdef->vd_ndx;
956 Verdefs.resize(VerdefIndex + 1);
957 Verdefs[VerdefIndex] = CurVerdef;
963 // We do not usually care about alignments of data in shared object
964 // files because the loader takes care of it. However, if we promote a
965 // DSO symbol to point to .bss due to copy relocation, we need to keep
966 // the original alignment requirements. We infer it in this function.
967 template <class ELFT>
968 uint32_t SharedFile<ELFT>::getAlignment(ArrayRef<Elf_Shdr> Sections,
969 const Elf_Sym &Sym) {
970 uint64_t Ret = UINT64_MAX;
972 Ret = 1ULL << countTrailingZeros((uint64_t)Sym.st_value);
973 if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size())
974 Ret = std::min<uint64_t>(Ret, Sections[Sym.st_shndx].sh_addralign);
975 return (Ret > UINT32_MAX) ? 0 : Ret;
978 // Fully parse the shared object file. This must be called after parseSoName().
980 // This function parses symbol versions. If a DSO has version information,
981 // the file has a ".gnu.version_d" section which contains symbol version
982 // definitions. Each symbol is associated to one version through a table in
983 // ".gnu.version" section. That table is a parallel array for the symbol
984 // table, and each table entry contains an index in ".gnu.version_d".
986 // The special index 0 is reserved for VERF_NDX_LOCAL and 1 is for
987 // VER_NDX_GLOBAL. There's no table entry for these special versions in
990 // The file format for symbol versioning is perhaps a bit more complicated
991 // than necessary, but you can easily understand the code if you wrap your
992 // head around the data structure described above.
993 template <class ELFT> void SharedFile<ELFT>::parseRest() {
994 Verdefs = parseVerdefs(); // parse .gnu.version_d
995 std::vector<uint32_t> Versyms = parseVersyms(); // parse .gnu.version
996 ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this);
998 // System libraries can have a lot of symbols with versions. Using a
999 // fixed buffer for computing the versions name (foo@ver) can save a
1000 // lot of allocations.
1001 SmallString<0> VersionedNameBuffer;
1003 // Add symbols to the symbol table.
1004 ArrayRef<Elf_Sym> Syms = this->getGlobalELFSyms();
1005 for (size_t I = 0; I < Syms.size(); ++I) {
1006 const Elf_Sym &Sym = Syms[I];
1008 // ELF spec requires that all local symbols precede weak or global
1009 // symbols in each symbol table, and the index of first non-local symbol
1010 // is stored to sh_info. If a local symbol appears after some non-local
1011 // symbol, that's a violation of the spec.
1012 StringRef Name = CHECK(Sym.getName(this->StringTable), this);
1013 if (Sym.getBinding() == STB_LOCAL) {
1014 warn("found local symbol '" + Name +
1015 "' in global part of symbol table in file " + toString(this));
1019 if (Sym.isUndefined()) {
1020 Symbol *S = Symtab->addUndefined<ELFT>(Name, Sym.getBinding(),
1021 Sym.st_other, Sym.getType(),
1022 /*CanOmitFromDynSym=*/false, this);
1023 S->ExportDynamic = true;
1027 // MIPS BFD linker puts _gp_disp symbol into DSO files and incorrectly
1028 // assigns VER_NDX_LOCAL to this section global symbol. Here is a
1029 // workaround for this bug.
1030 uint32_t Idx = Versyms[I] & ~VERSYM_HIDDEN;
1031 if (Config->EMachine == EM_MIPS && Idx == VER_NDX_LOCAL &&
1035 uint64_t Alignment = getAlignment(Sections, Sym);
1036 if (!(Versyms[I] & VERSYM_HIDDEN))
1037 Symtab->addShared(Name, *this, Sym, Alignment, Idx);
1039 // Also add the symbol with the versioned name to handle undefined symbols
1040 // with explicit versions.
1041 if (Idx == VER_NDX_GLOBAL)
1044 if (Idx >= Verdefs.size() || Idx == VER_NDX_LOCAL) {
1045 error("corrupt input file: version definition index " + Twine(Idx) +
1046 " for symbol " + Name + " is out of bounds\n>>> defined in " +
1052 this->StringTable.data() + Verdefs[Idx]->getAux()->vda_name;
1053 VersionedNameBuffer.clear();
1054 Name = (Name + "@" + VerName).toStringRef(VersionedNameBuffer);
1055 Symtab->addShared(Saver.save(Name), *this, Sym, Alignment, Idx);
1059 static ELFKind getBitcodeELFKind(const Triple &T) {
1060 if (T.isLittleEndian())
1061 return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
1062 return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
1065 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
1066 switch (T.getArch()) {
1067 case Triple::aarch64:
1069 case Triple::amdgcn:
1078 case Triple::mipsel:
1079 case Triple::mips64:
1080 case Triple::mips64el:
1082 case Triple::msp430:
1087 case Triple::ppc64le:
1090 return T.isOSIAMCU() ? EM_IAMCU : EM_386;
1091 case Triple::x86_64:
1094 error(Path + ": could not infer e_machine from bitcode target triple " +
1100 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
1101 uint64_t OffsetInArchive)
1102 : InputFile(BitcodeKind, MB) {
1103 this->ArchiveName = ArchiveName;
1105 std::string Path = MB.getBufferIdentifier().str();
1106 if (Config->ThinLTOIndexOnly)
1107 Path = replaceThinLTOSuffix(MB.getBufferIdentifier());
1109 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1110 // name. If two archives define two members with the same name, this
1111 // causes a collision which result in only one of the objects being taken
1112 // into consideration at LTO time (which very likely causes undefined
1113 // symbols later in the link stage). So we append file offset to make
1115 MemoryBufferRef MBRef(
1117 Saver.save(ArchiveName + Path +
1118 (ArchiveName.empty() ? "" : utostr(OffsetInArchive))));
1120 Obj = CHECK(lto::InputFile::create(MBRef), this);
1122 Triple T(Obj->getTargetTriple());
1123 EKind = getBitcodeELFKind(T);
1124 EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
1127 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
1128 switch (GvVisibility) {
1129 case GlobalValue::DefaultVisibility:
1131 case GlobalValue::HiddenVisibility:
1133 case GlobalValue::ProtectedVisibility:
1134 return STV_PROTECTED;
1136 llvm_unreachable("unknown visibility");
1139 template <class ELFT>
1140 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
1141 const lto::InputFile::Symbol &ObjSym,
1143 StringRef Name = Saver.save(ObjSym.getName());
1144 uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
1146 uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
1147 uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
1148 bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
1150 int C = ObjSym.getComdatIndex();
1151 if (C != -1 && !KeptComdats[C])
1152 return Symtab->addUndefined<ELFT>(Name, Binding, Visibility, Type,
1153 CanOmitFromDynSym, &F);
1155 if (ObjSym.isUndefined())
1156 return Symtab->addUndefined<ELFT>(Name, Binding, Visibility, Type,
1157 CanOmitFromDynSym, &F);
1159 if (ObjSym.isCommon())
1160 return Symtab->addCommon(Name, ObjSym.getCommonSize(),
1161 ObjSym.getCommonAlignment(), Binding, Visibility,
1164 return Symtab->addBitcode(Name, Binding, Visibility, Type, CanOmitFromDynSym,
1168 template <class ELFT>
1169 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
1170 std::vector<bool> KeptComdats;
1171 for (StringRef S : Obj->getComdatTable())
1172 KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
1174 for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
1175 Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this));
1178 static ELFKind getELFKind(MemoryBufferRef MB) {
1180 unsigned char Endian;
1181 std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
1183 if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
1184 fatal(MB.getBufferIdentifier() + ": invalid data encoding");
1185 if (Size != ELFCLASS32 && Size != ELFCLASS64)
1186 fatal(MB.getBufferIdentifier() + ": invalid file class");
1188 size_t BufSize = MB.getBuffer().size();
1189 if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
1190 (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
1191 fatal(MB.getBufferIdentifier() + ": file is too short");
1193 if (Size == ELFCLASS32)
1194 return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
1195 return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
1198 void BinaryFile::parse() {
1199 ArrayRef<uint8_t> Data = arrayRefFromStringRef(MB.getBuffer());
1200 auto *Section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1202 Sections.push_back(Section);
1204 // For each input file foo that is embedded to a result as a binary
1205 // blob, we define _binary_foo_{start,end,size} symbols, so that
1206 // user programs can access blobs by name. Non-alphanumeric
1207 // characters in a filename are replaced with underscore.
1208 std::string S = "_binary_" + MB.getBufferIdentifier().str();
1209 for (size_t I = 0; I < S.size(); ++I)
1213 Symtab->addDefined(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 0, 0,
1214 STB_GLOBAL, Section, nullptr);
1215 Symtab->addDefined(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
1216 Data.size(), 0, STB_GLOBAL, Section, nullptr);
1217 Symtab->addDefined(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
1218 Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
1221 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
1222 uint64_t OffsetInArchive) {
1224 return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
1226 switch (getELFKind(MB)) {
1228 return make<ObjFile<ELF32LE>>(MB, ArchiveName);
1230 return make<ObjFile<ELF32BE>>(MB, ArchiveName);
1232 return make<ObjFile<ELF64LE>>(MB, ArchiveName);
1234 return make<ObjFile<ELF64BE>>(MB, ArchiveName);
1236 llvm_unreachable("getELFKind");
1240 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
1241 switch (getELFKind(MB)) {
1243 return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
1245 return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
1247 return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
1249 return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
1251 llvm_unreachable("getELFKind");
1255 MemoryBufferRef LazyObjFile::getBuffer() {
1257 return MemoryBufferRef();
1262 InputFile *LazyObjFile::fetch() {
1263 MemoryBufferRef MBRef = getBuffer();
1264 if (MBRef.getBuffer().empty())
1267 InputFile *File = createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1268 File->GroupId = GroupId;
1272 template <class ELFT> void LazyObjFile::parse() {
1273 // A lazy object file wraps either a bitcode file or an ELF file.
1274 if (isBitcode(this->MB)) {
1275 std::unique_ptr<lto::InputFile> Obj =
1276 CHECK(lto::InputFile::create(this->MB), this);
1277 for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1278 if (!Sym.isUndefined())
1279 Symtab->addLazyObject<ELFT>(Saver.save(Sym.getName()), *this);
1283 if (getELFKind(this->MB) != Config->EKind) {
1284 error("incompatible file: " + this->MB.getBufferIdentifier());
1288 ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(MB.getBuffer()));
1289 ArrayRef<typename ELFT::Shdr> Sections = CHECK(Obj.sections(), this);
1291 for (const typename ELFT::Shdr &Sec : Sections) {
1292 if (Sec.sh_type != SHT_SYMTAB)
1295 typename ELFT::SymRange Syms = CHECK(Obj.symbols(&Sec), this);
1296 uint32_t FirstGlobal = Sec.sh_info;
1297 StringRef StringTable =
1298 CHECK(Obj.getStringTableForSymtab(Sec, Sections), this);
1300 for (const typename ELFT::Sym &Sym : Syms.slice(FirstGlobal))
1301 if (Sym.st_shndx != SHN_UNDEF)
1302 Symtab->addLazyObject<ELFT>(CHECK(Sym.getName(StringTable), this),
1308 std::string elf::replaceThinLTOSuffix(StringRef Path) {
1309 StringRef Suffix = Config->ThinLTOObjectSuffixReplace.first;
1310 StringRef Repl = Config->ThinLTOObjectSuffixReplace.second;
1312 if (Path.consume_back(Suffix))
1313 return (Path + Repl).str();
1317 template void ArchiveFile::parse<ELF32LE>();
1318 template void ArchiveFile::parse<ELF32BE>();
1319 template void ArchiveFile::parse<ELF64LE>();
1320 template void ArchiveFile::parse<ELF64BE>();
1322 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1323 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1324 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1325 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1327 template void LazyObjFile::parse<ELF32LE>();
1328 template void LazyObjFile::parse<ELF32BE>();
1329 template void LazyObjFile::parse<ELF64LE>();
1330 template void LazyObjFile::parse<ELF64BE>();
1332 template class elf::ELFFileBase<ELF32LE>;
1333 template class elf::ELFFileBase<ELF32BE>;
1334 template class elf::ELFFileBase<ELF64LE>;
1335 template class elf::ELFFileBase<ELF64BE>;
1337 template class elf::ObjFile<ELF32LE>;
1338 template class elf::ObjFile<ELF32BE>;
1339 template class elf::ObjFile<ELF64LE>;
1340 template class elf::ObjFile<ELF64BE>;
1342 template class elf::SharedFile<ELF32LE>;
1343 template class elf::SharedFile<ELF32BE>;
1344 template class elf::SharedFile<ELF64LE>;
1345 template class elf::SharedFile<ELF64BE>;