1 //===- InputFiles.cpp -----------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "InputFiles.h"
11 #include "InputSection.h"
12 #include "LinkerScript.h"
13 #include "SymbolTable.h"
14 #include "Symbols.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"
31 
32 using namespace llvm;
33 using namespace llvm::ELF;
34 using namespace llvm::object;
35 using namespace llvm::sys;
36 using namespace llvm::sys::fs;
37 
38 using namespace lld;
39 using namespace lld::elf;
40 
41 std::vector<BinaryFile *> elf::BinaryFiles;
42 std::vector<BitcodeFile *> elf::BitcodeFiles;
43 std::vector<InputFile *> elf::ObjectFiles;
44 std::vector<InputFile *> elf::SharedFiles;
45 
46 TarWriter *elf::Tar;
47 
48 InputFile::InputFile(Kind K, MemoryBufferRef M) : MB(M), FileKind(K) {}
49 
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);
55 
56   log(Path);
57 
58   auto MBOrErr = MemoryBuffer::getFile(Path);
59   if (auto EC = MBOrErr.getError()) {
60     error("cannot open " + Path + ": " + EC.message());
61     return None;
62   }
63 
64   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
65   MemoryBufferRef MBRef = MB->getMemBufferRef();
66   make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
67 
68   if (Tar)
69     Tar->append(relativeToRoot(Path), MBRef.getBuffer());
70   return MBRef;
71 }
72 
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);
77   if (Filename == Path)
78     return Filename + Lineno;
79   return Filename + Lineno + " (" + Path.str() + Lineno + ")";
80 }
81 
82 template <class ELFT>
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);
89 
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);
94 
95   // File.SourceFile contains STT_FILE symbol, and that is a last resort.
96   return File.SourceFile;
97 }
98 
99 std::string InputFile::getSrcMsg(const Symbol &Sym, InputSectionBase &Sec,
100                                  uint64_t Offset) {
101   if (kind() != ObjKind)
102     return "";
103   switch (Config->EKind) {
104   default:
105     llvm_unreachable("Invalid kind");
106   case ELF32LEKind:
107     return getSrcMsgAux(cast<ObjFile<ELF32LE>>(*this), Sym, Sec, Offset);
108   case ELF32BEKind:
109     return getSrcMsgAux(cast<ObjFile<ELF32BE>>(*this), Sym, Sec, Offset);
110   case ELF64LEKind:
111     return getSrcMsgAux(cast<ObjFile<ELF64LE>>(*this), Sym, Sec, Offset);
112   case ELF64BEKind:
113     return getSrcMsgAux(cast<ObjFile<ELF64BE>>(*this), Sym, Sec, Offset);
114   }
115 }
116 
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,
122                               Config->Wordsize);
123 
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   const DWARFDebugLine::LineTable *LT =
128       DwarfLine->getOrParseLineTable(LineData, 0, Dwarf, nullptr);
129 
130   // Return if there is no debug information about CU available.
131   if (!Dwarf.getNumCompileUnits())
132     return;
133 
134   // Loop over variable records and insert them to VariableLoc.
135   DWARFCompileUnit *CU = Dwarf.getCompileUnitAtIndex(0);
136   for (const auto &Entry : CU->dies()) {
137     DWARFDie Die(CU, &Entry);
138     // Skip all tags that are not variables.
139     if (Die.getTag() != dwarf::DW_TAG_variable)
140       continue;
141 
142     // Skip if a local variable because we don't need them for generating error
143     // messages. In general, only non-local symbols can fail to be linked.
144     if (!dwarf::toUnsigned(Die.find(dwarf::DW_AT_external), 0))
145       continue;
146 
147     // Get the source filename index for the variable.
148     unsigned File = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_file), 0);
149     if (!LT->hasFileAtIndex(File))
150       continue;
151 
152     // Get the line number on which the variable is declared.
153     unsigned Line = dwarf::toUnsigned(Die.find(dwarf::DW_AT_decl_line), 0);
154 
155     // Get the name of the variable and add the collected information to
156     // VariableLoc. Usually Name is non-empty, but it can be empty if the input
157     // object file lacks some debug info.
158     StringRef Name = dwarf::toString(Die.find(dwarf::DW_AT_name), "");
159     if (!Name.empty())
160       VariableLoc.insert({Name, {File, Line}});
161   }
162 }
163 
164 // Returns the pair of file name and line number describing location of data
165 // object (variable, array, etc) definition.
166 template <class ELFT>
167 Optional<std::pair<std::string, unsigned>>
168 ObjFile<ELFT>::getVariableLoc(StringRef Name) {
169   llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
170 
171   // There is always only one CU so it's offset is 0.
172   const DWARFDebugLine::LineTable *LT = DwarfLine->getLineTable(0);
173   if (!LT)
174     return None;
175 
176   // Return if we have no debug information about data object.
177   auto It = VariableLoc.find(Name);
178   if (It == VariableLoc.end())
179     return None;
180 
181   // Take file name string from line table.
182   std::string FileName;
183   if (!LT->getFileNameByIndex(
184           It->second.first /* File */, nullptr,
185           DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FileName))
186     return None;
187 
188   return std::make_pair(FileName, It->second.second /*Line*/);
189 }
190 
191 // Returns source line information for a given offset
192 // using DWARF debug info.
193 template <class ELFT>
194 Optional<DILineInfo> ObjFile<ELFT>::getDILineInfo(InputSectionBase *S,
195                                                   uint64_t Offset) {
196   llvm::call_once(InitDwarfLine, [this]() { initializeDwarf(); });
197 
198   // The offset to CU is 0.
199   const DWARFDebugLine::LineTable *Tbl = DwarfLine->getLineTable(0);
200   if (!Tbl)
201     return None;
202 
203   // Use fake address calcuated by adding section file offset and offset in
204   // section. See comments for ObjectInfo class.
205   DILineInfo Info;
206   Tbl->getFileLineInfoForAddress(
207       S->getOffsetInFile() + Offset, nullptr,
208       DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info);
209   if (Info.Line == 0)
210     return None;
211   return Info;
212 }
213 
214 // Returns source line information for a given offset
215 // using DWARF debug info.
216 template <class ELFT>
217 std::string ObjFile<ELFT>::getLineInfo(InputSectionBase *S, uint64_t Offset) {
218   if (Optional<DILineInfo> Info = getDILineInfo(S, Offset))
219     return Info->FileName + ":" + std::to_string(Info->Line);
220   return "";
221 }
222 
223 // Returns "<internal>", "foo.a(bar.o)" or "baz.o".
224 std::string lld::toString(const InputFile *F) {
225   if (!F)
226     return "<internal>";
227 
228   if (F->ToStringCache.empty()) {
229     if (F->ArchiveName.empty())
230       F->ToStringCache = F->getName();
231     else
232       F->ToStringCache = (F->ArchiveName + "(" + F->getName() + ")").str();
233   }
234   return F->ToStringCache;
235 }
236 
237 template <class ELFT>
238 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
239   if (ELFT::TargetEndianness == support::little)
240     EKind = ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
241   else
242     EKind = ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
243 
244   EMachine = getObj().getHeader()->e_machine;
245   OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
246 }
247 
248 template <class ELFT>
249 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalELFSyms() {
250   return makeArrayRef(ELFSyms.begin() + FirstNonLocal, ELFSyms.end());
251 }
252 
253 template <class ELFT>
254 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
255   return CHECK(getObj().getSectionIndex(&Sym, ELFSyms, SymtabSHNDX), this);
256 }
257 
258 template <class ELFT>
259 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
260                                    const Elf_Shdr *Symtab) {
261   FirstNonLocal = Symtab->sh_info;
262   ELFSyms = CHECK(getObj().symbols(Symtab), this);
263   if (FirstNonLocal == 0 || FirstNonLocal > ELFSyms.size())
264     fatal(toString(this) + ": invalid sh_info in symbol table");
265 
266   StringTable =
267       CHECK(getObj().getStringTableForSymtab(*Symtab, Sections), this);
268 }
269 
270 template <class ELFT>
271 ObjFile<ELFT>::ObjFile(MemoryBufferRef M, StringRef ArchiveName)
272     : ELFFileBase<ELFT>(Base::ObjKind, M) {
273   this->ArchiveName = ArchiveName;
274 }
275 
276 template <class ELFT> ArrayRef<Symbol *> ObjFile<ELFT>::getLocalSymbols() {
277   if (this->Symbols.empty())
278     return {};
279   return makeArrayRef(this->Symbols).slice(1, this->FirstNonLocal - 1);
280 }
281 
282 template <class ELFT>
283 void ObjFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
284   // Read section and symbol tables.
285   initializeSections(ComdatGroups);
286   initializeSymbols();
287 }
288 
289 // Sections with SHT_GROUP and comdat bits define comdat section groups.
290 // They are identified and deduplicated by group name. This function
291 // returns a group name.
292 template <class ELFT>
293 StringRef ObjFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
294                                               const Elf_Shdr &Sec) {
295   // Group signatures are stored as symbol names in object files.
296   // sh_info contains a symbol index, so we fetch a symbol and read its name.
297   if (this->ELFSyms.empty())
298     this->initSymtab(
299         Sections, CHECK(object::getSection<ELFT>(Sections, Sec.sh_link), this));
300 
301   const Elf_Sym *Sym =
302       CHECK(object::getSymbol<ELFT>(this->ELFSyms, Sec.sh_info), this);
303   StringRef Signature = CHECK(Sym->getName(this->StringTable), this);
304 
305   // As a special case, if a symbol is a section symbol and has no name,
306   // we use a section name as a signature.
307   //
308   // Such SHT_GROUP sections are invalid from the perspective of the ELF
309   // standard, but GNU gold 1.14 (the neweset version as of July 2017) or
310   // older produce such sections as outputs for the -r option, so we need
311   // a bug-compatibility.
312   if (Signature.empty() && Sym->getType() == STT_SECTION)
313     return getSectionName(Sec);
314   return Signature;
315 }
316 
317 template <class ELFT>
318 ArrayRef<typename ObjFile<ELFT>::Elf_Word>
319 ObjFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
320   const ELFFile<ELFT> &Obj = this->getObj();
321   ArrayRef<Elf_Word> Entries =
322       CHECK(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec), this);
323   if (Entries.empty() || Entries[0] != GRP_COMDAT)
324     fatal(toString(this) + ": unsupported SHT_GROUP format");
325   return Entries.slice(1);
326 }
327 
328 template <class ELFT> bool ObjFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
329   // We don't merge sections if -O0 (default is -O1). This makes sometimes
330   // the linker significantly faster, although the output will be bigger.
331   if (Config->Optimize == 0)
332     return false;
333 
334   // A mergeable section with size 0 is useless because they don't have
335   // any data to merge. A mergeable string section with size 0 can be
336   // argued as invalid because it doesn't end with a null character.
337   // We'll avoid a mess by handling them as if they were non-mergeable.
338   if (Sec.sh_size == 0)
339     return false;
340 
341   // Check for sh_entsize. The ELF spec is not clear about the zero
342   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
343   // the section does not hold a table of fixed-size entries". We know
344   // that Rust 1.13 produces a string mergeable section with a zero
345   // sh_entsize. Here we just accept it rather than being picky about it.
346   uint64_t EntSize = Sec.sh_entsize;
347   if (EntSize == 0)
348     return false;
349   if (Sec.sh_size % EntSize)
350     fatal(toString(this) +
351           ": SHF_MERGE section size must be a multiple of sh_entsize");
352 
353   uint64_t Flags = Sec.sh_flags;
354   if (!(Flags & SHF_MERGE))
355     return false;
356   if (Flags & SHF_WRITE)
357     fatal(toString(this) + ": writable SHF_MERGE section is not supported");
358 
359   return true;
360 }
361 
362 template <class ELFT>
363 void ObjFile<ELFT>::initializeSections(
364     DenseSet<CachedHashStringRef> &ComdatGroups) {
365   const ELFFile<ELFT> &Obj = this->getObj();
366 
367   ArrayRef<Elf_Shdr> ObjSections = CHECK(this->getObj().sections(), this);
368   uint64_t Size = ObjSections.size();
369   this->Sections.resize(Size);
370   this->SectionStringTable =
371       CHECK(Obj.getSectionStringTable(ObjSections), this);
372 
373   for (size_t I = 0, E = ObjSections.size(); I < E; I++) {
374     if (this->Sections[I] == &InputSection::Discarded)
375       continue;
376     const Elf_Shdr &Sec = ObjSections[I];
377 
378     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
379     // if -r is given, we'll let the final link discard such sections.
380     // This is compatible with GNU.
381     if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
382       this->Sections[I] = &InputSection::Discarded;
383       continue;
384     }
385 
386     switch (Sec.sh_type) {
387     case SHT_GROUP: {
388       // De-duplicate section groups by their signatures.
389       StringRef Signature = getShtGroupSignature(ObjSections, Sec);
390       bool IsNew = ComdatGroups.insert(CachedHashStringRef(Signature)).second;
391       this->Sections[I] = &InputSection::Discarded;
392 
393       // If it is a new section group, we want to keep group members.
394       // Group leader sections, which contain indices of group members, are
395       // discarded because they are useless beyond this point. The only
396       // exception is the -r option because in order to produce re-linkable
397       // object files, we want to pass through basically everything.
398       if (IsNew) {
399         if (Config->Relocatable)
400           this->Sections[I] = createInputSection(Sec);
401         continue;
402       }
403 
404       // Otherwise, discard group members.
405       for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
406         if (SecIndex >= Size)
407           fatal(toString(this) +
408                 ": invalid section index in group: " + Twine(SecIndex));
409         this->Sections[SecIndex] = &InputSection::Discarded;
410       }
411       break;
412     }
413     case SHT_SYMTAB:
414       this->initSymtab(ObjSections, &Sec);
415       break;
416     case SHT_SYMTAB_SHNDX:
417       this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, ObjSections), this);
418       break;
419     case SHT_STRTAB:
420     case SHT_NULL:
421       break;
422     default:
423       this->Sections[I] = createInputSection(Sec);
424     }
425 
426     // .ARM.exidx sections have a reverse dependency on the InputSection they
427     // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
428     if (Sec.sh_flags & SHF_LINK_ORDER) {
429       if (Sec.sh_link >= this->Sections.size())
430         fatal(toString(this) +
431               ": invalid sh_link index: " + Twine(Sec.sh_link));
432       this->Sections[Sec.sh_link]->DependentSections.push_back(
433           cast<InputSection>(this->Sections[I]));
434     }
435   }
436 }
437 
438 // The ARM support in lld makes some use of instructions that are not available
439 // on all ARM architectures. Namely:
440 // - Use of BLX instruction for interworking between ARM and Thumb state.
441 // - Use of the extended Thumb branch encoding in relocation.
442 // - Use of the MOVT/MOVW instructions in Thumb Thunks.
443 // The ARM Attributes section contains information about the architecture chosen
444 // at compile time. We follow the convention that if at least one input object
445 // is compiled with an architecture that supports these features then lld is
446 // permitted to use them.
447 static void updateSupportedARMFeatures(const ARMAttributeParser &Attributes) {
448   if (!Attributes.hasAttribute(ARMBuildAttrs::CPU_arch))
449     return;
450   auto Arch = Attributes.getAttributeValue(ARMBuildAttrs::CPU_arch);
451   switch (Arch) {
452   case ARMBuildAttrs::Pre_v4:
453   case ARMBuildAttrs::v4:
454   case ARMBuildAttrs::v4T:
455     // Architectures prior to v5 do not support BLX instruction
456     break;
457   case ARMBuildAttrs::v5T:
458   case ARMBuildAttrs::v5TE:
459   case ARMBuildAttrs::v5TEJ:
460   case ARMBuildAttrs::v6:
461   case ARMBuildAttrs::v6KZ:
462   case ARMBuildAttrs::v6K:
463     Config->ARMHasBlx = true;
464     // Architectures used in pre-Cortex processors do not support
465     // The J1 = 1 J2 = 1 Thumb branch range extension, with the exception
466     // of Architecture v6T2 (arm1156t2-s and arm1156t2f-s) that do.
467     break;
468   default:
469     // All other Architectures have BLX and extended branch encoding
470     Config->ARMHasBlx = true;
471     Config->ARMJ1J2BranchEncoding = true;
472     if (Arch != ARMBuildAttrs::v6_M && Arch != ARMBuildAttrs::v6S_M)
473       // All Architectures used in Cortex processors with the exception
474       // of v6-M and v6S-M have the MOVT and MOVW instructions.
475       Config->ARMHasMovtMovw = true;
476     break;
477   }
478 }
479 
480 template <class ELFT>
481 InputSectionBase *ObjFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
482   uint32_t Idx = Sec.sh_info;
483   if (Idx >= this->Sections.size())
484     fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
485   InputSectionBase *Target = this->Sections[Idx];
486 
487   // Strictly speaking, a relocation section must be included in the
488   // group of the section it relocates. However, LLVM 3.3 and earlier
489   // would fail to do so, so we gracefully handle that case.
490   if (Target == &InputSection::Discarded)
491     return nullptr;
492 
493   if (!Target)
494     fatal(toString(this) + ": unsupported relocation reference");
495   return Target;
496 }
497 
498 // Create a regular InputSection class that has the same contents
499 // as a given section.
500 static InputSection *toRegularSection(MergeInputSection *Sec) {
501   return make<InputSection>(Sec->File, Sec->Flags, Sec->Type, Sec->Alignment,
502                             Sec->Data, Sec->Name);
503 }
504 
505 template <class ELFT>
506 InputSectionBase *ObjFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
507   StringRef Name = getSectionName(Sec);
508 
509   switch (Sec.sh_type) {
510   case SHT_ARM_ATTRIBUTES: {
511     if (Config->EMachine != EM_ARM)
512       break;
513     ARMAttributeParser Attributes;
514     ArrayRef<uint8_t> Contents = check(this->getObj().getSectionContents(&Sec));
515     Attributes.Parse(Contents, /*isLittle*/ Config->EKind == ELF32LEKind);
516     updateSupportedARMFeatures(Attributes);
517     // FIXME: Retain the first attribute section we see. The eglibc ARM
518     // dynamic loaders require the presence of an attribute section for dlopen
519     // to work. In a full implementation we would merge all attribute sections.
520     if (InX::ARMAttributes == nullptr) {
521       InX::ARMAttributes = make<InputSection>(*this, Sec, Name);
522       return InX::ARMAttributes;
523     }
524     return &InputSection::Discarded;
525   }
526   case SHT_RELA:
527   case SHT_REL: {
528     // Find the relocation target section and associate this
529     // section with it. Target can be discarded, for example
530     // if it is a duplicated member of SHT_GROUP section, we
531     // do not create or proccess relocatable sections then.
532     InputSectionBase *Target = getRelocTarget(Sec);
533     if (!Target)
534       return nullptr;
535 
536     // This section contains relocation information.
537     // If -r is given, we do not interpret or apply relocation
538     // but just copy relocation sections to output.
539     if (Config->Relocatable)
540       return make<InputSection>(*this, Sec, Name);
541 
542     if (Target->FirstRelocation)
543       fatal(toString(this) +
544             ": multiple relocation sections to one section are not supported");
545 
546     // Mergeable sections with relocations are tricky because relocations
547     // need to be taken into account when comparing section contents for
548     // merging. It's not worth supporting such mergeable sections because
549     // they are rare and it'd complicates the internal design (we usually
550     // have to determine if two sections are mergeable early in the link
551     // process much before applying relocations). We simply handle mergeable
552     // sections with relocations as non-mergeable.
553     if (auto *MS = dyn_cast<MergeInputSection>(Target)) {
554       Target = toRegularSection(MS);
555       this->Sections[Sec.sh_info] = Target;
556     }
557 
558     size_t NumRelocations;
559     if (Sec.sh_type == SHT_RELA) {
560       ArrayRef<Elf_Rela> Rels = CHECK(this->getObj().relas(&Sec), this);
561       Target->FirstRelocation = Rels.begin();
562       NumRelocations = Rels.size();
563       Target->AreRelocsRela = true;
564     } else {
565       ArrayRef<Elf_Rel> Rels = CHECK(this->getObj().rels(&Sec), this);
566       Target->FirstRelocation = Rels.begin();
567       NumRelocations = Rels.size();
568       Target->AreRelocsRela = false;
569     }
570     assert(isUInt<31>(NumRelocations));
571     Target->NumRelocations = NumRelocations;
572 
573     // Relocation sections processed by the linker are usually removed
574     // from the output, so returning `nullptr` for the normal case.
575     // However, if -emit-relocs is given, we need to leave them in the output.
576     // (Some post link analysis tools need this information.)
577     if (Config->EmitRelocs) {
578       InputSection *RelocSec = make<InputSection>(*this, Sec, Name);
579       // We will not emit relocation section if target was discarded.
580       Target->DependentSections.push_back(RelocSec);
581       return RelocSec;
582     }
583     return nullptr;
584   }
585   }
586 
587   // The GNU linker uses .note.GNU-stack section as a marker indicating
588   // that the code in the object file does not expect that the stack is
589   // executable (in terms of NX bit). If all input files have the marker,
590   // the GNU linker adds a PT_GNU_STACK segment to tells the loader to
591   // make the stack non-executable. Most object files have this section as
592   // of 2017.
593   //
594   // But making the stack non-executable is a norm today for security
595   // reasons. Failure to do so may result in a serious security issue.
596   // Therefore, we make LLD always add PT_GNU_STACK unless it is
597   // explicitly told to do otherwise (by -z execstack). Because the stack
598   // executable-ness is controlled solely by command line options,
599   // .note.GNU-stack sections are simply ignored.
600   if (Name == ".note.GNU-stack")
601     return &InputSection::Discarded;
602 
603   // Split stacks is a feature to support a discontiguous stack. At least
604   // as of 2017, it seems that the feature is not being used widely.
605   // Only GNU gold supports that. We don't. For the details about that,
606   // see https://gcc.gnu.org/wiki/SplitStacks
607   if (Name == ".note.GNU-split-stack") {
608     error(toString(this) +
609           ": object file compiled with -fsplit-stack is not supported");
610     return &InputSection::Discarded;
611   }
612 
613   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
614   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
615   // sections. Drop those sections to avoid duplicate symbol errors.
616   // FIXME: This is glibc PR20543, we should remove this hack once that has been
617   // fixed for a while.
618   if (Name.startswith(".gnu.linkonce."))
619     return &InputSection::Discarded;
620 
621   // If we are creating a new .build-id section, strip existing .build-id
622   // sections so that the output won't have more than one .build-id.
623   // This is not usually a problem because input object files normally don't
624   // have .build-id sections, but you can create such files by
625   // "ld.{bfd,gold,lld} -r --build-id", and we want to guard against it.
626   if (Name == ".note.gnu.build-id" && Config->BuildId != BuildIdKind::None)
627     return &InputSection::Discarded;
628 
629   // The linker merges EH (exception handling) frames and creates a
630   // .eh_frame_hdr section for runtime. So we handle them with a special
631   // class. For relocatable outputs, they are just passed through.
632   if (Name == ".eh_frame" && !Config->Relocatable)
633     return make<EhInputSection>(*this, Sec, Name);
634 
635   if (shouldMerge(Sec))
636     return make<MergeInputSection>(*this, Sec, Name);
637   return make<InputSection>(*this, Sec, Name);
638 }
639 
640 template <class ELFT>
641 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
642   return CHECK(this->getObj().getSectionName(&Sec, SectionStringTable), this);
643 }
644 
645 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
646   this->Symbols.reserve(this->ELFSyms.size());
647   for (const Elf_Sym &Sym : this->ELFSyms)
648     this->Symbols.push_back(createSymbol(&Sym));
649 }
650 
651 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) {
652   int Binding = Sym->getBinding();
653 
654   uint32_t SecIdx = this->getSectionIndex(*Sym);
655   if (SecIdx >= this->Sections.size())
656     fatal(toString(this) + ": invalid section index: " + Twine(SecIdx));
657 
658   InputSectionBase *Sec = this->Sections[SecIdx];
659   uint8_t StOther = Sym->st_other;
660   uint8_t Type = Sym->getType();
661   uint64_t Value = Sym->st_value;
662   uint64_t Size = Sym->st_size;
663 
664   if (Binding == STB_LOCAL) {
665     if (Sym->getType() == STT_FILE)
666       SourceFile = CHECK(Sym->getName(this->StringTable), this);
667 
668     if (this->StringTable.size() <= Sym->st_name)
669       fatal(toString(this) + ": invalid symbol name offset");
670 
671     StringRefZ Name = this->StringTable.data() + Sym->st_name;
672     if (Sym->st_shndx == SHN_UNDEF)
673       return make<Undefined>(this, Name, Binding, StOther, Type);
674 
675     return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec);
676   }
677 
678   StringRef Name = CHECK(Sym->getName(this->StringTable), this);
679 
680   switch (Sym->st_shndx) {
681   case SHN_UNDEF:
682     return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
683                                       /*CanOmitFromDynSym=*/false, this);
684   case SHN_COMMON:
685     if (Value == 0 || Value >= UINT32_MAX)
686       fatal(toString(this) + ": common symbol '" + Name +
687             "' has invalid alignment: " + Twine(Value));
688     return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, *this);
689   }
690 
691   switch (Binding) {
692   default:
693     fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
694   case STB_GLOBAL:
695   case STB_WEAK:
696   case STB_GNU_UNIQUE:
697     if (Sec == &InputSection::Discarded)
698       return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
699                                         /*CanOmitFromDynSym=*/false, this);
700     return Symtab->addRegular(Name, StOther, Type, Value, Size, Binding, Sec,
701                               this);
702   }
703 }
704 
705 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
706     : InputFile(ArchiveKind, File->getMemoryBufferRef()),
707       File(std::move(File)) {}
708 
709 template <class ELFT> void ArchiveFile::parse() {
710   Symbols.reserve(File->getNumberOfSymbols());
711   for (const Archive::Symbol &Sym : File->symbols())
712     Symbols.push_back(Symtab->addLazyArchive<ELFT>(Sym.getName(), *this, Sym));
713 }
714 
715 // Returns a buffer pointing to a member file containing a given symbol.
716 std::pair<MemoryBufferRef, uint64_t>
717 ArchiveFile::getMember(const Archive::Symbol *Sym) {
718   Archive::Child C =
719       CHECK(Sym->getMember(), toString(this) +
720                                   ": could not get the member for symbol " +
721                                   Sym->getName());
722 
723   if (!Seen.insert(C.getChildOffset()).second)
724     return {MemoryBufferRef(), 0};
725 
726   MemoryBufferRef Ret =
727       CHECK(C.getMemoryBufferRef(),
728             toString(this) +
729                 ": could not get the buffer for the member defining symbol " +
730                 Sym->getName());
731 
732   if (C.getParent()->isThin() && Tar)
733     Tar->append(relativeToRoot(CHECK(C.getFullName(), this)), Ret.getBuffer());
734   if (C.getParent()->isThin())
735     return {Ret, 0};
736   return {Ret, C.getChildOffset()};
737 }
738 
739 template <class ELFT>
740 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
741     : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
742       IsNeeded(!Config->AsNeeded) {}
743 
744 // Partially parse the shared object file so that we can call
745 // getSoName on this object.
746 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
747   const Elf_Shdr *DynamicSec = nullptr;
748   const ELFFile<ELFT> Obj = this->getObj();
749   ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
750 
751   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
752   for (const Elf_Shdr &Sec : Sections) {
753     switch (Sec.sh_type) {
754     default:
755       continue;
756     case SHT_DYNSYM:
757       this->initSymtab(Sections, &Sec);
758       break;
759     case SHT_DYNAMIC:
760       DynamicSec = &Sec;
761       break;
762     case SHT_SYMTAB_SHNDX:
763       this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this);
764       break;
765     case SHT_GNU_versym:
766       this->VersymSec = &Sec;
767       break;
768     case SHT_GNU_verdef:
769       this->VerdefSec = &Sec;
770       break;
771     }
772   }
773 
774   if (this->VersymSec && this->ELFSyms.empty())
775     error("SHT_GNU_versym should be associated with symbol table");
776 
777   // Search for a DT_SONAME tag to initialize this->SoName.
778   if (!DynamicSec)
779     return;
780   ArrayRef<Elf_Dyn> Arr =
781       CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this);
782   for (const Elf_Dyn &Dyn : Arr) {
783     if (Dyn.d_tag == DT_SONAME) {
784       uint64_t Val = Dyn.getVal();
785       if (Val >= this->StringTable.size())
786         fatal(toString(this) + ": invalid DT_SONAME entry");
787       SoName = this->StringTable.data() + Val;
788       return;
789     }
790   }
791 }
792 
793 // Parse the version definitions in the object file if present. Returns a vector
794 // whose nth element contains a pointer to the Elf_Verdef for version identifier
795 // n. Version identifiers that are not definitions map to nullptr. The array
796 // always has at least length 1.
797 template <class ELFT>
798 std::vector<const typename ELFT::Verdef *>
799 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
800   std::vector<const Elf_Verdef *> Verdefs(1);
801   // We only need to process symbol versions for this DSO if it has both a
802   // versym and a verdef section, which indicates that the DSO contains symbol
803   // version definitions.
804   if (!VersymSec || !VerdefSec)
805     return Verdefs;
806 
807   // The location of the first global versym entry.
808   const char *Base = this->MB.getBuffer().data();
809   Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
810            this->FirstNonLocal;
811 
812   // We cannot determine the largest verdef identifier without inspecting
813   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
814   // sequentially starting from 1, so we predict that the largest identifier
815   // will be VerdefCount.
816   unsigned VerdefCount = VerdefSec->sh_info;
817   Verdefs.resize(VerdefCount + 1);
818 
819   // Build the Verdefs array by following the chain of Elf_Verdef objects
820   // from the start of the .gnu.version_d section.
821   const char *Verdef = Base + VerdefSec->sh_offset;
822   for (unsigned I = 0; I != VerdefCount; ++I) {
823     auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
824     Verdef += CurVerdef->vd_next;
825     unsigned VerdefIndex = CurVerdef->vd_ndx;
826     if (Verdefs.size() <= VerdefIndex)
827       Verdefs.resize(VerdefIndex + 1);
828     Verdefs[VerdefIndex] = CurVerdef;
829   }
830 
831   return Verdefs;
832 }
833 
834 // Fully parse the shared object file. This must be called after parseSoName().
835 template <class ELFT> void SharedFile<ELFT>::parseRest() {
836   // Create mapping from version identifiers to Elf_Verdef entries.
837   const Elf_Versym *Versym = nullptr;
838   Verdefs = parseVerdefs(Versym);
839 
840   ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this);
841 
842   // Add symbols to the symbol table.
843   Elf_Sym_Range Syms = this->getGlobalELFSyms();
844   for (const Elf_Sym &Sym : Syms) {
845     unsigned VersymIndex = VER_NDX_GLOBAL;
846     if (Versym) {
847       VersymIndex = Versym->vs_index;
848       ++Versym;
849     }
850     bool Hidden = VersymIndex & VERSYM_HIDDEN;
851     VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
852 
853     StringRef Name = CHECK(Sym.getName(this->StringTable), this);
854     if (Sym.isUndefined()) {
855       Undefs.push_back(Name);
856       continue;
857     }
858 
859     if (Sym.getBinding() == STB_LOCAL) {
860       warn("found local symbol '" + Name +
861            "' in global part of symbol table in file " + toString(this));
862       continue;
863     }
864 
865     if (Config->EMachine == EM_MIPS) {
866       // FIXME: MIPS BFD linker puts _gp_disp symbol into DSO files
867       // and incorrectly assigns VER_NDX_LOCAL to this section global
868       // symbol. Here is a workaround for this bug.
869       if (Versym && VersymIndex == VER_NDX_LOCAL && Name == "_gp_disp")
870         continue;
871     }
872 
873     const Elf_Verdef *Ver = nullptr;
874     if (VersymIndex != VER_NDX_GLOBAL) {
875       if (VersymIndex >= Verdefs.size() || VersymIndex == VER_NDX_LOCAL) {
876         error("corrupt input file: version definition index " +
877               Twine(VersymIndex) + " for symbol " + Name +
878               " is out of bounds\n>>> defined in " + toString(this));
879         continue;
880       }
881       Ver = Verdefs[VersymIndex];
882     } else {
883       VersymIndex = 0;
884     }
885 
886     // We do not usually care about alignments of data in shared object
887     // files because the loader takes care of it. However, if we promote a
888     // DSO symbol to point to .bss due to copy relocation, we need to keep
889     // the original alignment requirements. We infer it here.
890     uint64_t Alignment = 1;
891     if (Sym.st_value)
892       Alignment = 1ULL << countTrailingZeros((uint64_t)Sym.st_value);
893     if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) {
894       uint64_t SecAlign = Sections[Sym.st_shndx].sh_addralign;
895       Alignment = std::min(Alignment, SecAlign);
896     }
897     if (Alignment > UINT32_MAX)
898       error(toString(this) + ": alignment too large: " + Name);
899 
900     if (!Hidden)
901       Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
902 
903     // Also add the symbol with the versioned name to handle undefined symbols
904     // with explicit versions.
905     if (Ver) {
906       StringRef VerName = this->StringTable.data() + Ver->getAux()->vda_name;
907       Name = Saver.save(Name + "@" + VerName);
908       Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
909     }
910   }
911 }
912 
913 static ELFKind getBitcodeELFKind(const Triple &T) {
914   if (T.isLittleEndian())
915     return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
916   return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
917 }
918 
919 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
920   switch (T.getArch()) {
921   case Triple::aarch64:
922     return EM_AARCH64;
923   case Triple::arm:
924   case Triple::thumb:
925     return EM_ARM;
926   case Triple::avr:
927     return EM_AVR;
928   case Triple::mips:
929   case Triple::mipsel:
930   case Triple::mips64:
931   case Triple::mips64el:
932     return EM_MIPS;
933   case Triple::ppc:
934     return EM_PPC;
935   case Triple::ppc64:
936     return EM_PPC64;
937   case Triple::x86:
938     return T.isOSIAMCU() ? EM_IAMCU : EM_386;
939   case Triple::x86_64:
940     return EM_X86_64;
941   default:
942     fatal(Path + ": could not infer e_machine from bitcode target triple " +
943           T.str());
944   }
945 }
946 
947 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
948                          uint64_t OffsetInArchive)
949     : InputFile(BitcodeKind, MB) {
950   this->ArchiveName = ArchiveName;
951 
952   // Here we pass a new MemoryBufferRef which is identified by ArchiveName
953   // (the fully resolved path of the archive) + member name + offset of the
954   // member in the archive.
955   // ThinLTO uses the MemoryBufferRef identifier to access its internal
956   // data structures and if two archives define two members with the same name,
957   // this causes a collision which result in only one of the objects being
958   // taken into consideration at LTO time (which very likely causes undefined
959   // symbols later in the link stage).
960   MemoryBufferRef MBRef(MB.getBuffer(),
961                         Saver.save(ArchiveName + MB.getBufferIdentifier() +
962                                    utostr(OffsetInArchive)));
963   Obj = CHECK(lto::InputFile::create(MBRef), this);
964 
965   Triple T(Obj->getTargetTriple());
966   EKind = getBitcodeELFKind(T);
967   EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
968 }
969 
970 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
971   switch (GvVisibility) {
972   case GlobalValue::DefaultVisibility:
973     return STV_DEFAULT;
974   case GlobalValue::HiddenVisibility:
975     return STV_HIDDEN;
976   case GlobalValue::ProtectedVisibility:
977     return STV_PROTECTED;
978   }
979   llvm_unreachable("unknown visibility");
980 }
981 
982 template <class ELFT>
983 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
984                                    const lto::InputFile::Symbol &ObjSym,
985                                    BitcodeFile &F) {
986   StringRef NameRef = Saver.save(ObjSym.getName());
987   uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
988 
989   uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
990   uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
991   bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
992 
993   int C = ObjSym.getComdatIndex();
994   if (C != -1 && !KeptComdats[C])
995     return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
996                                       CanOmitFromDynSym, &F);
997 
998   if (ObjSym.isUndefined())
999     return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
1000                                       CanOmitFromDynSym, &F);
1001 
1002   if (ObjSym.isCommon())
1003     return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
1004                              ObjSym.getCommonAlignment(), Binding, Visibility,
1005                              STT_OBJECT, F);
1006 
1007   return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
1008                             CanOmitFromDynSym, F);
1009 }
1010 
1011 template <class ELFT>
1012 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
1013   std::vector<bool> KeptComdats;
1014   for (StringRef S : Obj->getComdatTable())
1015     KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
1016 
1017   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
1018     Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this));
1019 }
1020 
1021 static ELFKind getELFKind(MemoryBufferRef MB) {
1022   unsigned char Size;
1023   unsigned char Endian;
1024   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
1025 
1026   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
1027     fatal(MB.getBufferIdentifier() + ": invalid data encoding");
1028   if (Size != ELFCLASS32 && Size != ELFCLASS64)
1029     fatal(MB.getBufferIdentifier() + ": invalid file class");
1030 
1031   size_t BufSize = MB.getBuffer().size();
1032   if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
1033       (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
1034     fatal(MB.getBufferIdentifier() + ": file is too short");
1035 
1036   if (Size == ELFCLASS32)
1037     return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
1038   return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
1039 }
1040 
1041 void BinaryFile::parse() {
1042   ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
1043   auto *Section = make<InputSection>(this, SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
1044                                      8, Data, ".data");
1045   Sections.push_back(Section);
1046 
1047   // For each input file foo that is embedded to a result as a binary
1048   // blob, we define _binary_foo_{start,end,size} symbols, so that
1049   // user programs can access blobs by name. Non-alphanumeric
1050   // characters in a filename are replaced with underscore.
1051   std::string S = "_binary_" + MB.getBufferIdentifier().str();
1052   for (size_t I = 0; I < S.size(); ++I)
1053     if (!isAlnum(S[I]))
1054       S[I] = '_';
1055 
1056   Symtab->addRegular(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 0, 0,
1057                      STB_GLOBAL, Section, nullptr);
1058   Symtab->addRegular(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
1059                      Data.size(), 0, STB_GLOBAL, Section, nullptr);
1060   Symtab->addRegular(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
1061                      Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
1062 }
1063 
1064 static bool isBitcode(MemoryBufferRef MB) {
1065   using namespace sys::fs;
1066   return identify_magic(MB.getBuffer()) == file_magic::bitcode;
1067 }
1068 
1069 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
1070                                  uint64_t OffsetInArchive) {
1071   if (isBitcode(MB))
1072     return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
1073 
1074   switch (getELFKind(MB)) {
1075   case ELF32LEKind:
1076     return make<ObjFile<ELF32LE>>(MB, ArchiveName);
1077   case ELF32BEKind:
1078     return make<ObjFile<ELF32BE>>(MB, ArchiveName);
1079   case ELF64LEKind:
1080     return make<ObjFile<ELF64LE>>(MB, ArchiveName);
1081   case ELF64BEKind:
1082     return make<ObjFile<ELF64BE>>(MB, ArchiveName);
1083   default:
1084     llvm_unreachable("getELFKind");
1085   }
1086 }
1087 
1088 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
1089   switch (getELFKind(MB)) {
1090   case ELF32LEKind:
1091     return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
1092   case ELF32BEKind:
1093     return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
1094   case ELF64LEKind:
1095     return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
1096   case ELF64BEKind:
1097     return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
1098   default:
1099     llvm_unreachable("getELFKind");
1100   }
1101 }
1102 
1103 MemoryBufferRef LazyObjFile::getBuffer() {
1104   if (Seen)
1105     return MemoryBufferRef();
1106   Seen = true;
1107   return MB;
1108 }
1109 
1110 InputFile *LazyObjFile::fetch() {
1111   MemoryBufferRef MBRef = getBuffer();
1112   if (MBRef.getBuffer().empty())
1113     return nullptr;
1114   return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1115 }
1116 
1117 template <class ELFT> void LazyObjFile::parse() {
1118   for (StringRef Sym : getSymbolNames())
1119     Symtab->addLazyObject<ELFT>(Sym, *this);
1120 }
1121 
1122 template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
1123   typedef typename ELFT::Shdr Elf_Shdr;
1124   typedef typename ELFT::Sym Elf_Sym;
1125   typedef typename ELFT::SymRange Elf_Sym_Range;
1126 
1127   ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(this->MB.getBuffer()));
1128   ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
1129   for (const Elf_Shdr &Sec : Sections) {
1130     if (Sec.sh_type != SHT_SYMTAB)
1131       continue;
1132 
1133     Elf_Sym_Range Syms = CHECK(Obj.symbols(&Sec), this);
1134     uint32_t FirstNonLocal = Sec.sh_info;
1135     StringRef StringTable =
1136         CHECK(Obj.getStringTableForSymtab(Sec, Sections), this);
1137     std::vector<StringRef> V;
1138 
1139     for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1140       if (Sym.st_shndx != SHN_UNDEF)
1141         V.push_back(CHECK(Sym.getName(StringTable), this));
1142     return V;
1143   }
1144   return {};
1145 }
1146 
1147 std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1148   std::unique_ptr<lto::InputFile> Obj =
1149       CHECK(lto::InputFile::create(this->MB), this);
1150   std::vector<StringRef> V;
1151   for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1152     if (!Sym.isUndefined())
1153       V.push_back(Saver.save(Sym.getName()));
1154   return V;
1155 }
1156 
1157 // Returns a vector of globally-visible defined symbol names.
1158 std::vector<StringRef> LazyObjFile::getSymbolNames() {
1159   if (isBitcode(this->MB))
1160     return getBitcodeSymbols();
1161 
1162   switch (getELFKind(this->MB)) {
1163   case ELF32LEKind:
1164     return getElfSymbols<ELF32LE>();
1165   case ELF32BEKind:
1166     return getElfSymbols<ELF32BE>();
1167   case ELF64LEKind:
1168     return getElfSymbols<ELF64LE>();
1169   case ELF64BEKind:
1170     return getElfSymbols<ELF64BE>();
1171   default:
1172     llvm_unreachable("getELFKind");
1173   }
1174 }
1175 
1176 template void ArchiveFile::parse<ELF32LE>();
1177 template void ArchiveFile::parse<ELF32BE>();
1178 template void ArchiveFile::parse<ELF64LE>();
1179 template void ArchiveFile::parse<ELF64BE>();
1180 
1181 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1182 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1183 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1184 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1185 
1186 template void LazyObjFile::parse<ELF32LE>();
1187 template void LazyObjFile::parse<ELF32BE>();
1188 template void LazyObjFile::parse<ELF64LE>();
1189 template void LazyObjFile::parse<ELF64BE>();
1190 
1191 template class elf::ELFFileBase<ELF32LE>;
1192 template class elf::ELFFileBase<ELF32BE>;
1193 template class elf::ELFFileBase<ELF64LE>;
1194 template class elf::ELFFileBase<ELF64BE>;
1195 
1196 template class elf::ObjFile<ELF32LE>;
1197 template class elf::ObjFile<ELF32BE>;
1198 template class elf::ObjFile<ELF64LE>;
1199 template class elf::ObjFile<ELF64BE>;
1200 
1201 template class elf::SharedFile<ELF32LE>;
1202 template class elf::SharedFile<ELF32BE>;
1203 template class elf::SharedFile<ELF64LE>;
1204 template class elf::SharedFile<ELF64BE>;
1205