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::getFilename(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(getFilename(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(getFilename(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(getFilename(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(getFilename(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(getFilename(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(getFilename(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(getFilename(this) + ": invalid relocated section index: " +
316           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(getFilename(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(getFilename(this) +
357             ": multiple relocation sections to one section are not supported");
358     if (!isa<InputSection<ELFT>>(Target) && !isa<EhInputSection<ELFT>>(Target))
359       fatal(getFilename(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(getFilename(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
421   // could generate broken objects. STT_SECTION 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
424   // do not allocate sections of these types.
425   if (!S) {
426     if (Index == 0 || Sym.getType() == STT_SECTION)
427       return nullptr;
428     fatal(getFilename(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   if (Binding == STB_LOCAL) {
441     if (Sym->getType() == STT_FILE)
442       SourceFile = check(Sym->getName(this->StringTable));
443     if (Sym->st_shndx == SHN_UNDEF)
444       return new (BAlloc)
445           Undefined(Sym->st_name, Sym->st_other, Sym->getType(), this);
446     return new (BAlloc) DefinedRegular<ELFT>(*Sym, Sec);
447   }
448 
449   StringRef Name = check(Sym->getName(this->StringTable));
450 
451   switch (Sym->st_shndx) {
452   case SHN_UNDEF:
453     return elf::Symtab<ELFT>::X->addUndefined(Name, Binding, Sym->st_other,
454                                               Sym->getType(),
455                                               /*CanOmitFromDynSym*/ false, this)
456         ->body();
457   case SHN_COMMON:
458     if (Sym->st_value == 0 || Sym->st_value >= UINT32_MAX)
459       fatal(getFilename(this) + ": common symbol '" + Name +
460             "' has invalid alignment: " + Twine(Sym->st_value));
461     return elf::Symtab<ELFT>::X->addCommon(Name, Sym->st_size, Sym->st_value,
462                                            Binding, Sym->st_other,
463                                            Sym->getType(), this)
464         ->body();
465   }
466 
467   switch (Binding) {
468   default:
469     fatal(getFilename(this) + ": unexpected binding: " + Twine(Binding));
470   case STB_GLOBAL:
471   case STB_WEAK:
472   case STB_GNU_UNIQUE:
473     if (Sec == &InputSection<ELFT>::Discarded)
474       return elf::Symtab<ELFT>::X->addUndefined(Name, Binding, Sym->st_other,
475                                                 Sym->getType(),
476                                                 /*CanOmitFromDynSym*/ false,
477                                                 this)
478           ->body();
479     return elf::Symtab<ELFT>::X->addRegular(Name, *Sym, Sec)->body();
480   }
481 }
482 
483 template <class ELFT> void ArchiveFile::parse() {
484   File = check(Archive::create(MB), "failed to parse archive");
485 
486   // Read the symbol table to construct Lazy objects.
487   for (const Archive::Symbol &Sym : File->symbols())
488     Symtab<ELFT>::X->addLazyArchive(this, Sym);
489 }
490 
491 // Returns a buffer pointing to a member file containing a given symbol.
492 std::pair<MemoryBufferRef, uint64_t>
493 ArchiveFile::getMember(const Archive::Symbol *Sym) {
494   Archive::Child C =
495       check(Sym->getMember(),
496             "could not get the member for symbol " + Sym->getName());
497 
498   if (!Seen.insert(C.getChildOffset()).second)
499     return {MemoryBufferRef(), 0};
500 
501   MemoryBufferRef Ret =
502       check(C.getMemoryBufferRef(),
503             "could not get the buffer for the member defining symbol " +
504                 Sym->getName());
505 
506   if (C.getParent()->isThin() && Driver->Cpio)
507     Driver->Cpio->append(relativeToRoot(check(C.getFullName())),
508                          Ret.getBuffer());
509   if (C.getParent()->isThin())
510     return {Ret, 0};
511   return {Ret, C.getChildOffset()};
512 }
513 
514 template <class ELFT>
515 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
516     : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {}
517 
518 template <class ELFT>
519 const typename ELFT::Shdr *
520 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
521   return check(
522       this->getObj().getSection(&Sym, this->Symbols, this->SymtabSHNDX));
523 }
524 
525 // Partially parse the shared object file so that we can call
526 // getSoName on this object.
527 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
528   typedef typename ELFT::Dyn Elf_Dyn;
529   typedef typename ELFT::uint uintX_t;
530   const Elf_Shdr *DynamicSec = nullptr;
531 
532   const ELFFile<ELFT> Obj = this->getObj();
533   ArrayRef<Elf_Shdr> Sections = check(Obj.sections());
534   for (const Elf_Shdr &Sec : Sections) {
535     switch (Sec.sh_type) {
536     default:
537       continue;
538     case SHT_DYNSYM:
539       this->initSymtab(Sections, &Sec);
540       break;
541     case SHT_DYNAMIC:
542       DynamicSec = &Sec;
543       break;
544     case SHT_SYMTAB_SHNDX:
545       this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec, Sections));
546       break;
547     case SHT_GNU_versym:
548       this->VersymSec = &Sec;
549       break;
550     case SHT_GNU_verdef:
551       this->VerdefSec = &Sec;
552       break;
553     }
554   }
555 
556   if (this->VersymSec && this->Symbols.empty())
557     error("SHT_GNU_versym should be associated with symbol table");
558 
559   // DSOs are identified by soname, and they usually contain
560   // DT_SONAME tag in their header. But if they are missing,
561   // filenames are used as default sonames.
562   SoName = sys::path::filename(this->getName());
563 
564   if (!DynamicSec)
565     return;
566 
567   ArrayRef<Elf_Dyn> Arr =
568       check(Obj.template getSectionContentsAsArray<Elf_Dyn>(DynamicSec),
569             getFilename(this) + ": getSectionContentsAsArray failed");
570   for (const Elf_Dyn &Dyn : Arr) {
571     if (Dyn.d_tag == DT_SONAME) {
572       uintX_t Val = Dyn.getVal();
573       if (Val >= this->StringTable.size())
574         fatal(getFilename(this) + ": invalid DT_SONAME entry");
575       SoName = StringRef(this->StringTable.data() + Val);
576       return;
577     }
578   }
579 }
580 
581 // Parse the version definitions in the object file if present. Returns a vector
582 // whose nth element contains a pointer to the Elf_Verdef for version identifier
583 // n. Version identifiers that are not definitions map to nullptr. The array
584 // always has at least length 1.
585 template <class ELFT>
586 std::vector<const typename ELFT::Verdef *>
587 SharedFile<ELFT>::parseVerdefs(const Elf_Versym *&Versym) {
588   std::vector<const Elf_Verdef *> Verdefs(1);
589   // We only need to process symbol versions for this DSO if it has both a
590   // versym and a verdef section, which indicates that the DSO contains symbol
591   // version definitions.
592   if (!VersymSec || !VerdefSec)
593     return Verdefs;
594 
595   // The location of the first global versym entry.
596   const char *Base = this->MB.getBuffer().data();
597   Versym = reinterpret_cast<const Elf_Versym *>(Base + VersymSec->sh_offset) +
598            this->FirstNonLocal;
599 
600   // We cannot determine the largest verdef identifier without inspecting
601   // every Elf_Verdef, but both bfd and gold assign verdef identifiers
602   // sequentially starting from 1, so we predict that the largest identifier
603   // will be VerdefCount.
604   unsigned VerdefCount = VerdefSec->sh_info;
605   Verdefs.resize(VerdefCount + 1);
606 
607   // Build the Verdefs array by following the chain of Elf_Verdef objects
608   // from the start of the .gnu.version_d section.
609   const char *Verdef = Base + VerdefSec->sh_offset;
610   for (unsigned I = 0; I != VerdefCount; ++I) {
611     auto *CurVerdef = reinterpret_cast<const Elf_Verdef *>(Verdef);
612     Verdef += CurVerdef->vd_next;
613     unsigned VerdefIndex = CurVerdef->vd_ndx;
614     if (Verdefs.size() <= VerdefIndex)
615       Verdefs.resize(VerdefIndex + 1);
616     Verdefs[VerdefIndex] = CurVerdef;
617   }
618 
619   return Verdefs;
620 }
621 
622 // Fully parse the shared object file. This must be called after parseSoName().
623 template <class ELFT> void SharedFile<ELFT>::parseRest() {
624   // Create mapping from version identifiers to Elf_Verdef entries.
625   const Elf_Versym *Versym = nullptr;
626   std::vector<const Elf_Verdef *> Verdefs = parseVerdefs(Versym);
627 
628   Elf_Sym_Range Syms = this->getGlobalSymbols();
629   for (const Elf_Sym &Sym : Syms) {
630     unsigned VersymIndex = 0;
631     if (Versym) {
632       VersymIndex = Versym->vs_index;
633       ++Versym;
634     }
635 
636     StringRef Name = check(Sym.getName(this->StringTable));
637     if (Sym.isUndefined()) {
638       Undefs.push_back(Name);
639       continue;
640     }
641 
642     if (Versym) {
643       // Ignore local symbols and non-default versions.
644       if (VersymIndex == VER_NDX_LOCAL || (VersymIndex & VERSYM_HIDDEN))
645         continue;
646     }
647 
648     const Elf_Verdef *V =
649         VersymIndex == VER_NDX_GLOBAL ? nullptr : Verdefs[VersymIndex];
650     elf::Symtab<ELFT>::X->addShared(this, Name, Sym, V);
651   }
652 }
653 
654 static ELFKind getBitcodeELFKind(MemoryBufferRef MB) {
655   Triple T(check(getBitcodeTargetTriple(MB)));
656   if (T.isLittleEndian())
657     return T.isArch64Bit() ? ELF64LEKind : ELF32LEKind;
658   return T.isArch64Bit() ? ELF64BEKind : ELF32BEKind;
659 }
660 
661 static uint8_t getBitcodeMachineKind(MemoryBufferRef MB) {
662   Triple T(check(getBitcodeTargetTriple(MB)));
663   switch (T.getArch()) {
664   case Triple::aarch64:
665     return EM_AARCH64;
666   case Triple::arm:
667     return EM_ARM;
668   case Triple::mips:
669   case Triple::mipsel:
670   case Triple::mips64:
671   case Triple::mips64el:
672     return EM_MIPS;
673   case Triple::ppc:
674     return EM_PPC;
675   case Triple::ppc64:
676     return EM_PPC64;
677   case Triple::x86:
678     return T.isOSIAMCU() ? EM_IAMCU : EM_386;
679   case Triple::x86_64:
680     return EM_X86_64;
681   default:
682     fatal(MB.getBufferIdentifier() +
683           ": could not infer e_machine from bitcode target triple " + T.str());
684   }
685 }
686 
687 BitcodeFile::BitcodeFile(MemoryBufferRef MB) : InputFile(BitcodeKind, MB) {
688   EKind = getBitcodeELFKind(MB);
689   EMachine = getBitcodeMachineKind(MB);
690 }
691 
692 static uint8_t mapVisibility(GlobalValue::VisibilityTypes GvVisibility) {
693   switch (GvVisibility) {
694   case GlobalValue::DefaultVisibility:
695     return STV_DEFAULT;
696   case GlobalValue::HiddenVisibility:
697     return STV_HIDDEN;
698   case GlobalValue::ProtectedVisibility:
699     return STV_PROTECTED;
700   }
701   llvm_unreachable("unknown visibility");
702 }
703 
704 template <class ELFT>
705 static Symbol *createBitcodeSymbol(const std::vector<bool> &KeptComdats,
706                                    const lto::InputFile::Symbol &ObjSym,
707                                    BitcodeFile *F) {
708   StringRef NameRef = Saver.save(ObjSym.getName());
709   uint32_t Flags = ObjSym.getFlags();
710   uint32_t Binding = (Flags & BasicSymbolRef::SF_Weak) ? STB_WEAK : STB_GLOBAL;
711 
712   uint8_t Type = ObjSym.isTLS() ? STT_TLS : STT_NOTYPE;
713   uint8_t Visibility = mapVisibility(ObjSym.getVisibility());
714   bool CanOmitFromDynSym = ObjSym.canBeOmittedFromSymbolTable();
715 
716   int C = check(ObjSym.getComdatIndex());
717   if (C != -1 && !KeptComdats[C])
718     return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type,
719                                          CanOmitFromDynSym, F);
720 
721   if (Flags & BasicSymbolRef::SF_Undefined)
722     return Symtab<ELFT>::X->addUndefined(NameRef, Binding, Visibility, Type,
723                                          CanOmitFromDynSym, F);
724 
725   if (Flags & BasicSymbolRef::SF_Common)
726     return Symtab<ELFT>::X->addCommon(NameRef, ObjSym.getCommonSize(),
727                                       ObjSym.getCommonAlignment(), Binding,
728                                       Visibility, STT_OBJECT, F);
729 
730   return Symtab<ELFT>::X->addBitcode(NameRef, Binding, Visibility, Type,
731                                      CanOmitFromDynSym, F);
732 }
733 
734 template <class ELFT>
735 void BitcodeFile::parse(DenseSet<CachedHashStringRef> &ComdatGroups) {
736 
737   // Here we pass a new MemoryBufferRef which is identified by ArchiveName
738   // (the fully resolved path of the archive) + member name + offset of the
739   // member in the archive.
740   // ThinLTO uses the MemoryBufferRef identifier to access its internal
741   // data structures and if two archives define two members with the same name,
742   // this causes a collision which result in only one of the objects being
743   // taken into consideration at LTO time (which very likely causes undefined
744   // symbols later in the link stage).
745   Obj = check(lto::InputFile::create(MemoryBufferRef(
746       MB.getBuffer(), Saver.save(ArchiveName + MB.getBufferIdentifier() +
747                                  utostr(OffsetInArchive)))));
748 
749   std::vector<bool> KeptComdats;
750   for (StringRef S : Obj->getComdatTable()) {
751     StringRef N = Saver.save(S);
752     KeptComdats.push_back(ComdatGroups.insert(CachedHashStringRef(N)).second);
753   }
754 
755   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols())
756     Symbols.push_back(createBitcodeSymbol<ELFT>(KeptComdats, ObjSym, this));
757 }
758 
759 template <template <class> class T>
760 static InputFile *createELFFile(MemoryBufferRef MB) {
761   unsigned char Size;
762   unsigned char Endian;
763   std::tie(Size, Endian) = getElfArchType(MB.getBuffer());
764   if (Endian != ELFDATA2LSB && Endian != ELFDATA2MSB)
765     fatal("invalid data encoding: " + MB.getBufferIdentifier());
766 
767   size_t BufSize = MB.getBuffer().size();
768   if ((Size == ELFCLASS32 && BufSize < sizeof(Elf32_Ehdr)) ||
769       (Size == ELFCLASS64 && BufSize < sizeof(Elf64_Ehdr)))
770     fatal("file is too short");
771 
772   InputFile *Obj;
773   if (Size == ELFCLASS32 && Endian == ELFDATA2LSB)
774     Obj = make<T<ELF32LE>>(MB);
775   else if (Size == ELFCLASS32 && Endian == ELFDATA2MSB)
776     Obj = make<T<ELF32BE>>(MB);
777   else if (Size == ELFCLASS64 && Endian == ELFDATA2LSB)
778     Obj = make<T<ELF64LE>>(MB);
779   else if (Size == ELFCLASS64 && Endian == ELFDATA2MSB)
780     Obj = make<T<ELF64BE>>(MB);
781   else
782     fatal("invalid file class: " + MB.getBufferIdentifier());
783 
784   if (!Config->FirstElf)
785     Config->FirstElf = Obj;
786   return Obj;
787 }
788 
789 template <class ELFT> void BinaryFile::parse() {
790   StringRef Buf = MB.getBuffer();
791   ArrayRef<uint8_t> Data =
792       makeArrayRef<uint8_t>((const uint8_t *)Buf.data(), Buf.size());
793 
794   std::string Filename = MB.getBufferIdentifier();
795   std::transform(Filename.begin(), Filename.end(), Filename.begin(),
796                  [](char C) { return isalnum(C) ? C : '_'; });
797   Filename = "_binary_" + Filename;
798   StringRef StartName = Saver.save(Twine(Filename) + "_start");
799   StringRef EndName = Saver.save(Twine(Filename) + "_end");
800   StringRef SizeName = Saver.save(Twine(Filename) + "_size");
801 
802   auto *Section =
803       make<InputSection<ELFT>>(SHF_ALLOC, SHT_PROGBITS, 8, Data, ".data");
804   Sections.push_back(Section);
805 
806   elf::Symtab<ELFT>::X->addRegular(StartName, STV_DEFAULT, STT_OBJECT, 0, 0,
807                                    STB_GLOBAL, Section);
808   elf::Symtab<ELFT>::X->addRegular(EndName, STV_DEFAULT, STT_OBJECT,
809                                    Data.size(), 0, STB_GLOBAL, Section);
810   elf::Symtab<ELFT>::X->addRegular(SizeName, STV_DEFAULT, STT_OBJECT,
811                                    Data.size(), 0, STB_GLOBAL, nullptr);
812 }
813 
814 static bool isBitcode(MemoryBufferRef MB) {
815   using namespace sys::fs;
816   return identify_magic(MB.getBuffer()) == file_magic::bitcode;
817 }
818 
819 InputFile *elf::createObjectFile(MemoryBufferRef MB, StringRef ArchiveName,
820                                  uint64_t OffsetInArchive) {
821   InputFile *F =
822       isBitcode(MB) ? make<BitcodeFile>(MB) : createELFFile<ObjectFile>(MB);
823   F->ArchiveName = ArchiveName;
824   F->OffsetInArchive = OffsetInArchive;
825   return F;
826 }
827 
828 InputFile *elf::createSharedFile(MemoryBufferRef MB) {
829   return createELFFile<SharedFile>(MB);
830 }
831 
832 MemoryBufferRef LazyObjectFile::getBuffer() {
833   if (Seen)
834     return MemoryBufferRef();
835   Seen = true;
836   return MB;
837 }
838 
839 template <class ELFT> void LazyObjectFile::parse() {
840   for (StringRef Sym : getSymbols())
841     Symtab<ELFT>::X->addLazyObject(Sym, *this);
842 }
843 
844 template <class ELFT> std::vector<StringRef> LazyObjectFile::getElfSymbols() {
845   typedef typename ELFT::Shdr Elf_Shdr;
846   typedef typename ELFT::Sym Elf_Sym;
847   typedef typename ELFT::SymRange Elf_Sym_Range;
848 
849   const ELFFile<ELFT> Obj(this->MB.getBuffer());
850   ArrayRef<Elf_Shdr> Sections = check(Obj.sections());
851   for (const Elf_Shdr &Sec : Sections) {
852     if (Sec.sh_type != SHT_SYMTAB)
853       continue;
854     Elf_Sym_Range Syms = check(Obj.symbols(&Sec));
855     uint32_t FirstNonLocal = Sec.sh_info;
856     StringRef StringTable = check(Obj.getStringTableForSymtab(Sec, Sections));
857     std::vector<StringRef> V;
858     for (const Elf_Sym &Sym : Syms.slice(FirstNonLocal))
859       if (Sym.st_shndx != SHN_UNDEF)
860         V.push_back(check(Sym.getName(StringTable)));
861     return V;
862   }
863   return {};
864 }
865 
866 std::vector<StringRef> LazyObjectFile::getBitcodeSymbols() {
867   std::unique_ptr<lto::InputFile> Obj = check(lto::InputFile::create(this->MB));
868   std::vector<StringRef> V;
869   for (const lto::InputFile::Symbol &Sym : Obj->symbols())
870     if (!(Sym.getFlags() & BasicSymbolRef::SF_Undefined))
871       V.push_back(Saver.save(Sym.getName()));
872   return V;
873 }
874 
875 // Returns a vector of globally-visible defined symbol names.
876 std::vector<StringRef> LazyObjectFile::getSymbols() {
877   if (isBitcode(this->MB))
878     return getBitcodeSymbols();
879 
880   unsigned char Size;
881   unsigned char Endian;
882   std::tie(Size, Endian) = getElfArchType(this->MB.getBuffer());
883   if (Size == ELFCLASS32) {
884     if (Endian == ELFDATA2LSB)
885       return getElfSymbols<ELF32LE>();
886     return getElfSymbols<ELF32BE>();
887   }
888   if (Endian == ELFDATA2LSB)
889     return getElfSymbols<ELF64LE>();
890   return getElfSymbols<ELF64BE>();
891 }
892 
893 template void ArchiveFile::parse<ELF32LE>();
894 template void ArchiveFile::parse<ELF32BE>();
895 template void ArchiveFile::parse<ELF64LE>();
896 template void ArchiveFile::parse<ELF64BE>();
897 
898 template void BitcodeFile::parse<ELF32LE>(DenseSet<CachedHashStringRef> &);
899 template void BitcodeFile::parse<ELF32BE>(DenseSet<CachedHashStringRef> &);
900 template void BitcodeFile::parse<ELF64LE>(DenseSet<CachedHashStringRef> &);
901 template void BitcodeFile::parse<ELF64BE>(DenseSet<CachedHashStringRef> &);
902 
903 template void LazyObjectFile::parse<ELF32LE>();
904 template void LazyObjectFile::parse<ELF32BE>();
905 template void LazyObjectFile::parse<ELF64LE>();
906 template void LazyObjectFile::parse<ELF64BE>();
907 
908 template class elf::ELFFileBase<ELF32LE>;
909 template class elf::ELFFileBase<ELF32BE>;
910 template class elf::ELFFileBase<ELF64LE>;
911 template class elf::ELFFileBase<ELF64BE>;
912 
913 template class elf::ObjectFile<ELF32LE>;
914 template class elf::ObjectFile<ELF32BE>;
915 template class elf::ObjectFile<ELF64LE>;
916 template class elf::ObjectFile<ELF64BE>;
917 
918 template class elf::SharedFile<ELF32LE>;
919 template class elf::SharedFile<ELF32BE>;
920 template class elf::SharedFile<ELF64LE>;
921 template class elf::SharedFile<ELF64BE>;
922 
923 template void BinaryFile::parse<ELF32LE>();
924 template void BinaryFile::parse<ELF32BE>();
925 template void BinaryFile::parse<ELF64LE>();
926 template void BinaryFile::parse<ELF64BE>();
927