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