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