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
211         error("Relocations pointing to SHF_MERGE are not supported");
212       break;
213     }
214     default:
215       if (shouldMerge<ELFT>(Sec))
216         Sections[I] = new (this->Alloc) MergeInputSection<ELFT>(this, &Sec);
217       else
218         Sections[I] = new (this->Alloc) InputSection<ELFT>(this, &Sec);
219       break;
220     }
221   }
222 }
223 
224 template <class ELFT> void elf2::ObjectFile<ELFT>::initializeSymbols() {
225   this->initStringTable();
226   Elf_Sym_Range Syms = this->getNonLocalSymbols();
227   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
228   this->SymbolBodies.reserve(NumSymbols);
229   for (const Elf_Sym &Sym : Syms)
230     this->SymbolBodies.push_back(createSymbolBody(this->StringTable, &Sym));
231 }
232 
233 template <class ELFT>
234 InputSectionBase<ELFT> *
235 elf2::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
236   uint32_t Index = this->getSectionIndex(Sym);
237   if (Index == 0)
238     return nullptr;
239   if (Index >= Sections.size() || !Sections[Index])
240     error("Invalid section index");
241   return Sections[Index];
242 }
243 
244 template <class ELFT>
245 SymbolBody *elf2::ObjectFile<ELFT>::createSymbolBody(StringRef StringTable,
246                                                      const Elf_Sym *Sym) {
247   ErrorOr<StringRef> NameOrErr = Sym->getName(StringTable);
248   error(NameOrErr.getError());
249   StringRef Name = *NameOrErr;
250 
251   switch (Sym->st_shndx) {
252   case SHN_ABS:
253     return new (this->Alloc) DefinedAbsolute<ELFT>(Name, *Sym);
254   case SHN_UNDEF:
255     return new (this->Alloc) Undefined<ELFT>(Name, *Sym);
256   case SHN_COMMON:
257     return new (this->Alloc) DefinedCommon<ELFT>(Name, *Sym);
258   }
259 
260   switch (Sym->getBinding()) {
261   default:
262     error("unexpected binding");
263   case STB_GLOBAL:
264   case STB_WEAK:
265   case STB_GNU_UNIQUE: {
266     InputSectionBase<ELFT> *Sec = getSection(*Sym);
267     if (Sec == &InputSection<ELFT>::Discarded)
268       return new (this->Alloc) Undefined<ELFT>(Name, *Sym);
269     return new (this->Alloc) DefinedRegular<ELFT>(Name, *Sym, *Sec);
270   }
271   }
272 }
273 
274 static std::unique_ptr<Archive> openArchive(MemoryBufferRef MB) {
275   ErrorOr<std::unique_ptr<Archive>> ArchiveOrErr = Archive::create(MB);
276   error(ArchiveOrErr, "Failed to parse archive");
277   return std::move(*ArchiveOrErr);
278 }
279 
280 void ArchiveFile::parse() {
281   File = openArchive(MB);
282 
283   // Allocate a buffer for Lazy objects.
284   size_t NumSyms = File->getNumberOfSymbols();
285   LazySymbols.reserve(NumSyms);
286 
287   // Read the symbol table to construct Lazy objects.
288   for (const Archive::Symbol &Sym : File->symbols())
289     LazySymbols.emplace_back(this, Sym);
290 }
291 
292 // Returns a buffer pointing to a member file containing a given symbol.
293 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {
294   ErrorOr<Archive::Child> COrErr = Sym->getMember();
295   error(COrErr, "Could not get the member for symbol " + Sym->getName());
296   const Archive::Child &C = *COrErr;
297 
298   if (!Seen.insert(C.getChildOffset()).second)
299     return MemoryBufferRef();
300 
301   ErrorOr<MemoryBufferRef> Ret = C.getMemoryBufferRef();
302   error(Ret, "Could not get the buffer for the member defining symbol " +
303                  Sym->getName());
304   return *Ret;
305 }
306 
307 std::vector<MemoryBufferRef> ArchiveFile::getMembers() {
308   File = openArchive(MB);
309 
310   std::vector<MemoryBufferRef> Result;
311   for (auto &ChildOrErr : File->children()) {
312     error(ChildOrErr,
313           "Could not get the child of the archive " + File->getFileName());
314     const Archive::Child Child(*ChildOrErr);
315     ErrorOr<MemoryBufferRef> MbOrErr = Child.getMemoryBufferRef();
316     error(MbOrErr, "Could not get the buffer for a child of the archive " +
317                        File->getFileName());
318     Result.push_back(MbOrErr.get());
319   }
320   return Result;
321 }
322 
323 template <class ELFT>
324 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
325     : ELFFileBase<ELFT>(Base::SharedKind, M) {
326   AsNeeded = Config->AsNeeded;
327 }
328 
329 template <class ELFT>
330 const typename ELFFile<ELFT>::Elf_Shdr *
331 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
332   uint32_t Index = this->getSectionIndex(Sym);
333   if (Index == 0)
334     return nullptr;
335   ErrorOr<const Elf_Shdr *> Ret = this->ELFObj.getSection(Index);
336   error(Ret);
337   return *Ret;
338 }
339 
340 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
341   typedef typename ELFFile<ELFT>::Elf_Dyn Elf_Dyn;
342   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
343   const Elf_Shdr *DynamicSec = nullptr;
344 
345   const ELFFile<ELFT> Obj = this->ELFObj;
346   for (const Elf_Shdr &Sec : Obj.sections()) {
347     switch (Sec.sh_type) {
348     default:
349       continue;
350     case SHT_DYNSYM:
351       this->Symtab = &Sec;
352       break;
353     case SHT_DYNAMIC:
354       DynamicSec = &Sec;
355       break;
356     case SHT_SYMTAB_SHNDX: {
357       ErrorOr<ArrayRef<Elf_Word>> ErrorOrTable = Obj.getSHNDXTable(Sec);
358       error(ErrorOrTable);
359       this->SymtabSHNDX = *ErrorOrTable;
360       break;
361     }
362     }
363   }
364 
365   this->initStringTable();
366   this->SoName = this->getName();
367 
368   if (!DynamicSec)
369     return;
370   auto *Begin =
371       reinterpret_cast<const Elf_Dyn *>(Obj.base() + DynamicSec->sh_offset);
372   const Elf_Dyn *End = Begin + DynamicSec->sh_size / sizeof(Elf_Dyn);
373 
374   for (const Elf_Dyn &Dyn : make_range(Begin, End)) {
375     if (Dyn.d_tag == DT_SONAME) {
376       uintX_t Val = Dyn.getVal();
377       if (Val >= this->StringTable.size())
378         error("Invalid DT_SONAME entry");
379       this->SoName = StringRef(this->StringTable.data() + Val);
380       return;
381     }
382   }
383 }
384 
385 template <class ELFT> void SharedFile<ELFT>::parse() {
386   Elf_Sym_Range Syms = this->getNonLocalSymbols();
387   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
388   SymbolBodies.reserve(NumSymbols);
389   for (const Elf_Sym &Sym : Syms) {
390     ErrorOr<StringRef> NameOrErr = Sym.getName(this->StringTable);
391     error(NameOrErr.getError());
392     StringRef Name = *NameOrErr;
393 
394     if (Sym.isUndefined())
395       Undefs.push_back(Name);
396     else
397       SymbolBodies.emplace_back(this, Name, Sym);
398   }
399 }
400 
401 template <typename T>
402 static std::unique_ptr<InputFile> createELFFileAux(MemoryBufferRef MB) {
403   std::unique_ptr<T> Ret = llvm::make_unique<T>(MB);
404 
405   if (!Config->FirstElf)
406     Config->FirstElf = Ret.get();
407 
408   if (Config->EKind == ELFNoneKind) {
409     Config->EKind = Ret->getELFKind();
410     Config->EMachine = Ret->getEMachine();
411   }
412 
413   return std::move(Ret);
414 }
415 
416 template <template <class> class T>
417 std::unique_ptr<InputFile> lld::elf2::createELFFile(MemoryBufferRef MB) {
418   using namespace llvm;
419 
420   std::pair<unsigned char, unsigned char> Type =
421     object::getElfArchType(MB.getBuffer());
422   if (Type.second != ELF::ELFDATA2LSB && Type.second != ELF::ELFDATA2MSB)
423     error("Invalid data encoding: " + MB.getBufferIdentifier());
424 
425   if (Type.first == ELF::ELFCLASS32) {
426     if (Type.second == ELF::ELFDATA2LSB)
427       return createELFFileAux<T<object::ELF32LE>>(MB);
428     return createELFFileAux<T<object::ELF32BE>>(MB);
429   }
430   if (Type.first == ELF::ELFCLASS64) {
431     if (Type.second == ELF::ELFDATA2LSB)
432       return createELFFileAux<T<object::ELF64LE>>(MB);
433     return createELFFileAux<T<object::ELF64BE>>(MB);
434   }
435   error("Invalid file class: " + MB.getBufferIdentifier());
436 }
437 
438 namespace lld {
439 namespace elf2 {
440 template class ELFFileBase<llvm::object::ELF32LE>;
441 template class ELFFileBase<llvm::object::ELF32BE>;
442 template class ELFFileBase<llvm::object::ELF64LE>;
443 template class ELFFileBase<llvm::object::ELF64BE>;
444 
445 template class ObjectFile<llvm::object::ELF32LE>;
446 template class ObjectFile<llvm::object::ELF32BE>;
447 template class ObjectFile<llvm::object::ELF64LE>;
448 template class ObjectFile<llvm::object::ELF64BE>;
449 
450 template class SharedFile<llvm::object::ELF32LE>;
451 template class SharedFile<llvm::object::ELF32BE>;
452 template class SharedFile<llvm::object::ELF64LE>;
453 template class SharedFile<llvm::object::ELF64BE>;
454 
455 template std::unique_ptr<InputFile> createELFFile<ObjectFile>(MemoryBufferRef);
456 template std::unique_ptr<InputFile> createELFFile<SharedFile>(MemoryBufferRef);
457 }
458 }
459