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 "Error.h"
12 #include "InputSection.h"
13 #include "LinkerScript.h"
14 #include "Memory.h"
15 #include "SymbolTable.h"
16 #include "Symbols.h"
17 #include "SyntheticSections.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Bitcode/BitcodeReader.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/LTO/LTO.h"
25 #include "llvm/MC/StringTableBuilder.h"
26 #include "llvm/Object/ELFObjectFile.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/TarWriter.h"
29 #include "llvm/Support/raw_ostream.h"
30 
31 using namespace llvm;
32 using namespace llvm::ELF;
33 using namespace llvm::object;
34 using namespace llvm::sys::fs;
35 
36 using namespace lld;
37 using namespace lld::elf;
38 
39 TarWriter *elf::Tar;
40 
41 namespace {
42 // In ELF object file all section addresses are zero. If we have multiple
43 // .text sections (when using -ffunction-section or comdat group) then
44 // LLVM DWARF parser will not be able to parse .debug_line correctly, unless
45 // we assign each section some unique address. This callback method assigns
46 // each section an address equal to its offset in ELF object file.
47 class ObjectInfo : public LoadedObjectInfo {
48 public:
49   uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const override {
50     return static_cast<const ELFSectionRef &>(Sec).getOffset();
51   }
52   std::unique_ptr<LoadedObjectInfo> clone() const override {
53     return std::unique_ptr<LoadedObjectInfo>();
54   }
55 };
56 }
57 
58 Optional<MemoryBufferRef> elf::readFile(StringRef Path) {
59   if (Config->Verbose)
60     outs() << Path << "\n";
61 
62   auto MBOrErr = MemoryBuffer::getFile(Path);
63   if (auto EC = MBOrErr.getError()) {
64     error("cannot open " + Path + ": " + EC.message());
65     return None;
66   }
67   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
68   MemoryBufferRef MBRef = MB->getMemBufferRef();
69   make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take MB ownership
70 
71   if (Tar)
72     Tar->append(relativeToRoot(Path), MBRef.getBuffer());
73   return MBRef;
74 }
75 
76 template <class ELFT> void elf::ObjectFile<ELFT>::initializeDwarfLine() {
77   std::unique_ptr<object::ObjectFile> Obj =
78       check(object::ObjectFile::createObjectFile(this->MB),
79             "createObjectFile failed");
80 
81   ObjectInfo ObjInfo;
82   DWARFContextInMemory Dwarf(*Obj, &ObjInfo);
83   DwarfLine.reset(new DWARFDebugLine(&Dwarf.getLineSection().Relocs));
84   DataExtractor LineData(Dwarf.getLineSection().Data,
85                          ELFT::TargetEndianness == support::little,
86                          ELFT::Is64Bits ? 8 : 4);
87 
88   // The second parameter is offset in .debug_line section
89   // for compilation unit (CU) of interest. We have only one
90   // CU (object file), so offset is always 0.
91   DwarfLine->getOrParseLineTable(LineData, 0);
92 }
93 
94 // Returns source line information for a given offset
95 // using DWARF debug info.
96 template <class ELFT>
97 std::string elf::ObjectFile<ELFT>::getLineInfo(InputSectionBase<ELFT> *S,
98                                                uintX_t Offset) {
99   if (!DwarfLine)
100     initializeDwarfLine();
101 
102   // The offset to CU is 0.
103   const DWARFDebugLine::LineTable *Tbl = DwarfLine->getLineTable(0);
104   if (!Tbl)
105     return "";
106 
107   // Use fake address calcuated by adding section file offset and offset in
108   // section. See comments for ObjectInfo class.
109   DILineInfo Info;
110   Tbl->getFileLineInfoForAddress(
111       S->Offset + Offset, nullptr,
112       DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Info);
113   if (Info.Line == 0)
114     return "";
115   return Info.FileName + ":" + std::to_string(Info.Line);
116 }
117 
118 // Returns "(internal)", "foo.a(bar.o)" or "baz.o".
119 std::string lld::toString(const InputFile *F) {
120   if (!F)
121     return "(internal)";
122   if (!F->ArchiveName.empty())
123     return (F->ArchiveName + "(" + F->getName() + ")").str();
124   return F->getName();
125 }
126 
127 template <class ELFT> static ELFKind getELFKind() {
128   if (ELFT::TargetEndianness == support::little)
129     return ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
130   return ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
131 }
132 
133 template <class ELFT>
134 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB) : InputFile(K, MB) {
135   EKind = getELFKind<ELFT>();
136   EMachine = getObj().getHeader()->e_machine;
137   OSABI = getObj().getHeader()->e_ident[llvm::ELF::EI_OSABI];
138 }
139 
140 template <class ELFT>
141 typename ELFT::SymRange ELFFileBase<ELFT>::getGlobalSymbols() {
142   return makeArrayRef(Symbols.begin() + FirstNonLocal, Symbols.end());
143 }
144 
145 template <class ELFT>
146 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
147   return check(getObj().getSectionIndex(&Sym, Symbols, SymtabSHNDX));
148 }
149 
150 template <class ELFT>
151 void ELFFileBase<ELFT>::initSymtab(ArrayRef<Elf_Shdr> Sections,
152                                    const Elf_Shdr *Symtab) {
153   FirstNonLocal = Symtab->sh_info;
154   Symbols = check(getObj().symbols(Symtab));
155   if (FirstNonLocal == 0 || FirstNonLocal > Symbols.size())
156     fatal(toString(this) + ": invalid sh_info in symbol table");
157 
158   StringTable = check(getObj().getStringTableForSymtab(*Symtab, Sections));
159 }
160 
161 template <class ELFT>
162 elf::ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M)
163     : ELFFileBase<ELFT>(Base::ObjectKind, M) {}
164 
165 template <class ELFT>
166 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getNonLocalSymbols() {
167   return makeArrayRef(this->SymbolBodies).slice(this->FirstNonLocal);
168 }
169 
170 template <class ELFT>
171 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getLocalSymbols() {
172   if (this->SymbolBodies.empty())
173     return this->SymbolBodies;
174   return makeArrayRef(this->SymbolBodies).slice(1, this->FirstNonLocal - 1);
175 }
176 
177 template <class ELFT>
178 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getSymbols() {
179   if (this->SymbolBodies.empty())
180     return this->SymbolBodies;
181   return makeArrayRef(this->SymbolBodies).slice(1);
182 }
183 
184 template <class ELFT>
185 void elf::ObjectFile<ELFT>::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
186   // Read section and symbol tables.
187   initializeSections(ComdatGroups);
188   initializeSymbols();
189 }
190 
191 // Sections with SHT_GROUP and comdat bits define comdat section groups.
192 // They are identified and deduplicated by group name. This function
193 // returns a group name.
194 template <class ELFT>
195 StringRef
196 elf::ObjectFile<ELFT>::getShtGroupSignature(ArrayRef<Elf_Shdr> Sections,
197                                             const Elf_Shdr &Sec) {
198   if (this->Symbols.empty())
199     this->initSymtab(Sections,
200                      check(object::getSection<ELFT>(Sections, Sec.sh_link)));
201   const Elf_Sym *Sym =
202       check(object::getSymbol<ELFT>(this->Symbols, Sec.sh_info));
203   return check(Sym->getName(this->StringTable));
204 }
205 
206 template <class ELFT>
207 ArrayRef<typename elf::ObjectFile<ELFT>::Elf_Word>
208 elf::ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
209   const ELFFile<ELFT> &Obj = this->getObj();
210   ArrayRef<Elf_Word> Entries =
211       check(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec));
212   if (Entries.empty() || Entries[0] != GRP_COMDAT)
213     fatal(toString(this) + ": unsupported SHT_GROUP format");
214   return Entries.slice(1);
215 }
216 
217 template <class ELFT>
218 bool elf::ObjectFile<ELFT>::shouldMerge(const Elf_Shdr &Sec) {
219   // We don't merge sections if -O0 (default is -O1). This makes sometimes
220   // the linker significantly faster, although the output will be bigger.
221   if (Config->Optimize == 0)
222     return false;
223 
224   // Do not merge sections if generating a relocatable object. It makes
225   // the code simpler because we do not need to update relocation addends
226   // to reflect changes introduced by merging. Instead of that we write
227   // such "merge" sections into separate OutputSections and keep SHF_MERGE
228   // / SHF_STRINGS flags and sh_entsize value to be able to perform merging
229   // later during a final linking.
230   if (Config->Relocatable)
231     return false;
232 
233   // A mergeable section with size 0 is useless because they don't have
234   // any data to merge. A mergeable string section with size 0 can be
235   // argued as invalid because it doesn't end with a null character.
236   // We'll avoid a mess by handling them as if they were non-mergeable.
237   if (Sec.sh_size == 0)
238     return false;
239 
240   // Check for sh_entsize. The ELF spec is not clear about the zero
241   // sh_entsize. It says that "the member [sh_entsize] contains 0 if
242   // the section does not hold a table of fixed-size entries". We know
243   // that Rust 1.13 produces a string mergeable section with a zero
244   // sh_entsize. Here we just accept it rather than being picky about it.
245   uintX_t EntSize = Sec.sh_entsize;
246   if (EntSize == 0)
247     return false;
248   if (Sec.sh_size % EntSize)
249     fatal(toString(this) +
250           ": SHF_MERGE section size must be a multiple of sh_entsize");
251 
252   uintX_t Flags = Sec.sh_flags;
253   if (!(Flags & SHF_MERGE))
254     return false;
255   if (Flags & SHF_WRITE)
256     fatal(toString(this) + ": writable SHF_MERGE section is not supported");
257 
258   // Don't try to merge if the alignment is larger than the sh_entsize and this
259   // is not SHF_STRINGS.
260   //
261   // Since this is not a SHF_STRINGS, we would need to pad after every entity.
262   // It would be equivalent for the producer of the .o to just set a larger
263   // sh_entsize.
264   if (Flags & SHF_STRINGS)
265     return true;
266 
267   return Sec.sh_addralign <= EntSize;
268 }
269 
270 template <class ELFT>
271 void elf::ObjectFile<ELFT>::initializeSections(
272     DenseSet<CachedHashStringRef> &ComdatGroups) {
273   ArrayRef<Elf_Shdr> ObjSections = check(this->getObj().sections());
274   const ELFFile<ELFT> &Obj = this->getObj();
275   uint64_t Size = ObjSections.size();
276   Sections.resize(Size);
277   unsigned I = -1;
278   StringRef SectionStringTable = check(Obj.getSectionStringTable(ObjSections));
279   for (const Elf_Shdr &Sec : ObjSections) {
280     ++I;
281     if (Sections[I] == &InputSection<ELFT>::Discarded)
282       continue;
283 
284     // SHF_EXCLUDE'ed sections are discarded by the linker. However,
285     // if -r is given, we'll let the final link discard such sections.
286     // This is compatible with GNU.
287     if ((Sec.sh_flags & SHF_EXCLUDE) && !Config->Relocatable) {
288       Sections[I] = &InputSection<ELFT>::Discarded;
289       continue;
290     }
291 
292     switch (Sec.sh_type) {
293     case SHT_GROUP:
294       Sections[I] = &InputSection<ELFT>::Discarded;
295       if (ComdatGroups.insert(CachedHashStringRef(
296                                   getShtGroupSignature(ObjSections, Sec)))
297               .second)
298         continue;
299       for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
300         if (SecIndex >= Size)
301           fatal(toString(this) + ": invalid section index in group: " +
302                 Twine(SecIndex));
303         Sections[SecIndex] = &InputSection<ELFT>::Discarded;
304       }
305       break;
306     case SHT_SYMTAB:
307       this->initSymtab(ObjSections, &Sec);
308       break;
309     case SHT_SYMTAB_SHNDX:
310       this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec, ObjSections));
311       break;
312     case SHT_STRTAB:
313     case SHT_NULL:
314       break;
315     default:
316       Sections[I] = createInputSection(Sec, SectionStringTable);
317     }
318 
319     // .ARM.exidx sections have a reverse dependency on the InputSection they
320     // have a SHF_LINK_ORDER dependency, this is identified by the sh_link.
321     if (Sec.sh_flags & SHF_LINK_ORDER) {
322       if (Sec.sh_link >= Sections.size())
323         fatal(toString(this) + ": invalid sh_link index: " +
324               Twine(Sec.sh_link));
325       Sections[Sec.sh_link]->DependentSections.push_back(Sections[I]);
326     }
327   }
328 }
329 
330 template <class ELFT>
331 InputSectionBase<ELFT> *
332 elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
333   uint32_t Idx = Sec.sh_info;
334   if (Idx >= Sections.size())
335     fatal(toString(this) + ": invalid relocated section index: " + Twine(Idx));
336   InputSectionBase<ELFT> *Target = Sections[Idx];
337 
338   // Strictly speaking, a relocation section must be included in the
339   // group of the section it relocates. However, LLVM 3.3 and earlier
340   // would fail to do so, so we gracefully handle that case.
341   if (Target == &InputSection<ELFT>::Discarded)
342     return nullptr;
343 
344   if (!Target)
345     fatal(toString(this) + ": unsupported relocation reference");
346   return Target;
347 }
348 
349 template <class ELFT>
350 InputSectionBase<ELFT> *
351 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec,
352                                           StringRef SectionStringTable) {
353   StringRef Name =
354       check(this->getObj().getSectionName(&Sec, SectionStringTable));
355 
356   switch (Sec.sh_type) {
357   case SHT_ARM_ATTRIBUTES:
358     // FIXME: ARM meta-data section. Retain the first attribute section
359     // we see. The eglibc ARM dynamic loaders require the presence of an
360     // attribute section for dlopen to work.
361     // In a full implementation we would merge all attribute sections.
362     if (In<ELFT>::ARMAttributes == nullptr) {
363       In<ELFT>::ARMAttributes = make<InputSection<ELFT>>(this, &Sec, Name);
364       return In<ELFT>::ARMAttributes;
365     }
366     return &InputSection<ELFT>::Discarded;
367   case SHT_RELA:
368   case SHT_REL: {
369     // Find the relocation target section and associate this
370     // section with it. Target can be discarded, for example
371     // if it is a duplicated member of SHT_GROUP section, we
372     // do not create or proccess relocatable sections then.
373     InputSectionBase<ELFT> *Target = getRelocTarget(Sec);
374     if (!Target)
375       return nullptr;
376 
377     // This section contains relocation information.
378     // If -r is given, we do not interpret or apply relocation
379     // but just copy relocation sections to output.
380     if (Config->Relocatable)
381       return make<InputSection<ELFT>>(this, &Sec, Name);
382 
383     if (Target->FirstRelocation)
384       fatal(toString(this) +
385             ": multiple relocation sections to one section are not supported");
386     if (!isa<InputSection<ELFT>>(Target) && !isa<EhInputSection<ELFT>>(Target))
387       fatal(toString(this) +
388             ": relocations pointing to SHF_MERGE are not supported");
389 
390     size_t NumRelocations;
391     if (Sec.sh_type == SHT_RELA) {
392       ArrayRef<Elf_Rela> Rels = check(this->getObj().relas(&Sec));
393       Target->FirstRelocation = Rels.begin();
394       NumRelocations = Rels.size();
395       Target->AreRelocsRela = true;
396     } else {
397       ArrayRef<Elf_Rel> Rels = check(this->getObj().rels(&Sec));
398       Target->FirstRelocation = Rels.begin();
399       NumRelocations = Rels.size();
400       Target->AreRelocsRela = false;
401     }
402     assert(isUInt<31>(NumRelocations));
403     Target->NumRelocations = NumRelocations;
404 
405     // Relocation sections processed by the linker are usually removed
406     // from the output, so returning `nullptr` for the normal case.
407     // However, if -emit-relocs is given, we need to leave them in the output.
408     // (Some post link analysis tools need this information.)
409     if (Config->EmitRelocs) {
410       InputSection<ELFT> *RelocSec = make<InputSection<ELFT>>(this, &Sec, Name);
411       // We will not emit relocation section if target was discarded.
412       Target->DependentSections.push_back(RelocSec);
413       return RelocSec;
414     }
415     return nullptr;
416   }
417   }
418 
419   // .note.GNU-stack is a marker section to control the presence of
420   // PT_GNU_STACK segment in outputs. Since the presence of the segment
421   // is controlled only by the command line option (-z execstack) in LLD,
422   // .note.GNU-stack is ignored.
423   if (Name == ".note.GNU-stack")
424     return &InputSection<ELFT>::Discarded;
425 
426   if (Name == ".note.GNU-split-stack") {
427     error("objects using splitstacks are not supported");
428     return &InputSection<ELFT>::Discarded;
429   }
430 
431   if (Config->Strip != StripPolicy::None && Name.startswith(".debug"))
432     return &InputSection<ELFT>::Discarded;
433 
434   // The linkonce feature is a sort of proto-comdat. Some glibc i386 object
435   // files contain definitions of symbol "__x86.get_pc_thunk.bx" in linkonce
436   // sections. Drop those sections to avoid duplicate symbol errors.
437   // FIXME: This is glibc PR20543, we should remove this hack once that has been
438   // fixed for a while.
439   if (Name.startswith(".gnu.linkonce."))
440     return &InputSection<ELFT>::Discarded;
441 
442   // The linker merges EH (exception handling) frames and creates a
443   // .eh_frame_hdr section for runtime. So we handle them with a special
444   // class. For relocatable outputs, they are just passed through.
445   if (Name == ".eh_frame" && !Config->Relocatable)
446     return make<EhInputSection<ELFT>>(this, &Sec, Name);
447 
448   if (shouldMerge(Sec))
449     return make<MergeInputSection<ELFT>>(this, &Sec, Name);
450   return make<InputSection<ELFT>>(this, &Sec, Name);
451 }
452 
453 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() {
454   SymbolBodies.reserve(this->Symbols.size());
455   for (const Elf_Sym &Sym : this->Symbols)
456     SymbolBodies.push_back(createSymbolBody(&Sym));
457 }
458 
459 template <class ELFT>
460 InputSectionBase<ELFT> *
461 elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
462   uint32_t Index = this->getSectionIndex(Sym);
463   if (Index >= Sections.size())
464     fatal(toString(this) + ": invalid section index: " + Twine(Index));
465   InputSectionBase<ELFT> *S = Sections[Index];
466 
467   // We found that GNU assembler 2.17.50 [FreeBSD] 2007-07-03 could
468   // generate broken objects. STT_SECTION/STT_NOTYPE symbols can be
469   // associated with SHT_REL[A]/SHT_SYMTAB/SHT_STRTAB sections.
470   // In this case it is fine for section to be null here as we do not
471   // allocate sections of these types.
472   if (!S) {
473     if (Index == 0 || Sym.getType() == STT_SECTION ||
474         Sym.getType() == STT_NOTYPE)
475       return nullptr;
476     fatal(toString(this) + ": invalid section index: " + Twine(Index));
477   }
478 
479   if (S == &InputSection<ELFT>::Discarded)
480     return S;
481   return S->Repl;
482 }
483 
484 template <class ELFT>
485 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
486   int Binding = Sym->getBinding();
487   InputSectionBase<ELFT> *Sec = getSection(*Sym);
488 
489   uint8_t StOther = Sym->st_other;
490   uint8_t Type = Sym->getType();
491   uintX_t Value = Sym->st_value;
492   uintX_t Size = Sym->st_size;
493 
494   if (Binding == STB_LOCAL) {
495     if (Sym->getType() == STT_FILE)
496       SourceFile = check(Sym->getName(this->StringTable));
497 
498     if (this->StringTable.size() <= Sym->st_name)
499       fatal(toString(this) + ": invalid symbol name offset");
500 
501     StringRefZ Name = this->StringTable.data() + Sym->st_name;
502     if (Sym->st_shndx == SHN_UNDEF)
503       return new (BAlloc)
504           Undefined(Name, /*IsLocal=*/true, StOther, Type, this);
505 
506     return new (BAlloc) DefinedRegular<ELFT>(Name, /*IsLocal=*/true, StOther,
507                                              Type, Value, Size, Sec, this);
508   }
509 
510   StringRef Name = check(Sym->getName(this->StringTable));
511 
512   switch (Sym->st_shndx) {
513   case SHN_UNDEF:
514     return elf::Symtab<ELFT>::X
515         ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type,
516                        /*CanOmitFromDynSym=*/false, this)
517         ->body();
518   case SHN_COMMON:
519     if (Value == 0 || Value >= UINT32_MAX)
520       fatal(toString(this) + ": common symbol '" + Name +
521             "' has invalid alignment: " + Twine(Value));
522     return elf::Symtab<ELFT>::X
523         ->addCommon(Name, Size, Value, Binding, StOther, Type, this)
524         ->body();
525   }
526 
527   switch (Binding) {
528   default:
529     fatal(toString(this) + ": unexpected binding: " + Twine(Binding));
530   case STB_GLOBAL:
531   case STB_WEAK:
532   case STB_GNU_UNIQUE:
533     if (Sec == &InputSection<ELFT>::Discarded)
534       return elf::Symtab<ELFT>::X
535           ->addUndefined(Name, /*IsLocal=*/false, Binding, StOther, Type,
536                          /*CanOmitFromDynSym=*/false, this)
537           ->body();
538     return elf::Symtab<ELFT>::X
539         ->addRegular(Name, StOther, Type, Value, Size, Binding, Sec, this)
540         ->body();
541   }
542 }
543 
544 template <class ELFT> void ArchiveFile::parse() {
545   File = check(Archive::create(MB),
546                MB.getBufferIdentifier() + ": failed to parse archive");
547 
548   // Read the symbol table to construct Lazy objects.
549   for (const Archive::Symbol &Sym : File->symbols())
550     Symtab<ELFT>::X->addLazyArchive(this, Sym);
551 }
552 
553 // Returns a buffer pointing to a member file containing a given symbol.
554 std::pair<MemoryBufferRef, uint64_t>
555 ArchiveFile::getMember(const Archive::Symbol *Sym) {
556   Archive::Child C =
557       check(Sym->getMember(),
558             "could not get the member for symbol " + Sym->getName());
559 
560   if (!Seen.insert(C.getChildOffset()).second)
561     return {MemoryBufferRef(), 0};
562 
563   MemoryBufferRef Ret =
564       check(C.getMemoryBufferRef(),
565             "could not get the buffer for the member defining symbol " +
566                 Sym->getName());
567 
568   if (C.getParent()->isThin() && Tar)
569     Tar->append(relativeToRoot(check(C.getFullName())), Ret.getBuffer());
570   if (C.getParent()->isThin())
571     return {Ret, 0};
572   return {Ret, C.getChildOffset()};
573 }
574 
575 template <class ELFT>
576 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
577     : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {}
578 
579 template <class ELFT>
580 const typename ELFT::Shdr *
581 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
582   return check(
583       this->getObj().getSection(&Sym, this->Symbols, this->SymtabSHNDX));
584 }
585 
586 // Partially parse the shared object file so that we can call
587 // getSoName on this object.
588 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
589   const Elf_Shdr *DynamicSec = nullptr;
590 
591   const ELFFile<ELFT> Obj = this->getObj();
592   ArrayRef<Elf_Shdr> Sections = check(Obj.sections());
593   for (const Elf_Shdr &Sec : Sections) {
594     switch (Sec.sh_type) {
595     default:
596       continue;
597     case SHT_DYNSYM:
598       this->initSymtab(Sections, &Sec);
599       break;
600     case SHT_DYNAMIC:
601       DynamicSec = &Sec;
602       break;
603     case SHT_SYMTAB_SHNDX:
604       this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec, Sections));
605       break;
606     case SHT_GNU_versym:
607       this->VersymSec = &Sec;
608       break;
609     case SHT_GNU_verdef:
610       this->VerdefSec = &Sec;
611       break;
612     }
613   }
614 
615   if (this->VersymSec && this->Symbols.empty())
616     error("SHT_GNU_versym should be associated with symbol table");
617 
618   // DSOs are identified by soname, and they usually contain
619   // DT_SONAME tag in their header. But if they are missing,
620   // filenames are used as default sonames.
621   SoName = sys::path::filename(this->getName());
622 
623   if (!DynamicSec)
624     return;
625 
626   ArrayRef<Elf_Dyn> Arr =
627       check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec),
628             toString(this) + ": getSectionContentsAsArray failed");
629   for (const Elf_Dyn &Dyn : Arr) {
630     if (Dyn.d_tag == DT_SONAME) {
631       uintX_t Val = Dyn.getVal();
632       if (Val >= this->StringTable.size())
633         fatal(toString(this) + ": invalid DT_SONAME entry");
634       SoName = StringRef(this->StringTable.data() + Val);
635       return;
636     }
637   }
638 }
639 
640 // Parse the version definitions in the object file if present. Returns a vector
641 // whose nth element contains a pointer to the Elf_Verdef for version identifier
642 // n. Version identifiers that are not definitions map to nullptr. The array
643 // always has at least length 1.
644 template <class ELFT>
645 std::vector<const typename ELFT::Verdef *>
646 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
647   std::vector<const Elf_Verdef *> Verdefs(1);
648   // We only need to process symbol versions for this DSO if it has both a
649   // versym and a verdef section, which indicates that the DSO contains symbol
650   // version definitions.
651   if (!VersymSec || !VerdefSec)
652     return Verdefs;
653 
654   // The location of the first global versym entry.
655   const char *Base = this->MB.getBuffer().data();
656   Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
657            this->FirstNonLocal;
658 
659   // We cannot determine the largest verdef identifier without inspecting
660   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
661   // sequentially starting from 1, so we predict that the largest identifier
662   // will be VerdefCount.
663   unsigned VerdefCount = VerdefSec->sh_info;
664   Verdefs.resize(VerdefCount + 1);
665 
666   // Build the Verdefs array by following the chain of Elf_Verdef objects
667   // from the start of the .gnu.version_d section.
668   const char *Verdef = Base + VerdefSec->sh_offset;
669   for (unsigned I = 0; I != VerdefCount; ++I) {
670     auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
671     Verdef += CurVerdef->vd_next;
672     unsigned VerdefIndex = CurVerdef->vd_ndx;
673     if (Verdefs.size() <= VerdefIndex)
674       Verdefs.resize(VerdefIndex + 1);
675     Verdefs[VerdefIndex] = CurVerdef;
676   }
677 
678   return Verdefs;
679 }
680 
681 // Fully parse the shared object file. This must be called after parseSoName().
682 template <class ELFT> void SharedFile<ELFT>::parseRest() {
683   // Create mapping from version identifiers to Elf_Verdef entries.
684   const Elf_Versym *Versym = nullptr;
685   std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
686 
687   Elf_Sym_Range Syms = this->getGlobalSymbols();
688   for (const Elf_Sym &Sym : Syms) {
689     unsigned VersymIndex = 0;
690     if (Versym) {
691       VersymIndex = Versym->vs_index;
692       ++Versym;
693     }
694     bool Hidden = VersymIndex & VERSYM_HIDDEN;
695     VersymIndex = VersymIndex & ~VERSYM_HIDDEN;
696 
697     StringRef Name = check(Sym.getName(this->StringTable));
698     if (Sym.isUndefined()) {
699       Undefs.push_back(Name);
700       continue;
701     }
702 
703     // Ignore local symbols.
704     if (Versym && VersymIndex == VER_NDX_LOCAL)
705       continue;
706 
707     const Elf_Verdef *V =
708         VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
709 
710     if (!Hidden)
711       elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
712 
713     // Also add the symbol with the versioned name to handle undefined symbols
714     // with explicit versions.
715     if (V) {
716       StringRef VerName = this->StringTable.data() + V->getAux()->vda_name;
717       Name = Saver.save(Twine(Name) + "@" + VerName);
718       elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
719     }
720   }
721 }
722 
723 static ELFKind getBitcodeELFKind(MemoryBufferRef MB) {
724   Triple T(check(getBitcodeTargetTriple(MB)));
725   if (T.isLittleEndian())
726     return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
727   return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
728 }
729 
730 static uint8_t getBitcodeMachineKind(MemoryBufferRef MB) {
731   Triple T(check(getBitcodeTargetTriple(MB)));
732   switch (T.getArch()) {
733   case Triple::aarch64:
734     return EM_AARCH64;
735   case Triple::arm:
736     return EM_ARM;
737   case Triple::mips:
738   case Triple::mipsel:
739   case Triple::mips64:
740   case Triple::mips64el:
741     return EM_MIPS;
742   case Triple::ppc:
743     return EM_PPC;
744   case Triple::ppc64:
745     return EM_PPC64;
746   case Triple::x86:
747     return T.isOSIAMCU() ? EM_IAMCU : EM_386;
748   case Triple::x86_64:
749     return EM_X86_64;
750   default:
751     fatal(MB.getBufferIdentifier() +
752           ": could not infer e_machine from bitcode target triple " + T.str());
753   }
754 }
755 
756 BitcodeFile::BitcodeFile(MemoryBufferRef MB) : InputFile(BitcodeKind, MB) {
757   EKind = getBitcodeELFKind(MB);
758   EMachine = getBitcodeMachineKind(MB);
759 }
760 
761 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
762   switch (GvVisibility) {
763   case GlobalValue::DefaultVisibility:
764     return STV_DEFAULT;
765   case GlobalValue::HiddenVisibility:
766     return STV_HIDDEN;
767   case GlobalValue::ProtectedVisibility:
768     return STV_PROTECTED;
769   }
770   llvm_unreachable("unknown visibility");
771 }
772 
773 template <class ELFT>
774 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
775                                    const lto::InputFile::Symbol &ObjSym,
776                                    BitcodeFile *F) {
777   StringRef NameRef = Saver.save(ObjSym.getName());
778   uint32_t Flags = ObjSym.getFlags();
779   uint32_t Binding = (Flags & BasicSymbolRef::SF_Weak) ? STB_WEAK : STB_GLOBAL;
780 
781   uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
782   uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
783   bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
784 
785   int C = check(ObjSym.getComdatIndex());
786   if (C != -1 && !KeptComdats[C])
787     return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding,
788                                          Visibility, Type, CanOmitFromDynSym,
789                                          F);
790 
791   if (Flags & BasicSymbolRef::SF_Undefined)
792     return Symtab<ELFT>::X->addUndefined(NameRef, /*IsLocal=*/false, Binding,
793                                          Visibility, Type, CanOmitFromDynSym,
794                                          F);
795 
796   if (Flags & BasicSymbolRef::SF_Common)
797     return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(),
798                                       ObjSym.getCommonAlignment(), Binding,
799                                       Visibility, STT_OBJECT, F);
800 
801   return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type,
802                                      CanOmitFromDynSym, F);
803 }
804 
805 template <class ELFT>
806 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
807 
808   // Here we pass a new MemoryBufferRef which is identified by ArchiveName
809   // (the fully resolved path of the archive) + member name + offset of the
810   // member in the archive.
811   // ThinLTO uses the MemoryBufferRef identifier to access its internal
812   // data structures and if two archives define two members with the same name,
813   // this causes a collision which result in only one of the objects being
814   // taken into consideration at LTO time (which very likely causes undefined
815   // symbols later in the link stage).
816   Obj = check(lto::InputFile::create(MemoryBufferRef(
817       MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier() +
818                                  utostr(OffsetInArchive)))));
819 
820   std::vector<bool> KeptComdats;
821   for (StringRef S : Obj->getComdatTable()) {
822     StringRef N = Saver.save(S);
823     KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(N)).second);
824   }
825 
826   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
827     Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this));
828 }
829 
830 template <template <class> class T>
831 static InputFile *createELFFile(MemoryBufferRef MB) {
832   unsigned char Size;
833   unsigned char Endian;
834   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
835   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
836     fatal(MB.getBufferIdentifier() + ": invalid data encoding");
837 
838   size_t BufSize = MB.getBuffer().size();
839   if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
840       (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
841     fatal(MB.getBufferIdentifier() + ": file is too short");
842 
843   InputFile *Obj;
844   if (Size == ELFCLASS32 && Endian == ELFDATA2LSB)
845     Obj = make<T<ELF32LE>>(MB);
846   else if (Size == ELFCLASS32 && Endian == ELFDATA2MSB)
847     Obj = make<T<ELF32BE>>(MB);
848   else if (Size == ELFCLASS64 && Endian == ELFDATA2LSB)
849     Obj = make<T<ELF64LE>>(MB);
850   else if (Size == ELFCLASS64 && Endian == ELFDATA2MSB)
851     Obj = make<T<ELF64BE>>(MB);
852   else
853     fatal(MB.getBufferIdentifier() + ": invalid file class");
854 
855   if (!Config->FirstElf)
856     Config->FirstElf = Obj;
857   return Obj;
858 }
859 
860 template <class ELFT> void BinaryFile::parse() {
861   StringRef Buf = MB.getBuffer();
862   ArrayRef<uint8_t> Data =
863       makeArrayRef<uint8_t>((const uint8_t *)Buf.data(), Buf.size());
864 
865   std::string Filename = MB.getBufferIdentifier();
866   std::transform(Filename.begin(), Filename.end(), Filename.begin(),
867                  [](char C) { return isalnum(C) ? C : '_'; });
868   Filename = "_binary_" + Filename;
869   StringRef StartName = Saver.save(Twine(Filename) + "_start");
870   StringRef EndName = Saver.save(Twine(Filename) + "_end");
871   StringRef SizeName = Saver.save(Twine(Filename) + "_size");
872 
873   auto *Section = make<InputSection<ELFT>>(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS,
874                                            8, Data, ".data");
875   Sections.push_back(Section);
876 
877   elf::Symtab<ELFT>::X->addRegular(StartName, STV_DEFAULT, STT_OBJECT, 0, 0,
878                                    STB_GLOBAL, Section, nullptr);
879   elf::Symtab<ELFT>::X->addRegular(EndName, STV_DEFAULT, STT_OBJECT,
880                                    Data.size(), 0, STB_GLOBAL, Section,
881                                    nullptr);
882   elf::Symtab<ELFT>::X->addRegular(SizeName, STV_DEFAULT, STT_OBJECT,
883                                    Data.size(), 0, STB_GLOBAL, nullptr,
884                                    nullptr);
885 }
886 
887 static bool isBitcode(MemoryBufferRef MB) {
888   using namespace sys::fs;
889   return identify_magic(MB.getBuffer()) == file_magic::bitcode;
890 }
891 
892 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
893                                  uint64_t OffsetInArchive) {
894   InputFile *F =
895       isBitcode(MB) ? make<BitcodeFile>(MB) : createELFFile<ObjectFile>(MB);
896   F->ArchiveName = ArchiveName;
897   F->OffsetInArchive = OffsetInArchive;
898   return F;
899 }
900 
901 InputFile *elf::createSharedFile(MemoryBufferRef MB) {
902   return createELFFile<SharedFile>(MB);
903 }
904 
905 MemoryBufferRef LazyObjectFile::getBuffer() {
906   if (Seen)
907     return MemoryBufferRef();
908   Seen = true;
909   return MB;
910 }
911 
912 template <class ELFT> void LazyObjectFile::parse() {
913   for (StringRef Sym : getSymbols())
914     Symtab<ELFT>::X->addLazyObject(Sym, *this);
915 }
916 
917 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() {
918   typedef typename ELFT::Shdr Elf_Shdr;
919   typedef typename ELFT::Sym Elf_Sym;
920   typedef typename ELFT::SymRange Elf_Sym_Range;
921 
922   const ELFFile<ELFT> Obj(this->MB.getBuffer());
923   ArrayRef<Elf_Shdr> Sections = check(Obj.sections());
924   for (const Elf_Shdr &Sec : Sections) {
925     if (Sec.sh_type != SHT_SYMTAB)
926       continue;
927     Elf_Sym_Range Syms = check(Obj.symbols(&Sec));
928     uint32_t FirstNonLocal = Sec.sh_info;
929     StringRef StringTable = check(Obj.getStringTableForSymtab(Sec, Sections));
930     std::vector<StringRef> V;
931     for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
932       if (Sym.st_shndx != SHN_UNDEF)
933         V.push_back(check(Sym.getName(StringTable)));
934     return V;
935   }
936   return {};
937 }
938 
939 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() {
940   std::unique_ptr<lto::InputFile> Obj = check(lto::InputFile::create(this->MB));
941   std::vector<StringRef> V;
942   for (const lto::InputFile::Symbol &Sym : Obj->symbols())
943     if (!(Sym.getFlags() & BasicSymbolRef::SF_Undefined))
944       V.push_back(Saver.save(Sym.getName()));
945   return V;
946 }
947 
948 // Returns a vector of globally-visible defined symbol names.
949 std::vector<StringRef> LazyObjectFile::getSymbols() {
950   if (isBitcode(this->MB))
951     return getBitcodeSymbols();
952 
953   unsigned char Size;
954   unsigned char Endian;
955   std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer());
956   if (Size == ELFCLASS32) {
957     if (Endian == ELFDATA2LSB)
958       return getElfSymbols<ELF32LE>();
959     return getElfSymbols<ELF32BE>();
960   }
961   if (Endian == ELFDATA2LSB)
962     return getElfSymbols<ELF64LE>();
963   return getElfSymbols<ELF64BE>();
964 }
965 
966 template void ArchiveFile::parse<ELF32LE>();
967 template void ArchiveFile::parse<ELF32BE>();
968 template void ArchiveFile::parse<ELF64LE>();
969 template void ArchiveFile::parse<ELF64BE>();
970 
971 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
972 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
973 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
974 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
975 
976 template void LazyObjectFile::parse<ELF32LE>();
977 template void LazyObjectFile::parse<ELF32BE>();
978 template void LazyObjectFile::parse<ELF64LE>();
979 template void LazyObjectFile::parse<ELF64BE>();
980 
981 template class elf::ELFFileBase<ELF32LE>;
982 template class elf::ELFFileBase<ELF32BE>;
983 template class elf::ELFFileBase<ELF64LE>;
984 template class elf::ELFFileBase<ELF64BE>;
985 
986 template class elf::ObjectFile<ELF32LE>;
987 template class elf::ObjectFile<ELF32BE>;
988 template class elf::ObjectFile<ELF64LE>;
989 template class elf::ObjectFile<ELF64BE>;
990 
991 template class elf::SharedFile<ELF32LE>;
992 template class elf::SharedFile<ELF32BE>;
993 template class elf::SharedFile<ELF64LE>;
994 template class elf::SharedFile<ELF64BE>;
995 
996 template void BinaryFile::parse<ELF32LE>();
997 template void BinaryFile::parse<ELF32BE>();
998 template void BinaryFile::parse<ELF64LE>();
999 template void BinaryFile::parse<ELF64BE>();
1000