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   // The linker merges EH (exception handling) frames and creates a
622   // .eh_frame_hdr section for runtime. So we handle them with a special
623   // class. For relocatable outputs, they are just passed through.
624   if (Name == ".eh_frame" && !Config->Relocatable)
625     return make<EhInputSection>(*this, Sec, Name);
626 
627   if (shouldMerge(Sec))
628     return make<MergeInputSection>(*this, Sec, Name);
629   return make<InputSection>(*this, Sec, Name);
630 }
631 
632 template <class ELFT>
633 StringRef ObjFile<ELFT>::getSectionName(const Elf_Shdr &Sec) {
634   return CHECK(this->getObj().getSectionName(&Sec, SectionStringTable), this);
635 }
636 
637 template <class ELFT> void ObjFile<ELFT>::initializeSymbols() {
638   this->Symbols.reserve(this->ELFSyms.size());
639   for (const Elf_Sym &Sym : this->ELFSyms)
640     this->Symbols.push_back(createSymbol(&Sym));
641 }
642 
643 template <class ELFT> Symbol *ObjFile<ELFT>::createSymbol(const Elf_Sym *Sym) {
644   int Binding = Sym->getBinding();
645 
646   uint32_t SecIdx = this->getSectionIndex(*Sym);
647   if (SecIdx >= this->Sections.size())
648     fatal(toString(this) + ": invalid section index: " + Twine(SecIdx));
649 
650   InputSectionBase *Sec = this->Sections[SecIdx];
651   uint8_t StOther = Sym->st_other;
652   uint8_t Type = Sym->getType();
653   uint64_t Value = Sym->st_value;
654   uint64_t Size = Sym->st_size;
655 
656   if (Binding == STB_LOCAL) {
657     if (Sym->getType() == STT_FILE)
658       SourceFile = CHECK(Sym->getName(this->StringTable), this);
659 
660     if (this->StringTable.size() <= Sym->st_name)
661       fatal(toString(this) + ": invalid symbol name offset");
662 
663     StringRefZ Name = this->StringTable.data() + Sym->st_name;
664     if (Sym->st_shndx == SHN_UNDEF)
665       return make<Undefined>(this, Name, Binding, StOther, Type);
666 
667     return make<Defined>(this, Name, Binding, StOther, Type, Value, Size, Sec);
668   }
669 
670   StringRef Name = CHECK(Sym->getName(this->StringTable), this);
671 
672   switch (Sym->st_shndx) {
673   case SHN_UNDEF:
674     return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
675                                       /*CanOmitFromDynSym=*/false, this);
676   case SHN_COMMON:
677     if (Value == 0 || Value >= UINT32_MAX)
678       fatal(toString(this) + ": common symbol '" + Name +
679             "' has invalid alignment: " + Twine(Value));
680     return Symtab->addCommon(Name, Size, Value, Binding, StOther, Type, *this);
681   }
682 
683   switch (Binding) {
684   default:
685     fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
686   case STB_GLOBAL:
687   case STB_WEAK:
688   case STB_GNU_UNIQUE:
689     if (Sec == &InputSection::Discarded)
690       return Symtab->addUndefined<ELFT>(Name, Binding, StOther, Type,
691                                         /*CanOmitFromDynSym=*/false, this);
692     return Symtab->addRegular(Name, StOther, Type, Value, Size, Binding, Sec,
693                               this);
694   }
695 }
696 
697 ArchiveFile::ArchiveFile(std::unique_ptr<Archive> &&File)
698     : InputFile(ArchiveKind, File->getMemoryBufferRef()),
699       File(std::move(File)) {}
700 
701 template <class ELFT> void ArchiveFile::parse() {
702   Symbols.reserve(File->getNumberOfSymbols());
703   for (const Archive::Symbol &Sym : File->symbols())
704     Symbols.push_back(Symtab->addLazyArchive<ELFT>(Sym.getName(), *this, Sym));
705 }
706 
707 // Returns a buffer pointing to a member file containing a given symbol.
708 std::pair<MemoryBufferRef, uint64_t>
709 ArchiveFile::getMember(const Archive::Symbol *Sym) {
710   Archive::Child C =
711       CHECK(Sym->getMember(), toString(this) +
712                                   ": could not get the member for symbol " +
713                                   Sym->getName());
714 
715   if (!Seen.insert(C.getChildOffset()).second)
716     return {MemoryBufferRef(), 0};
717 
718   MemoryBufferRef Ret =
719       CHECK(C.getMemoryBufferRef(),
720             toString(this) +
721                 ": could not get the buffer for the member defining symbol " +
722                 Sym->getName());
723 
724   if (C.getParent()->isThin() && Tar)
725     Tar->append(relativeToRoot(CHECK(C.getFullName(), this)), Ret.getBuffer());
726   if (C.getParent()->isThin())
727     return {Ret, 0};
728   return {Ret, C.getChildOffset()};
729 }
730 
731 template <class ELFT>
732 SharedFile<ELFT>::SharedFile(MemoryBufferRef M, StringRef DefaultSoName)
733     : ELFFileBase<ELFT>(Base::SharedKind, M), SoName(DefaultSoName),
734       IsNeeded(!Config->AsNeeded) {}
735 
736 // Partially parse the shared object file so that we can call
737 // getSoName on this object.
738 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
739   const Elf_Shdr *DynamicSec = nullptr;
740   const ELFFile<ELFT> Obj = this->getObj();
741   ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
742 
743   // Search for .dynsym, .dynamic, .symtab, .gnu.version and .gnu.version_d.
744   for (const Elf_Shdr &Sec : Sections) {
745     switch (Sec.sh_type) {
746     default:
747       continue;
748     case SHT_DYNSYM:
749       this->initSymtab(Sections, &Sec);
750       break;
751     case SHT_DYNAMIC:
752       DynamicSec = &Sec;
753       break;
754     case SHT_SYMTAB_SHNDX:
755       this->SymtabSHNDX = CHECK(Obj.getSHNDXTable(Sec, Sections), this);
756       break;
757     case SHT_GNU_versym:
758       this->VersymSec = &Sec;
759       break;
760     case SHT_GNU_verdef:
761       this->VerdefSec = &Sec;
762       break;
763     }
764   }
765 
766   if (this->VersymSec && this->ELFSyms.empty())
767     error("SHT_GNU_versym should be associated with symbol table");
768 
769   // Search for a DT_SONAME tag to initialize this->SoName.
770   if (!DynamicSec)
771     return;
772   ArrayRef<Elf_Dyn> Arr =
773       CHECK(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec), this);
774   for (const Elf_Dyn &Dyn : Arr) {
775     if (Dyn.d_tag == DT_SONAME) {
776       uint64_t Val = Dyn.getVal();
777       if (Val >= this->StringTable.size())
778         fatal(toString(this) + ": invalid DT_SONAME entry");
779       SoName = this->StringTable.data() + Val;
780       return;
781     }
782   }
783 }
784 
785 // Parse the version definitions in the object file if present. Returns a vector
786 // whose nth element contains a pointer to the Elf_Verdef for version identifier
787 // n. Version identifiers that are not definitions map to nullptr. The array
788 // always has at least length 1.
789 template <class ELFT>
790 std::vector<const typename ELFT::Verdef *>
791 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
792   std::vector<const Elf_Verdef *> Verdefs(1);
793   // We only need to process symbol versions for this DSO if it has both a
794   // versym and a verdef section, which indicates that the DSO contains symbol
795   // version definitions.
796   if (!VersymSec || !VerdefSec)
797     return Verdefs;
798 
799   // The location of the first global versym entry.
800   const char *Base = this->MB.getBuffer().data();
801   Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
802            this->FirstNonLocal;
803 
804   // We cannot determine the largest verdef identifier without inspecting
805   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
806   // sequentially starting from 1, so we predict that the largest identifier
807   // will be VerdefCount.
808   unsigned VerdefCount = VerdefSec->sh_info;
809   Verdefs.resize(VerdefCount + 1);
810 
811   // Build the Verdefs array by following the chain of Elf_Verdef objects
812   // from the start of the .gnu.version_d section.
813   const char *Verdef = Base + VerdefSec->sh_offset;
814   for (unsigned I = 0; I != VerdefCount; ++I) {
815     auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
816     Verdef += CurVerdef->vd_next;
817     unsigned VerdefIndex = CurVerdef->vd_ndx;
818     if (Verdefs.size() <= VerdefIndex)
819       Verdefs.resize(VerdefIndex + 1);
820     Verdefs[VerdefIndex] = CurVerdef;
821   }
822 
823   return Verdefs;
824 }
825 
826 // Fully parse the shared object file. This must be called after parseSoName().
827 template <class ELFT> void SharedFile<ELFT>::parseRest() {
828   // Create mapping from version identifiers to Elf_Verdef entries.
829   const Elf_Versym *Versym = nullptr;
830   Verdefs = parseVerdefs(Versym);
831 
832   ArrayRef<Elf_Shdr> Sections = CHECK(this->getObj().sections(), this);
833 
834   // Add symbols to the symbol table.
835   Elf_Sym_Range Syms = this->getGlobalELFSyms();
836   for (const Elf_Sym &Sym : Syms) {
837     unsigned VersymIndex = VER_NDX_GLOBAL;
838     if (Versym) {
839       VersymIndex = Versym->vs_index;
840       ++Versym;
841     }
842     bool Hidden = VersymIndex & VERSYM_HIDDEN;
843     VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
844 
845     StringRef Name = CHECK(Sym.getName(this->StringTable), this);
846     if (Sym.isUndefined()) {
847       Undefs.push_back(Name);
848       continue;
849     }
850 
851     if (Sym.getBinding() == STB_LOCAL) {
852       warn("found local symbol '" + Name +
853            "' in global part of symbol table in file " + toString(this));
854       continue;
855     }
856 
857     const Elf_Verdef *Ver = nullptr;
858     if (VersymIndex != VER_NDX_GLOBAL) {
859       if (VersymIndex >= Verdefs.size() || VersymIndex == VER_NDX_LOCAL) {
860         error("corrupt input file: version definition index " +
861               Twine(VersymIndex) + " for symbol " + Name +
862               " is out of bounds\n>>> defined in " + toString(this));
863         continue;
864       }
865       Ver = Verdefs[VersymIndex];
866     } else {
867       VersymIndex = 0;
868     }
869 
870     // We do not usually care about alignments of data in shared object
871     // files because the loader takes care of it. However, if we promote a
872     // DSO symbol to point to .bss due to copy relocation, we need to keep
873     // the original alignment requirements. We infer it here.
874     uint64_t Alignment = 1;
875     if (Sym.st_value)
876       Alignment = 1ULL << countTrailingZeros((uint64_t)Sym.st_value);
877     if (0 < Sym.st_shndx && Sym.st_shndx < Sections.size()) {
878       uint64_t SecAlign = Sections[Sym.st_shndx].sh_addralign;
879       Alignment = std::min(Alignment, SecAlign);
880     }
881     if (Alignment > UINT32_MAX)
882       error(toString(this) + ": alignment too large: " + Name);
883 
884     if (!Hidden)
885       Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
886 
887     // Also add the symbol with the versioned name to handle undefined symbols
888     // with explicit versions.
889     if (Ver) {
890       StringRef VerName = this->StringTable.data() + Ver->getAux()->vda_name;
891       Name = Saver.save(Name + "@" + VerName);
892       Symtab->addShared(Name, *this, Sym, Alignment, VersymIndex);
893     }
894   }
895 }
896 
897 static ELFKind getBitcodeELFKind(const Triple &T) {
898   if (T.isLittleEndian())
899     return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
900   return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
901 }
902 
903 static uint8_t getBitcodeMachineKind(StringRef Path, const Triple &T) {
904   switch (T.getArch()) {
905   case Triple::aarch64:
906     return EM_AARCH64;
907   case Triple::arm:
908   case Triple::thumb:
909     return EM_ARM;
910   case Triple::avr:
911     return EM_AVR;
912   case Triple::mips:
913   case Triple::mipsel:
914   case Triple::mips64:
915   case Triple::mips64el:
916     return EM_MIPS;
917   case Triple::ppc:
918     return EM_PPC;
919   case Triple::ppc64:
920     return EM_PPC64;
921   case Triple::x86:
922     return T.isOSIAMCU() ? EM_IAMCU : EM_386;
923   case Triple::x86_64:
924     return EM_X86_64;
925   default:
926     fatal(Path + ": could not infer e_machine from bitcode target triple " +
927           T.str());
928   }
929 }
930 
931 BitcodeFile::BitcodeFile(MemoryBufferRef MB, StringRef ArchiveName,
932                          uint64_t OffsetInArchive)
933     : InputFile(BitcodeKind, MB) {
934   this->ArchiveName = ArchiveName;
935 
936   // Here we pass a new MemoryBufferRef which is identified by ArchiveName
937   // (the fully resolved path of the archive) + member name + offset of the
938   // member in the archive.
939   // ThinLTO uses the MemoryBufferRef identifier to access its internal
940   // data structures and if two archives define two members with the same name,
941   // this causes a collision which result in only one of the objects being
942   // taken into consideration at LTO time (which very likely causes undefined
943   // symbols later in the link stage).
944   MemoryBufferRef MBRef(MB.getBuffer(),
945                         Saver.save(ArchiveName + MB.getBufferIdentifier() +
946                                    utostr(OffsetInArchive)));
947   Obj = CHECK(lto::InputFile::create(MBRef), this);
948 
949   Triple T(Obj->getTargetTriple());
950   EKind = getBitcodeELFKind(T);
951   EMachine = getBitcodeMachineKind(MB.getBufferIdentifier(), T);
952 }
953 
954 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
955   switch (GvVisibility) {
956   case GlobalValue::DefaultVisibility:
957     return STV_DEFAULT;
958   case GlobalValue::HiddenVisibility:
959     return STV_HIDDEN;
960   case GlobalValue::ProtectedVisibility:
961     return STV_PROTECTED;
962   }
963   llvm_unreachable("unknown visibility");
964 }
965 
966 template <class ELFT>
967 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
968                                    const lto::InputFile::Symbol &ObjSym,
969                                    BitcodeFile &F) {
970   StringRef NameRef = Saver.save(ObjSym.getName());
971   uint32_t Binding = ObjSym.isWeak() ? STB_WEAK : STB_GLOBAL;
972 
973   uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
974   uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
975   bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
976 
977   int C = ObjSym.getComdatIndex();
978   if (C != -1 && !KeptComdats[C])
979     return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
980                                       CanOmitFromDynSym, &F);
981 
982   if (ObjSym.isUndefined())
983     return Symtab->addUndefined<ELFT>(NameRef, Binding, Visibility, Type,
984                                       CanOmitFromDynSym, &F);
985 
986   if (ObjSym.isCommon())
987     return Symtab->addCommon(NameRef, ObjSym.getCommonSize(),
988                              ObjSym.getCommonAlignment(), Binding, Visibility,
989                              STT_OBJECT, F);
990 
991   return Symtab->addBitcode(NameRef, Binding, Visibility, Type,
992                             CanOmitFromDynSym, F);
993 }
994 
995 template <class ELFT>
996 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
997   std::vector<bool> KeptComdats;
998   for (StringRef S : Obj->getComdatTable())
999     KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(S)).second);
1000 
1001   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
1002     Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, *this));
1003 }
1004 
1005 static ELFKind getELFKind(MemoryBufferRef MB) {
1006   unsigned char Size;
1007   unsigned char Endian;
1008   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
1009 
1010   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
1011     fatal(MB.getBufferIdentifier() + ": invalid data encoding");
1012   if (Size != ELFCLASS32 && Size != ELFCLASS64)
1013     fatal(MB.getBufferIdentifier() + ": invalid file class");
1014 
1015   size_t BufSize = MB.getBuffer().size();
1016   if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
1017       (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
1018     fatal(MB.getBufferIdentifier() + ": file is too short");
1019 
1020   if (Size == ELFCLASS32)
1021     return (Endian == ELFDATA2LSB) ? ELF32LEKind : ELF32BEKind;
1022   return (Endian == ELFDATA2LSB) ? ELF64LEKind : ELF64BEKind;
1023 }
1024 
1025 void BinaryFile::parse() {
1026   ArrayRef<uint8_t> Data = toArrayRef(MB.getBuffer());
1027   auto *Section = make<InputSection>(nullptr, SHF_ALLOC | SHF_WRITE,
1028                                      SHT_PROGBITS, 8, Data, ".data");
1029   Sections.push_back(Section);
1030 
1031   // For each input file foo that is embedded to a result as a binary
1032   // blob, we define _binary_foo_{start,end,size} symbols, so that
1033   // user programs can access blobs by name. Non-alphanumeric
1034   // characters in a filename are replaced with underscore.
1035   std::string S = "_binary_" + MB.getBufferIdentifier().str();
1036   for (size_t I = 0; I < S.size(); ++I)
1037     if (!isAlnum(S[I]))
1038       S[I] = '_';
1039 
1040   Symtab->addRegular(Saver.save(S + "_start"), STV_DEFAULT, STT_OBJECT, 0, 0,
1041                      STB_GLOBAL, Section, nullptr);
1042   Symtab->addRegular(Saver.save(S + "_end"), STV_DEFAULT, STT_OBJECT,
1043                      Data.size(), 0, STB_GLOBAL, Section, nullptr);
1044   Symtab->addRegular(Saver.save(S + "_size"), STV_DEFAULT, STT_OBJECT,
1045                      Data.size(), 0, STB_GLOBAL, nullptr, nullptr);
1046 }
1047 
1048 static bool isBitcode(MemoryBufferRef MB) {
1049   using namespace sys::fs;
1050   return identify_magic(MB.getBuffer()) == file_magic::bitcode;
1051 }
1052 
1053 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
1054                                  uint64_t OffsetInArchive) {
1055   if (isBitcode(MB))
1056     return make<BitcodeFile>(MB, ArchiveName, OffsetInArchive);
1057 
1058   switch (getELFKind(MB)) {
1059   case ELF32LEKind:
1060     return make<ObjFile<ELF32LE>>(MB, ArchiveName);
1061   case ELF32BEKind:
1062     return make<ObjFile<ELF32BE>>(MB, ArchiveName);
1063   case ELF64LEKind:
1064     return make<ObjFile<ELF64LE>>(MB, ArchiveName);
1065   case ELF64BEKind:
1066     return make<ObjFile<ELF64BE>>(MB, ArchiveName);
1067   default:
1068     llvm_unreachable("getELFKind");
1069   }
1070 }
1071 
1072 InputFile *elf::createSharedFile(MemoryBufferRef MB, StringRef DefaultSoName) {
1073   switch (getELFKind(MB)) {
1074   case ELF32LEKind:
1075     return make<SharedFile<ELF32LE>>(MB, DefaultSoName);
1076   case ELF32BEKind:
1077     return make<SharedFile<ELF32BE>>(MB, DefaultSoName);
1078   case ELF64LEKind:
1079     return make<SharedFile<ELF64LE>>(MB, DefaultSoName);
1080   case ELF64BEKind:
1081     return make<SharedFile<ELF64BE>>(MB, DefaultSoName);
1082   default:
1083     llvm_unreachable("getELFKind");
1084   }
1085 }
1086 
1087 MemoryBufferRef LazyObjFile::getBuffer() {
1088   if (Seen)
1089     return MemoryBufferRef();
1090   Seen = true;
1091   return MB;
1092 }
1093 
1094 InputFile *LazyObjFile::fetch() {
1095   MemoryBufferRef MBRef = getBuffer();
1096   if (MBRef.getBuffer().empty())
1097     return nullptr;
1098   return createObjectFile(MBRef, ArchiveName, OffsetInArchive);
1099 }
1100 
1101 template <class ELFT> void LazyObjFile::parse() {
1102   for (StringRef Sym : getSymbolNames())
1103     Symtab->addLazyObject<ELFT>(Sym, *this);
1104 }
1105 
1106 template <class ELFT> std::vector<StringRef> LazyObjFile::getElfSymbols() {
1107   typedef typename ELFT::Shdr Elf_Shdr;
1108   typedef typename ELFT::Sym Elf_Sym;
1109   typedef typename ELFT::SymRange Elf_Sym_Range;
1110 
1111   ELFFile<ELFT> Obj = check(ELFFile<ELFT>::create(this->MB.getBuffer()));
1112   ArrayRef<Elf_Shdr> Sections = CHECK(Obj.sections(), this);
1113   for (const Elf_Shdr &Sec : Sections) {
1114     if (Sec.sh_type != SHT_SYMTAB)
1115       continue;
1116 
1117     Elf_Sym_Range Syms = CHECK(Obj.symbols(&Sec), this);
1118     uint32_t FirstNonLocal = Sec.sh_info;
1119     StringRef StringTable =
1120         CHECK(Obj.getStringTableForSymtab(Sec, Sections), this);
1121     std::vector<StringRef> V;
1122 
1123     for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
1124       if (Sym.st_shndx != SHN_UNDEF)
1125         V.push_back(CHECK(Sym.getName(StringTable), this));
1126     return V;
1127   }
1128   return {};
1129 }
1130 
1131 std::vector<StringRef> LazyObjFile::getBitcodeSymbols() {
1132   std::unique_ptr<lto::InputFile> Obj =
1133       CHECK(lto::InputFile::create(this->MB), this);
1134   std::vector<StringRef> V;
1135   for (const lto::InputFile::Symbol &Sym : Obj->symbols())
1136     if (!Sym.isUndefined())
1137       V.push_back(Saver.save(Sym.getName()));
1138   return V;
1139 }
1140 
1141 // Returns a vector of globally-visible defined symbol names.
1142 std::vector<StringRef> LazyObjFile::getSymbolNames() {
1143   if (isBitcode(this->MB))
1144     return getBitcodeSymbols();
1145 
1146   switch (getELFKind(this->MB)) {
1147   case ELF32LEKind:
1148     return getElfSymbols<ELF32LE>();
1149   case ELF32BEKind:
1150     return getElfSymbols<ELF32BE>();
1151   case ELF64LEKind:
1152     return getElfSymbols<ELF64LE>();
1153   case ELF64BEKind:
1154     return getElfSymbols<ELF64BE>();
1155   default:
1156     llvm_unreachable("getELFKind");
1157   }
1158 }
1159 
1160 template void ArchiveFile::parse<ELF32LE>();
1161 template void ArchiveFile::parse<ELF32BE>();
1162 template void ArchiveFile::parse<ELF64LE>();
1163 template void ArchiveFile::parse<ELF64BE>();
1164 
1165 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
1166 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
1167 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
1168 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
1169 
1170 template void LazyObjFile::parse<ELF32LE>();
1171 template void LazyObjFile::parse<ELF32BE>();
1172 template void LazyObjFile::parse<ELF64LE>();
1173 template void LazyObjFile::parse<ELF64BE>();
1174 
1175 template class elf::ELFFileBase<ELF32LE>;
1176 template class elf::ELFFileBase<ELF32BE>;
1177 template class elf::ELFFileBase<ELF64LE>;
1178 template class elf::ELFFileBase<ELF64BE>;
1179 
1180 template class elf::ObjFile<ELF32LE>;
1181 template class elf::ObjFile<ELF32BE>;
1182 template class elf::ObjFile<ELF64LE>;
1183 template class elf::ObjFile<ELF64BE>;
1184 
1185 template class elf::SharedFile<ELF32LE>;
1186 template class elf::SharedFile<ELF32BE>;
1187 template class elf::SharedFile<ELF64LE>;
1188 template class elf::SharedFile<ELF64BE>;
1189