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