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 "Error.h"
12 #include "InputSection.h"
13 #include "Symbols.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/Object/IRObjectFile.h"
18 #include "llvm/Support/raw_ostream.h"
19 
20 using namespace llvm;
21 using namespace llvm::ELF;
22 using namespace llvm::object;
23 using namespace llvm::sys::fs;
24 
25 using namespace lld;
26 using namespace lld::elf;
27 
28 template <class ELFT>
29 static ELFFile<ELFT> createELFObj(MemoryBufferRef MB) {
30   std::error_code EC;
31   ELFFile<ELFT> F(MB.getBuffer(), EC);
32   check(EC);
33   return F;
34 }
35 
36 template <class ELFT>
37 ELFFileBase<ELFT>::ELFFileBase(Kind K, MemoryBufferRef MB)
38     : InputFile(K, MB), ELFObj(createELFObj<ELFT>(MB)) {}
39 
40 template <class ELFT>
41 ELFKind ELFFileBase<ELFT>::getELFKind() {
42   if (ELFT::TargetEndianness == support::little)
43     return ELFT::Is64Bits ? ELF64LEKind : ELF32LEKind;
44   return ELFT::Is64Bits ? ELF64BEKind : ELF32BEKind;
45 }
46 
47 template <class ELFT>
48 typename ELFT::SymRange ELFFileBase<ELFT>::getElfSymbols(bool OnlyGlobals) {
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     fatal("invalid sh_info in symbol table");
56 
57   if (OnlyGlobals)
58     return make_range(Syms.begin() + FirstNonLocal, Syms.end());
59   return make_range(Syms.begin(), Syms.end());
60 }
61 
62 template <class ELFT>
63 uint32_t ELFFileBase<ELFT>::getSectionIndex(const Elf_Sym &Sym) const {
64   uint32_t I = Sym.st_shndx;
65   if (I == ELF::SHN_XINDEX)
66     return ELFObj.getExtendedSymbolTableIndex(&Sym, Symtab, SymtabSHNDX);
67   if (I >= ELF::SHN_LORESERVE)
68     return 0;
69   return I;
70 }
71 
72 template <class ELFT> void ELFFileBase<ELFT>::initStringTable() {
73   if (!Symtab)
74     return;
75   StringTable = check(ELFObj.getStringTableForSymtab(*Symtab));
76 }
77 
78 template <class ELFT>
79 elf::ObjectFile<ELFT>::ObjectFile(MemoryBufferRef M)
80     : ELFFileBase<ELFT>(Base::ObjectKind, M) {}
81 
82 template <class ELFT>
83 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getNonLocalSymbols() {
84   if (!this->Symtab)
85     return this->SymbolBodies;
86   uint32_t FirstNonLocal = this->Symtab->sh_info;
87   return makeArrayRef(this->SymbolBodies).slice(FirstNonLocal);
88 }
89 
90 template <class ELFT>
91 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getLocalSymbols() {
92   if (!this->Symtab)
93     return this->SymbolBodies;
94   uint32_t FirstNonLocal = this->Symtab->sh_info;
95   return makeArrayRef(this->SymbolBodies).slice(1, FirstNonLocal - 1);
96 }
97 
98 template <class ELFT>
99 ArrayRef<SymbolBody *> elf::ObjectFile<ELFT>::getSymbols() {
100   if (!this->Symtab)
101     return this->SymbolBodies;
102   return makeArrayRef(this->SymbolBodies).slice(1);
103 }
104 
105 template <class ELFT> uint32_t elf::ObjectFile<ELFT>::getMipsGp0() const {
106   if (MipsReginfo)
107     return MipsReginfo->Reginfo->ri_gp_value;
108   return 0;
109 }
110 
111 template <class ELFT>
112 void elf::ObjectFile<ELFT>::parse(DenseSet<StringRef> &ComdatGroups) {
113   // Read section and symbol tables.
114   initializeSections(ComdatGroups);
115   initializeSymbols();
116 }
117 
118 // Sections with SHT_GROUP and comdat bits define comdat section groups.
119 // They are identified and deduplicated by group name. This function
120 // returns a group name.
121 template <class ELFT>
122 StringRef elf::ObjectFile<ELFT>::getShtGroupSignature(const Elf_Shdr &Sec) {
123   const ELFFile<ELFT> &Obj = this->ELFObj;
124   uint32_t SymtabdSectionIndex = Sec.sh_link;
125   const Elf_Shdr *SymtabSec = check(Obj.getSection(SymtabdSectionIndex));
126   uint32_t SymIndex = Sec.sh_info;
127   const Elf_Sym *Sym = Obj.getSymbol(SymtabSec, SymIndex);
128   StringRef StringTable = check(Obj.getStringTableForSymtab(*SymtabSec));
129   return check(Sym->getName(StringTable));
130 }
131 
132 template <class ELFT>
133 ArrayRef<typename elf::ObjectFile<ELFT>::Elf_Word>
134 elf::ObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {
135   const ELFFile<ELFT> &Obj = this->ELFObj;
136   ArrayRef<Elf_Word> Entries =
137       check(Obj.template getSectionContentsAsArray<Elf_Word>(&Sec));
138   if (Entries.empty() || Entries[0] != GRP_COMDAT)
139     fatal("unsupported SHT_GROUP format");
140   return Entries.slice(1);
141 }
142 
143 template <class ELFT> static bool shouldMerge(const typename ELFT::Shdr &Sec) {
144   typedef typename ELFT::uint uintX_t;
145   uintX_t Flags = Sec.sh_flags;
146   if (!(Flags & SHF_MERGE))
147     return false;
148   if (Flags & SHF_WRITE)
149     fatal("writable SHF_MERGE sections are not supported");
150   uintX_t EntSize = Sec.sh_entsize;
151   if (!EntSize || Sec.sh_size % EntSize)
152     fatal("SHF_MERGE section size must be a multiple of sh_entsize");
153 
154   // Don't try to merge if the aligment is larger than the sh_entsize and this
155   // is not SHF_STRINGS.
156   //
157   // Since this is not a SHF_STRINGS, we would need to pad after every entity.
158   // It would be equivalent for the producer of the .o to just set a larger
159   // sh_entsize.
160   if (Flags & SHF_STRINGS)
161     return true;
162 
163   if (Sec.sh_addralign > EntSize)
164     return false;
165 
166   return true;
167 }
168 
169 template <class ELFT>
170 void elf::ObjectFile<ELFT>::initializeSections(
171     DenseSet<StringRef> &ComdatGroups) {
172   uint64_t Size = this->ELFObj.getNumSections();
173   Sections.resize(Size);
174   unsigned I = -1;
175   const ELFFile<ELFT> &Obj = this->ELFObj;
176   for (const Elf_Shdr &Sec : Obj.sections()) {
177     ++I;
178     if (Sections[I] == InputSection<ELFT>::Discarded)
179       continue;
180 
181     switch (Sec.sh_type) {
182     case SHT_GROUP:
183       Sections[I] = InputSection<ELFT>::Discarded;
184       if (ComdatGroups.insert(getShtGroupSignature(Sec)).second)
185         continue;
186       for (uint32_t SecIndex : getShtGroupEntries(Sec)) {
187         if (SecIndex >= Size)
188           fatal("invalid section index in group");
189         Sections[SecIndex] = InputSection<ELFT>::Discarded;
190       }
191       break;
192     case SHT_SYMTAB:
193       this->Symtab = &Sec;
194       break;
195     case SHT_SYMTAB_SHNDX:
196       this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
197       break;
198     case SHT_STRTAB:
199     case SHT_NULL:
200       break;
201     case SHT_RELA:
202     case SHT_REL: {
203       // This section contains relocation information.
204       // If -r is given, we do not interpret or apply relocation
205       // but just copy relocation sections to output.
206       if (Config->Relocatable) {
207         Sections[I] = new (Alloc) InputSection<ELFT>(this, &Sec);
208         break;
209       }
210 
211       // Find the relocation target section and associate this
212       // section with it.
213       InputSectionBase<ELFT> *Target = getRelocTarget(Sec);
214       if (!Target)
215         break;
216       if (auto *S = dyn_cast<InputSection<ELFT>>(Target)) {
217         S->RelocSections.push_back(&Sec);
218         break;
219       }
220       if (auto *S = dyn_cast<EHInputSection<ELFT>>(Target)) {
221         if (S->RelocSection)
222           fatal("multiple relocation sections to .eh_frame are not supported");
223         S->RelocSection = &Sec;
224         break;
225       }
226       fatal("relocations pointing to SHF_MERGE are not supported");
227     }
228     default:
229       Sections[I] = createInputSection(Sec);
230     }
231   }
232 }
233 
234 template <class ELFT>
235 InputSectionBase<ELFT> *
236 elf::ObjectFile<ELFT>::getRelocTarget(const Elf_Shdr &Sec) {
237   uint32_t Idx = Sec.sh_info;
238   if (Idx >= Sections.size())
239     fatal("invalid relocated section index");
240   InputSectionBase<ELFT> *Target = Sections[Idx];
241 
242   // Strictly speaking, a relocation section must be included in the
243   // group of the section it relocates. However, LLVM 3.3 and earlier
244   // would fail to do so, so we gracefully handle that case.
245   if (Target == InputSection<ELFT>::Discarded)
246     return nullptr;
247 
248   if (!Target)
249     fatal("unsupported relocation reference");
250   return Target;
251 }
252 
253 template <class ELFT>
254 InputSectionBase<ELFT> *
255 elf::ObjectFile<ELFT>::createInputSection(const Elf_Shdr &Sec) {
256   StringRef Name = check(this->ELFObj.getSectionName(&Sec));
257 
258   // .note.GNU-stack is a marker section to control the presence of
259   // PT_GNU_STACK segment in outputs. Since the presence of the segment
260   // is controlled only by the command line option (-z execstack) in LLD,
261   // .note.GNU-stack is ignored.
262   if (Name == ".note.GNU-stack")
263     return InputSection<ELFT>::Discarded;
264 
265   if (Name == ".note.GNU-split-stack")
266     error("objects using splitstacks are not supported");
267 
268   // A MIPS object file has a special section that contains register
269   // usage info, which needs to be handled by the linker specially.
270   if (Config->EMachine == EM_MIPS && Name == ".reginfo") {
271     MipsReginfo = new (Alloc) MipsReginfoInputSection<ELFT>(this, &Sec);
272     return MipsReginfo;
273   }
274 
275   // We dont need special handling of .eh_frame sections if relocatable
276   // output was choosen. Proccess them as usual input sections.
277   if (!Config->Relocatable && Name == ".eh_frame")
278     return new (EHAlloc.Allocate()) EHInputSection<ELFT>(this, &Sec);
279   if (shouldMerge<ELFT>(Sec))
280     return new (MAlloc.Allocate()) MergeInputSection<ELFT>(this, &Sec);
281   return new (Alloc) InputSection<ELFT>(this, &Sec);
282 }
283 
284 template <class ELFT> void elf::ObjectFile<ELFT>::initializeSymbols() {
285   this->initStringTable();
286   Elf_Sym_Range Syms = this->getElfSymbols(false);
287   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
288   SymbolBodies.reserve(NumSymbols);
289   for (const Elf_Sym &Sym : Syms)
290     SymbolBodies.push_back(createSymbolBody(&Sym));
291 }
292 
293 template <class ELFT>
294 InputSectionBase<ELFT> *
295 elf::ObjectFile<ELFT>::getSection(const Elf_Sym &Sym) const {
296   uint32_t Index = this->getSectionIndex(Sym);
297   if (Index == 0)
298     return nullptr;
299   if (Index >= Sections.size() || !Sections[Index])
300     fatal("invalid section index");
301   InputSectionBase<ELFT> *S = Sections[Index];
302   if (S == InputSectionBase<ELFT>::Discarded)
303     return S;
304   return S->Repl;
305 }
306 
307 template <class ELFT>
308 SymbolBody *elf::ObjectFile<ELFT>::createSymbolBody(const Elf_Sym *Sym) {
309   unsigned char Binding = Sym->getBinding();
310   InputSectionBase<ELFT> *Sec = getSection(*Sym);
311   if (Binding == STB_LOCAL) {
312     if (Sec == InputSection<ELFT>::Discarded)
313       Sec = nullptr;
314     return new (Alloc) DefinedRegular<ELFT>("", *Sym, Sec);
315   }
316 
317   StringRef Name = check(Sym->getName(this->StringTable));
318 
319   switch (Sym->st_shndx) {
320   case SHN_UNDEF:
321     return new (Alloc) UndefinedElf<ELFT>(Name, *Sym);
322   case SHN_COMMON:
323     return new (Alloc) DefinedCommon(Name, Sym->st_size, Sym->st_value,
324                                      Sym->getBinding() == llvm::ELF::STB_WEAK,
325                                      Sym->getVisibility());
326   }
327 
328   switch (Binding) {
329   default:
330     fatal("unexpected binding");
331   case STB_GLOBAL:
332   case STB_WEAK:
333   case STB_GNU_UNIQUE:
334     if (Sec == InputSection<ELFT>::Discarded)
335       return new (Alloc) UndefinedElf<ELFT>(Name, *Sym);
336     return new (Alloc) DefinedRegular<ELFT>(Name, *Sym, Sec);
337   }
338 }
339 
340 void ArchiveFile::parse() {
341   File = check(Archive::create(MB), "failed to parse archive");
342 
343   // Allocate a buffer for Lazy objects.
344   size_t NumSyms = File->getNumberOfSymbols();
345   LazySymbols.reserve(NumSyms);
346 
347   // Read the symbol table to construct Lazy objects.
348   for (const Archive::Symbol &Sym : File->symbols())
349     LazySymbols.emplace_back(this, Sym);
350 }
351 
352 // Returns a buffer pointing to a member file containing a given symbol.
353 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {
354   Archive::Child C =
355       check(Sym->getMember(),
356             "could not get the member for symbol " + Sym->getName());
357 
358   if (!Seen.insert(C.getChildOffset()).second)
359     return MemoryBufferRef();
360 
361   return check(C.getMemoryBufferRef(),
362                "could not get the buffer for the member defining symbol " +
363                    Sym->getName());
364 }
365 
366 template <class ELFT>
367 SharedFile<ELFT>::SharedFile(MemoryBufferRef M)
368     : ELFFileBase<ELFT>(Base::SharedKind, M), AsNeeded(Config->AsNeeded) {}
369 
370 template <class ELFT>
371 const typename ELFT::Shdr *
372 SharedFile<ELFT>::getSection(const Elf_Sym &Sym) const {
373   uint32_t Index = this->getSectionIndex(Sym);
374   if (Index == 0)
375     return nullptr;
376   return check(this->ELFObj.getSection(Index));
377 }
378 
379 // Partially parse the shared object file so that we can call
380 // getSoName on this object.
381 template <class ELFT> void SharedFile<ELFT>::parseSoName() {
382   typedef typename ELFT::Dyn Elf_Dyn;
383   typedef typename ELFT::uint uintX_t;
384   const Elf_Shdr *DynamicSec = nullptr;
385 
386   const ELFFile<ELFT> Obj = this->ELFObj;
387   for (const Elf_Shdr &Sec : Obj.sections()) {
388     switch (Sec.sh_type) {
389     default:
390       continue;
391     case SHT_DYNSYM:
392       this->Symtab = &Sec;
393       break;
394     case SHT_DYNAMIC:
395       DynamicSec = &Sec;
396       break;
397     case SHT_SYMTAB_SHNDX:
398       this->SymtabSHNDX = check(Obj.getSHNDXTable(Sec));
399       break;
400     }
401   }
402 
403   this->initStringTable();
404   SoName = this->getName();
405 
406   if (!DynamicSec)
407     return;
408   auto *Begin =
409       reinterpret_cast<const Elf_Dyn *>(Obj.base() + DynamicSec->sh_offset);
410   const Elf_Dyn *End = Begin + DynamicSec->sh_size / sizeof(Elf_Dyn);
411 
412   for (const Elf_Dyn &Dyn : make_range(Begin, End)) {
413     if (Dyn.d_tag == DT_SONAME) {
414       uintX_t Val = Dyn.getVal();
415       if (Val >= this->StringTable.size())
416         fatal("invalid DT_SONAME entry");
417       SoName = StringRef(this->StringTable.data() + Val);
418       return;
419     }
420   }
421 }
422 
423 // Fully parse the shared object file. This must be called after parseSoName().
424 template <class ELFT> void SharedFile<ELFT>::parseRest() {
425   Elf_Sym_Range Syms = this->getElfSymbols(true);
426   uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());
427   SymbolBodies.reserve(NumSymbols);
428   for (const Elf_Sym &Sym : Syms) {
429     StringRef Name = check(Sym.getName(this->StringTable));
430     if (Sym.isUndefined())
431       Undefs.push_back(Name);
432     else
433       SymbolBodies.emplace_back(this, Name, Sym);
434   }
435 }
436 
437 BitcodeFile::BitcodeFile(MemoryBufferRef M) : InputFile(BitcodeKind, M) {}
438 
439 bool BitcodeFile::classof(const InputFile *F) {
440   return F->kind() == BitcodeKind;
441 }
442 
443 static uint8_t getGvVisibility(const GlobalValue *GV) {
444   switch (GV->getVisibility()) {
445   case GlobalValue::DefaultVisibility:
446     return STV_DEFAULT;
447   case GlobalValue::HiddenVisibility:
448     return STV_HIDDEN;
449   case GlobalValue::ProtectedVisibility:
450     return STV_PROTECTED;
451   }
452   llvm_unreachable("unknown visibility");
453 }
454 
455 SymbolBody *
456 BitcodeFile::createSymbolBody(const DenseSet<const Comdat *> &KeptComdats,
457                               const IRObjectFile &Obj,
458                               const BasicSymbolRef &Sym) {
459   const GlobalValue *GV = Obj.getSymbolGV(Sym.getRawDataRefImpl());
460   assert(GV);
461   if (const Comdat *C = GV->getComdat())
462     if (!KeptComdats.count(C))
463       return nullptr;
464 
465   uint8_t Visibility = getGvVisibility(GV);
466 
467   SmallString<64> Name;
468   raw_svector_ostream OS(Name);
469   Sym.printName(OS);
470   StringRef NameRef = Saver.save(StringRef(Name));
471 
472   const Module &M = Obj.getModule();
473   SymbolBody *Body;
474   uint32_t Flags = Sym.getFlags();
475   bool IsWeak = Flags & BasicSymbolRef::SF_Weak;
476   if (Flags & BasicSymbolRef::SF_Undefined) {
477     Body = new (Alloc) Undefined(NameRef, IsWeak, Visibility, false);
478   } else if (Flags & BasicSymbolRef::SF_Common) {
479     const DataLayout &DL = M.getDataLayout();
480     uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
481     Body = new (Alloc)
482         DefinedCommon(NameRef, Size, GV->getAlignment(), IsWeak, Visibility);
483   } else {
484     Body = new (Alloc) DefinedBitcode(NameRef, IsWeak, Visibility);
485   }
486   Body->IsTls = GV->isThreadLocal();
487   return Body;
488 }
489 
490 bool BitcodeFile::shouldSkip(const BasicSymbolRef &Sym) {
491   uint32_t Flags = Sym.getFlags();
492   if (!(Flags & BasicSymbolRef::SF_Global))
493     return true;
494   if (Flags & BasicSymbolRef::SF_FormatSpecific)
495     return true;
496   return false;
497 }
498 
499 void BitcodeFile::parse(DenseSet<StringRef> &ComdatGroups) {
500   LLVMContext Context;
501   std::unique_ptr<IRObjectFile> Obj = check(IRObjectFile::create(MB, Context));
502   const Module &M = Obj->getModule();
503 
504   DenseSet<const Comdat *> KeptComdats;
505   for (const auto &P : M.getComdatSymbolTable()) {
506     StringRef N = Saver.save(P.first());
507     if (ComdatGroups.insert(N).second)
508       KeptComdats.insert(&P.second);
509   }
510 
511   for (const BasicSymbolRef &Sym : Obj->symbols())
512     if (!shouldSkip(Sym))
513       SymbolBodies.push_back(createSymbolBody(KeptComdats, *Obj, Sym));
514 }
515 
516 template <typename T>
517 static std::unique_ptr<InputFile> createELFFileAux(MemoryBufferRef MB) {
518   std::unique_ptr<T> Ret = llvm::make_unique<T>(MB);
519 
520   if (!Config->FirstElf)
521     Config->FirstElf = Ret.get();
522 
523   if (Config->EKind == ELFNoneKind) {
524     Config->EKind = Ret->getELFKind();
525     Config->EMachine = Ret->getEMachine();
526   }
527 
528   return std::move(Ret);
529 }
530 
531 template <template <class> class T>
532 static std::unique_ptr<InputFile> createELFFile(MemoryBufferRef MB) {
533   std::pair<unsigned char, unsigned char> Type = getElfArchType(MB.getBuffer());
534   if (Type.second != ELF::ELFDATA2LSB && Type.second != ELF::ELFDATA2MSB)
535     fatal("invalid data encoding: " + MB.getBufferIdentifier());
536 
537   if (Type.first == ELF::ELFCLASS32) {
538     if (Type.second == ELF::ELFDATA2LSB)
539       return createELFFileAux<T<ELF32LE>>(MB);
540     return createELFFileAux<T<ELF32BE>>(MB);
541   }
542   if (Type.first == ELF::ELFCLASS64) {
543     if (Type.second == ELF::ELFDATA2LSB)
544       return createELFFileAux<T<ELF64LE>>(MB);
545     return createELFFileAux<T<ELF64BE>>(MB);
546   }
547   fatal("invalid file class: " + MB.getBufferIdentifier());
548 }
549 
550 std::unique_ptr<InputFile> elf::createObjectFile(MemoryBufferRef MB,
551                                                  StringRef ArchiveName) {
552   using namespace sys::fs;
553   std::unique_ptr<InputFile> F;
554   if (identify_magic(MB.getBuffer()) == file_magic::bitcode)
555     F.reset(new BitcodeFile(MB));
556   else
557     F = createELFFile<ObjectFile>(MB);
558   F->ArchiveName = ArchiveName;
559   return F;
560 }
561 
562 std::unique_ptr<InputFile> elf::createSharedFile(MemoryBufferRef MB) {
563   return createELFFile<SharedFile>(MB);
564 }
565 
566 template class elf::ELFFileBase<ELF32LE>;
567 template class elf::ELFFileBase<ELF32BE>;
568 template class elf::ELFFileBase<ELF64LE>;
569 template class elf::ELFFileBase<ELF64BE>;
570 
571 template class elf::ObjectFile<ELF32LE>;
572 template class elf::ObjectFile<ELF32BE>;
573 template class elf::ObjectFile<ELF64LE>;
574 template class elf::ObjectFile<ELF64BE>;
575 
576 template class elf::SharedFile<ELF32LE>;
577 template class elf::SharedFile<ELF32BE>;
578 template class elf::SharedFile<ELF64LE>;
579 template class elf::SharedFile<ELF64BE>;
580