1 //===- InputFiles.cpp -----------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "InputFiles.h"
11 #include "InputSection.h"
12 #include "Error.h"
13 #include "Symbols.h"
14 #include "llvm/ADT/STLExtras.h"
15 
16 using namespace llvm;
17 using namespace llvm::ELF;
18 using namespace llvm::object;
19 using namespace llvm::sys::fs;
20 
21 using namespace lld;
22 using namespace lld::elf2;
23 
24 namespace {
25 class ECRAII {
26   std::error_code EC;
27 
28 public:
29   std::error_code &getEC() { return EC; }
30   ~ECRAII() { error(EC); }
31 };
32 }
33 
34 template <class ELFT>
35 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef M)
36     : InputFile(K, M), ELFObj(MB.getBuffer(), ECRAII().getEC()) {}
37 
38 template <class ELFT>
39 typename ELFFileBase<ELFT>::Elf_Sym_Range
40 ELFFileBase<ELFT>::getSymbolsHelper(bool Local) {
41   if (!Symtab)
42     return Elf_Sym_Range(nullptr, nullptr);
43   Elf_Sym_Range Syms = ELFObj.symbols(Symtab);
44   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
45   uint32_t FirstNonLocal = Symtab->sh_info;
46   if (FirstNonLocal > NumSymbols)
47     error("Invalid sh_info in symbol table");
48   if (!Local)
49     return make_range(Syms.begin() + FirstNonLocal, Syms.end());
50   // +1 to skip over dummy symbol.
51   return make_range(Syms.begin() + 1, Syms.begin() + FirstNonLocal);
52 }
53 
54 template <class ELFT>
55 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
56   uint32_t Index = Sym.st_shndx;
57   if (Index == ELF::SHN_XINDEX)
58     Index = this->ELFObj.getExtendedSymbolTableIndex(&Sym, this->Symtab,
59                                                      SymtabSHNDX);
60   else if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
61     return 0;
62 
63   if (!Index)
64     error("Invalid section index");
65   return Index;
66 }
67 
68 template <class ELFT> void ELFFileBase<ELFT>::initStringTable() {
69   if (!Symtab)
70     return;
71   ErrorOr<StringRef> StringTableOrErr = ELFObj.getStringTableForSymtab(*Symtab);
72   error(StringTableOrErr.getError());
73   StringTable = *StringTableOrErr;
74 }
75 
76 template <class ELFT>
77 typename ELFFileBase<ELFT>::Elf_Sym_Range
78 ELFFileBase<ELFT>::getNonLocalSymbols() {
79   return getSymbolsHelper(false);
80 }
81 
82 template <class ELFT>
83 ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M)
84     : ELFFileBase<ELFT>(Base::ObjectKind, M) {}
85 
86 template <class ELFT>
87 typename ObjectFile<ELFT>::Elf_Sym_Range ObjectFile<ELFT>::getLocalSymbols() {
88   return this->getSymbolsHelper(true);
89 }
90 
91 template <class ELFT>
92 const typename ObjectFile<ELFT>::Elf_Sym *
93 ObjectFile<ELFT>::getLocalSymbol(uintX_t SymIndex) {
94   uint32_t FirstNonLocal = this->Symtab->sh_info;
95   if (SymIndex >= FirstNonLocal)
96     return nullptr;
97   Elf_Sym_Range Syms = this->ELFObj.symbols(this->Symtab);
98   return Syms.begin() + SymIndex;
99 }
100 
101 template <class ELFT>
102 void elf2::ObjectFile<ELFT>::parse(DenseSet<StringRef> &Comdats) {
103   // Read section and symbol tables.
104   initializeSections(Comdats);
105   initializeSymbols();
106 }
107 
108 template <class ELFT>
109 StringRef ObjectFile<ELFT>::getShtGroupSignature(const Elf_Shdr &Sec) {
110   const ELFFile<ELFT> &Obj = this->ELFObj;
111   uint32_t SymtabdSectionIndex = Sec.sh_link;
112   ErrorOr<const Elf_Shdr *> SecOrErr = Obj.getSection(SymtabdSectionIndex);
113   error(SecOrErr);
114   const Elf_Shdr *SymtabSec = *SecOrErr;
115   uint32_t SymIndex = Sec.sh_info;
116   const Elf_Sym *Sym = Obj.getSymbol(SymtabSec, SymIndex);
117   ErrorOr<StringRef> StringTableOrErr = Obj.getStringTableForSymtab(*SymtabSec);
118   error(StringTableOrErr);
119   ErrorOr<StringRef> SignatureOrErr = Sym->getName(*StringTableOrErr);
120   error(SignatureOrErr);
121   return *SignatureOrErr;
122 }
123 
124 template <class ELFT>
125 ArrayRef<typename ObjectFile<ELFT>::GroupEntryType>
126 ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
127   const ELFFile<ELFT> &Obj = this->ELFObj;
128   ErrorOr<ArrayRef<GroupEntryType>> EntriesOrErr =
129       Obj.template getSectionContentsAsArray<GroupEntryType>(&Sec);
130   error(EntriesOrErr.getError());
131   ArrayRef<GroupEntryType> Entries = *EntriesOrErr;
132   if (Entries.empty() || Entries[0] != GRP_COMDAT)
133     error("Unsupported SHT_GROUP format");
134   return Entries.slice(1);
135 }
136 
137 template <class ELFT>
138 static bool shouldMerge(const typename ELFFile<ELFT>::Elf_Shdr &Sec) {
139   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
140   uintX_t Flags = Sec.sh_flags;
141   if (!(Flags & SHF_MERGE))
142     return false;
143   if (Flags & SHF_WRITE)
144     error("Writable SHF_MERGE sections are not supported");
145   uintX_t EntSize = Sec.sh_entsize;
146   if (!EntSize || Sec.sh_size % EntSize)
147     error("SHF_MERGE section size must be a multiple of sh_entsize");
148 
149   // Don't try to merge if the aligment is larger than the sh_entsize.
150   //
151   // If this is not a SHF_STRINGS, we would need to pad after every entity. It
152   // would be equivalent for the producer of the .o to just set a larger
153   // sh_entsize.
154   //
155   // If this is a SHF_STRINGS, the larger alignment makes sense. Unfortunately
156   // it would complicate tail merging. This doesn't seem that common to
157   // justify the effort.
158   if (Sec.sh_addralign > EntSize)
159     return false;
160 
161   return true;
162 }
163 
164 template <class ELFT>
165 void elf2::ObjectFile<ELFT>::initializeSections(DenseSet<StringRef> &Comdats) {
166   uint64_t Size = this->ELFObj.getNumSections();
167   Sections.resize(Size);
168   unsigned I = -1;
169   const ELFFile<ELFT> &Obj = this->ELFObj;
170   for (const Elf_Shdr &Sec : Obj.sections()) {
171     ++I;
172     if (Sections[I] == &InputSection<ELFT>::Discarded)
173       continue;
174 
175     switch (Sec.sh_type) {
176     case SHT_GROUP:
177       Sections[I] = &InputSection<ELFT>::Discarded;
178       if (Comdats.insert(getShtGroupSignature(Sec)).second)
179         continue;
180       for (GroupEntryType E : getShtGroupEntries(Sec)) {
181         uint32_t SecIndex = E;
182         if (SecIndex >= Size)
183           error("Invalid section index in group");
184         Sections[SecIndex] = &InputSection<ELFT>::Discarded;
185       }
186       break;
187     case SHT_SYMTAB:
188       this->Symtab = &Sec;
189       break;
190     case SHT_SYMTAB_SHNDX: {
191       ErrorOr<ArrayRef<Elf_Word>> ErrorOrTable = Obj.getSHNDXTable(Sec);
192       error(ErrorOrTable);
193       this->SymtabSHNDX = *ErrorOrTable;
194       break;
195     }
196     case SHT_STRTAB:
197     case SHT_NULL:
198       break;
199     case SHT_RELA:
200     case SHT_REL: {
201       uint32_t RelocatedSectionIndex = Sec.sh_info;
202       if (RelocatedSectionIndex >= Size)
203         error("Invalid relocated section index");
204       InputSectionBase<ELFT> *RelocatedSection =
205           Sections[RelocatedSectionIndex];
206       if (!RelocatedSection)
207         error("Unsupported relocation reference");
208       if (auto *S = dyn_cast<InputSection<ELFT>>(RelocatedSection)) {
209         S->RelocSections.push_back(&Sec);
210       } else if (auto *S = dyn_cast<EHInputSection<ELFT>>(RelocatedSection)) {
211         if (S->RelocSection)
212           error("Multiple relocation sections to .eh_frame are not supported");
213         S->RelocSection = &Sec;
214       } else {
215         error("Relocations pointing to SHF_MERGE are not supported");
216       }
217       break;
218     }
219     default: {
220       ErrorOr<StringRef> NameOrErr = this->ELFObj.getSectionName(&Sec);
221       error(NameOrErr);
222       if (*NameOrErr == ".eh_frame")
223         Sections[I] = new (this->Alloc) EHInputSection<ELFT>(this, &Sec);
224       else if (shouldMerge<ELFT>(Sec))
225         Sections[I] = new (this->Alloc) MergeInputSection<ELFT>(this, &Sec);
226       else
227         Sections[I] = new (this->Alloc) InputSection<ELFT>(this, &Sec);
228       break;
229     }
230     }
231   }
232 }
233 
234 template <class ELFT> void elf2::ObjectFile<ELFT>::initializeSymbols() {
235   this->initStringTable();
236   Elf_Sym_Range Syms = this->getNonLocalSymbols();
237   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
238   this->SymbolBodies.reserve(NumSymbols);
239   for (const Elf_Sym &Sym : Syms)
240     this->SymbolBodies.push_back(createSymbolBody(this->StringTable, &Sym));
241 }
242 
243 template <class ELFT>
244 InputSectionBase<ELFT> *
245 elf2::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
246   uint32_t Index = this->getSectionIndex(Sym);
247   if (Index == 0)
248     return nullptr;
249   if (Index >= Sections.size() || !Sections[Index])
250     error("Invalid section index");
251   return Sections[Index];
252 }
253 
254 template <class ELFT>
255 SymbolBody *elf2::ObjectFile<ELFT>::createSymbolBody(StringRef StringTable,
256                                                      const Elf_Sym *Sym) {
257   ErrorOr<StringRef> NameOrErr = Sym->getName(StringTable);
258   error(NameOrErr.getError());
259   StringRef Name = *NameOrErr;
260 
261   switch (Sym->st_shndx) {
262   case SHN_ABS:
263     return new (this->Alloc) DefinedAbsolute<ELFT>(Name, *Sym);
264   case SHN_UNDEF:
265     return new (this->Alloc) Undefined<ELFT>(Name, *Sym);
266   case SHN_COMMON:
267     return new (this->Alloc) DefinedCommon<ELFT>(Name, *Sym);
268   }
269 
270   switch (Sym->getBinding()) {
271   default:
272     error("unexpected binding");
273   case STB_GLOBAL:
274   case STB_WEAK:
275   case STB_GNU_UNIQUE: {
276     InputSectionBase<ELFT> *Sec = getSection(*Sym);
277     if (Sec == &InputSection<ELFT>::Discarded)
278       return new (this->Alloc) Undefined<ELFT>(Name, *Sym);
279     return new (this->Alloc) DefinedRegular<ELFT>(Name, *Sym, *Sec);
280   }
281   }
282 }
283 
284 static std::unique_ptr<Archive> openArchive(MemoryBufferRef MB) {
285   ErrorOr<std::unique_ptr<Archive>> ArchiveOrErr = Archive::create(MB);
286   error(ArchiveOrErr, "Failed to parse archive");
287   return std::move(*ArchiveOrErr);
288 }
289 
290 void ArchiveFile::parse() {
291   File = openArchive(MB);
292 
293   // Allocate a buffer for Lazy objects.
294   size_t NumSyms = File->getNumberOfSymbols();
295   LazySymbols.reserve(NumSyms);
296 
297   // Read the symbol table to construct Lazy objects.
298   for (const Archive::Symbol &Sym : File->symbols())
299     LazySymbols.emplace_back(this, Sym);
300 }
301 
302 // Returns a buffer pointing to a member file containing a given symbol.
303 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {
304   ErrorOr<Archive::Child> COrErr = Sym->getMember();
305   error(COrErr, "Could not get the member for symbol " + Sym->getName());
306   const Archive::Child &C = *COrErr;
307 
308   if (!Seen.insert(C.getChildOffset()).second)
309     return MemoryBufferRef();
310 
311   ErrorOr<MemoryBufferRef> Ret = C.getMemoryBufferRef();
312   error(Ret, "Could not get the buffer for the member defining symbol " +
313                  Sym->getName());
314   return *Ret;
315 }
316 
317 std::vector<MemoryBufferRef> ArchiveFile::getMembers() {
318   File = openArchive(MB);
319 
320   std::vector<MemoryBufferRef> Result;
321   for (auto &ChildOrErr : File->children()) {
322     error(ChildOrErr,
323           "Could not get the child of the archive " + File->getFileName());
324     const Archive::Child Child(*ChildOrErr);
325     ErrorOr<MemoryBufferRef> MbOrErr = Child.getMemoryBufferRef();
326     error(MbOrErr, "Could not get the buffer for a child of the archive " +
327                        File->getFileName());
328     Result.push_back(MbOrErr.get());
329   }
330   return Result;
331 }
332 
333 template <class ELFT>
334 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
335     : ELFFileBase<ELFT>(Base::SharedKind, M) {
336   AsNeeded = Config->AsNeeded;
337 }
338 
339 template <class ELFT>
340 const typename ELFFile<ELFT>::Elf_Shdr *
341 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
342   uint32_t Index = this->getSectionIndex(Sym);
343   if (Index == 0)
344     return nullptr;
345   ErrorOr<const Elf_Shdr *> Ret = this->ELFObj.getSection(Index);
346   error(Ret);
347   return *Ret;
348 }
349 
350 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
351   typedef typename ELFFile<ELFT>::Elf_Dyn Elf_Dyn;
352   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
353   const Elf_Shdr *DynamicSec = nullptr;
354 
355   const ELFFile<ELFT> Obj = this->ELFObj;
356   for (const Elf_Shdr &Sec : Obj.sections()) {
357     switch (Sec.sh_type) {
358     default:
359       continue;
360     case SHT_DYNSYM:
361       this->Symtab = &Sec;
362       break;
363     case SHT_DYNAMIC:
364       DynamicSec = &Sec;
365       break;
366     case SHT_SYMTAB_SHNDX: {
367       ErrorOr<ArrayRef<Elf_Word>> ErrorOrTable = Obj.getSHNDXTable(Sec);
368       error(ErrorOrTable);
369       this->SymtabSHNDX = *ErrorOrTable;
370       break;
371     }
372     }
373   }
374 
375   this->initStringTable();
376   this->SoName = this->getName();
377 
378   if (!DynamicSec)
379     return;
380   auto *Begin =
381       reinterpret_cast<const Elf_Dyn *>(Obj.base() + DynamicSec->sh_offset);
382   const Elf_Dyn *End = Begin + DynamicSec->sh_size / sizeof(Elf_Dyn);
383 
384   for (const Elf_Dyn &Dyn : make_range(Begin, End)) {
385     if (Dyn.d_tag == DT_SONAME) {
386       uintX_t Val = Dyn.getVal();
387       if (Val >= this->StringTable.size())
388         error("Invalid DT_SONAME entry");
389       this->SoName = StringRef(this->StringTable.data() + Val);
390       return;
391     }
392   }
393 }
394 
395 template <class ELFT> void SharedFile<ELFT>::parse() {
396   Elf_Sym_Range Syms = this->getNonLocalSymbols();
397   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
398   SymbolBodies.reserve(NumSymbols);
399   for (const Elf_Sym &Sym : Syms) {
400     ErrorOr<StringRef> NameOrErr = Sym.getName(this->StringTable);
401     error(NameOrErr.getError());
402     StringRef Name = *NameOrErr;
403 
404     if (Sym.isUndefined())
405       Undefs.push_back(Name);
406     else
407       SymbolBodies.emplace_back(this, Name, Sym);
408   }
409 }
410 
411 template <typename T>
412 static std::unique_ptr<InputFile> createELFFileAux(MemoryBufferRef MB) {
413   std::unique_ptr<T> Ret = llvm::make_unique<T>(MB);
414 
415   if (!Config->FirstElf)
416     Config->FirstElf = Ret.get();
417 
418   if (Config->EKind == ELFNoneKind) {
419     Config->EKind = Ret->getELFKind();
420     Config->EMachine = Ret->getEMachine();
421   }
422 
423   return std::move(Ret);
424 }
425 
426 template <template <class> class T>
427 std::unique_ptr<InputFile> lld::elf2::createELFFile(MemoryBufferRef MB) {
428   using namespace llvm;
429 
430   std::pair<unsigned char, unsigned char> Type =
431     object::getElfArchType(MB.getBuffer());
432   if (Type.second != ELF::ELFDATA2LSB && Type.second != ELF::ELFDATA2MSB)
433     error("Invalid data encoding: " + MB.getBufferIdentifier());
434 
435   if (Type.first == ELF::ELFCLASS32) {
436     if (Type.second == ELF::ELFDATA2LSB)
437       return createELFFileAux<T<object::ELF32LE>>(MB);
438     return createELFFileAux<T<object::ELF32BE>>(MB);
439   }
440   if (Type.first == ELF::ELFCLASS64) {
441     if (Type.second == ELF::ELFDATA2LSB)
442       return createELFFileAux<T<object::ELF64LE>>(MB);
443     return createELFFileAux<T<object::ELF64BE>>(MB);
444   }
445   error("Invalid file class: " + MB.getBufferIdentifier());
446 }
447 
448 namespace lld {
449 namespace elf2 {
450 template class ELFFileBase<llvm::object::ELF32LE>;
451 template class ELFFileBase<llvm::object::ELF32BE>;
452 template class ELFFileBase<llvm::object::ELF64LE>;
453 template class ELFFileBase<llvm::object::ELF64BE>;
454 
455 template class ObjectFile<llvm::object::ELF32LE>;
456 template class ObjectFile<llvm::object::ELF32BE>;
457 template class ObjectFile<llvm::object::ELF64LE>;
458 template class ObjectFile<llvm::object::ELF64BE>;
459 
460 template class SharedFile<llvm::object::ELF32LE>;
461 template class SharedFile<llvm::object::ELF32BE>;
462 template class SharedFile<llvm::object::ELF64LE>;
463 template class SharedFile<llvm::object::ELF64BE>;
464 
465 template std::unique_ptr<InputFile> createELFFile<ObjectFile>(MemoryBufferRef);
466 template std::unique_ptr<InputFile> createELFFile<SharedFile>(MemoryBufferRef);
467 }
468 }
469