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