c78e1dbe774076b02bc0ab8b86da206336214bbf
[oota-llvm.git] / tools / yaml2obj / yaml2elf.cpp
1 //===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief The ELF component of yaml2obj.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #include "yaml2obj.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/Object/ELFObjectFile.h"
18 #include "llvm/Object/ELFYAML.h"
19 #include "llvm/Support/ELF.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/YAMLTraits.h"
22 #include "llvm/Support/raw_ostream.h"
23
24 using namespace llvm;
25
26 // There is similar code in yaml2coff, but with some slight COFF-specific
27 // variations like different initial state. Might be able to deduplicate
28 // some day, but also want to make sure that the Mach-O use case is served.
29 //
30 // This class has a deliberately small interface, since a lot of
31 // implementation variation is possible.
32 //
33 // TODO: Use the StringTable builder from lib/Object instead, since it
34 // will deduplicate suffixes.
35 namespace {
36 class StringTableBuilder {
37   /// \brief Indices of strings currently present in `Buf`.
38   StringMap<unsigned> StringIndices;
39   /// \brief The contents of the string table as we build it.
40   std::string Buf;
41 public:
42   StringTableBuilder() {
43     Buf.push_back('\0');
44   }
45   /// \returns Index of string in string table.
46   unsigned addString(StringRef S) {
47     StringMapEntry<unsigned> &Entry = StringIndices.GetOrCreateValue(S);
48     unsigned &I = Entry.getValue();
49     if (I != 0)
50       return I;
51     I = Buf.size();
52     Buf.append(S.begin(), S.end());
53     Buf.push_back('\0');
54     return I;
55   }
56   size_t size() const {
57     return Buf.size();
58   }
59   void writeToStream(raw_ostream &OS) {
60     OS.write(Buf.data(), Buf.size());
61   }
62 };
63 } // end anonymous namespace
64
65 // This class is used to build up a contiguous binary blob while keeping
66 // track of an offset in the output (which notionally begins at
67 // `InitialOffset`).
68 namespace {
69 class ContiguousBlobAccumulator {
70   const uint64_t InitialOffset;
71   SmallVector<char, 128> Buf;
72   raw_svector_ostream OS;
73
74   /// \returns The new offset.
75   uint64_t padToAlignment(unsigned Align) {
76     uint64_t CurrentOffset = InitialOffset + OS.tell();
77     uint64_t AlignedOffset = RoundUpToAlignment(CurrentOffset, Align);
78     for (; CurrentOffset != AlignedOffset; ++CurrentOffset)
79       OS.write('\0');
80     return AlignedOffset; // == CurrentOffset;
81   }
82
83 public:
84   ContiguousBlobAccumulator(uint64_t InitialOffset_)
85       : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
86   template <class Integer>
87   raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align = 16) {
88     Offset = padToAlignment(Align);
89     return OS;
90   }
91   void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
92 };
93 } // end anonymous namespace
94
95 // Used to keep track of section and symbol names, so that in the YAML file
96 // sections and symbols can be referenced by name instead of by index.
97 namespace {
98 class NameToIdxMap {
99   StringMap<int> Map;
100 public:
101   /// \returns true if name is already present in the map.
102   bool addName(StringRef Name, unsigned i) {
103     StringMapEntry<int> &Entry = Map.GetOrCreateValue(Name, -1);
104     if (Entry.getValue() != -1)
105       return true;
106     Entry.setValue((int)i);
107     return false;
108   }
109   /// \returns true if name is not present in the map
110   bool lookup(StringRef Name, unsigned &Idx) const {
111     StringMap<int>::const_iterator I = Map.find(Name);
112     if (I == Map.end())
113       return true;
114     Idx = I->getValue();
115     return false;
116   }
117 };
118 } // end anonymous namespace
119
120 template <class T>
121 static size_t arrayDataSize(ArrayRef<T> A) {
122   return A.size() * sizeof(T);
123 }
124
125 template <class T>
126 static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
127   OS.write((const char *)A.data(), arrayDataSize(A));
128 }
129
130 template <class T>
131 static void zero(T &Obj) {
132   memset(&Obj, 0, sizeof(Obj));
133 }
134
135 namespace {
136 /// \brief "Single point of truth" for the ELF file construction.
137 /// TODO: This class still has a ways to go before it is truly a "single
138 /// point of truth".
139 template <class ELFT>
140 class ELFState {
141   typedef typename object::ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
142   typedef typename object::ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
143   typedef typename object::ELFFile<ELFT>::Elf_Sym Elf_Sym;
144   typedef typename object::ELFFile<ELFT>::Elf_Rel Elf_Rel;
145   typedef typename object::ELFFile<ELFT>::Elf_Rela Elf_Rela;
146
147   /// \brief The future ".strtab" section.
148   StringTableBuilder DotStrtab;
149
150   /// \brief The future ".shstrtab" section.
151   StringTableBuilder DotShStrtab;
152
153   NameToIdxMap SN2I;
154   NameToIdxMap SymN2I;
155   const ELFYAML::Object &Doc;
156
157   bool buildSectionIndex();
158   bool buildSymbolIndex(std::size_t &StartIndex,
159                         const std::vector<ELFYAML::Symbol> &Symbols);
160   void initELFHeader(Elf_Ehdr &Header);
161   bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
162                           ContiguousBlobAccumulator &CBA);
163   void initSymtabSectionHeader(Elf_Shdr &SHeader,
164                                ContiguousBlobAccumulator &CBA);
165   void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
166                                StringTableBuilder &STB,
167                                ContiguousBlobAccumulator &CBA);
168   void addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
169                   std::vector<Elf_Sym> &Syms, unsigned SymbolBinding);
170   void writeSectionContent(Elf_Shdr &SHeader,
171                            const ELFYAML::RawContentSection &Section,
172                            ContiguousBlobAccumulator &CBA);
173   bool writeSectionContent(Elf_Shdr &SHeader,
174                            const ELFYAML::RelocationSection &Section,
175                            ContiguousBlobAccumulator &CBA);
176
177   // - SHT_NULL entry (placed first, i.e. 0'th entry)
178   // - symbol table (.symtab) (placed third to last)
179   // - string table (.strtab) (placed second to last)
180   // - section header string table (.shstrtab) (placed last)
181   unsigned getDotSymTabSecNo() const { return Doc.Sections.size() + 1; }
182   unsigned getDotStrTabSecNo() const { return Doc.Sections.size() + 2; }
183   unsigned getDotShStrTabSecNo() const { return Doc.Sections.size() + 3; }
184   unsigned getSectionCount() const { return Doc.Sections.size() + 4; }
185
186   ELFState(const ELFYAML::Object &D) : Doc(D) {}
187
188 public:
189   static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
190 };
191 } // end anonymous namespace
192
193 template <class ELFT>
194 void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
195   using namespace llvm::ELF;
196   zero(Header);
197   Header.e_ident[EI_MAG0] = 0x7f;
198   Header.e_ident[EI_MAG1] = 'E';
199   Header.e_ident[EI_MAG2] = 'L';
200   Header.e_ident[EI_MAG3] = 'F';
201   Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
202   bool IsLittleEndian = ELFT::TargetEndianness == support::little;
203   Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
204   Header.e_ident[EI_VERSION] = EV_CURRENT;
205   Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
206   Header.e_ident[EI_ABIVERSION] = 0;
207   Header.e_type = Doc.Header.Type;
208   Header.e_machine = Doc.Header.Machine;
209   Header.e_version = EV_CURRENT;
210   Header.e_entry = Doc.Header.Entry;
211   Header.e_flags = Doc.Header.Flags;
212   Header.e_ehsize = sizeof(Elf_Ehdr);
213   Header.e_shentsize = sizeof(Elf_Shdr);
214   // Immediately following the ELF header.
215   Header.e_shoff = sizeof(Header);
216   Header.e_shnum = getSectionCount();
217   Header.e_shstrndx = getDotShStrTabSecNo();
218 }
219
220 template <class ELFT>
221 bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
222                                         ContiguousBlobAccumulator &CBA) {
223   // Ensure SHN_UNDEF entry is present. An all-zero section header is a
224   // valid SHN_UNDEF entry since SHT_NULL == 0.
225   Elf_Shdr SHeader;
226   zero(SHeader);
227   SHeaders.push_back(SHeader);
228
229   for (const auto &Sec : Doc.Sections) {
230     zero(SHeader);
231     SHeader.sh_name = DotShStrtab.addString(Sec->Name);
232     SHeader.sh_type = Sec->Type;
233     SHeader.sh_flags = Sec->Flags;
234     SHeader.sh_addr = Sec->Address;
235     SHeader.sh_addralign = Sec->AddressAlign;
236
237     if (!Sec->Link.empty()) {
238       unsigned Index;
239       if (SN2I.lookup(Sec->Link, Index)) {
240         errs() << "error: Unknown section referenced: '" << Sec->Link
241                << "' at YAML section '" << Sec->Name << "'.\n";
242         return false;
243       }
244       SHeader.sh_link = Index;
245     }
246
247     if (auto S = dyn_cast<ELFYAML::RawContentSection>(Sec.get()))
248       writeSectionContent(SHeader, *S, CBA);
249     else if (auto S = dyn_cast<ELFYAML::RelocationSection>(Sec.get())) {
250       if (S->Link.empty())
251         // For relocation section set link to .symtab by default.
252         SHeader.sh_link = getDotSymTabSecNo();
253
254       unsigned Index;
255       if (SN2I.lookup(S->Info, Index)) {
256         errs() << "error: Unknown section referenced: '" << S->Info
257                << "' at YAML section '" << S->Name << "'.\n";
258         return false;
259       }
260       SHeader.sh_info = Index;
261
262       if (!writeSectionContent(SHeader, *S, CBA))
263         return false;
264     } else
265       llvm_unreachable("Unknown section type");
266
267     SHeaders.push_back(SHeader);
268   }
269   return true;
270 }
271
272 template <class ELFT>
273 void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
274                                              ContiguousBlobAccumulator &CBA) {
275   zero(SHeader);
276   SHeader.sh_name = DotShStrtab.addString(StringRef(".symtab"));
277   SHeader.sh_type = ELF::SHT_SYMTAB;
278   SHeader.sh_link = getDotStrTabSecNo();
279   // One greater than symbol table index of the last local symbol.
280   SHeader.sh_info = Doc.Symbols.Local.size() + 1;
281   SHeader.sh_entsize = sizeof(Elf_Sym);
282
283   std::vector<Elf_Sym> Syms;
284   {
285     // Ensure STN_UNDEF is present
286     Elf_Sym Sym;
287     zero(Sym);
288     Syms.push_back(Sym);
289   }
290   addSymbols(Doc.Symbols.Local, Syms, ELF::STB_LOCAL);
291   addSymbols(Doc.Symbols.Global, Syms, ELF::STB_GLOBAL);
292   addSymbols(Doc.Symbols.Weak, Syms, ELF::STB_WEAK);
293
294   writeArrayData(CBA.getOSAndAlignedOffset(SHeader.sh_offset),
295                  makeArrayRef(Syms));
296   SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
297 }
298
299 template <class ELFT>
300 void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
301                                              StringTableBuilder &STB,
302                                              ContiguousBlobAccumulator &CBA) {
303   zero(SHeader);
304   SHeader.sh_name = DotShStrtab.addString(Name);
305   SHeader.sh_type = ELF::SHT_STRTAB;
306   STB.writeToStream(CBA.getOSAndAlignedOffset(SHeader.sh_offset));
307   SHeader.sh_size = STB.size();
308   SHeader.sh_addralign = 1;
309 }
310
311 template <class ELFT>
312 void ELFState<ELFT>::addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
313                                 std::vector<Elf_Sym> &Syms,
314                                 unsigned SymbolBinding) {
315   for (const auto &Sym : Symbols) {
316     Elf_Sym Symbol;
317     zero(Symbol);
318     if (!Sym.Name.empty())
319       Symbol.st_name = DotStrtab.addString(Sym.Name);
320     Symbol.setBindingAndType(SymbolBinding, Sym.Type);
321     if (!Sym.Section.empty()) {
322       unsigned Index;
323       if (SN2I.lookup(Sym.Section, Index)) {
324         errs() << "error: Unknown section referenced: '" << Sym.Section
325                << "' by YAML symbol " << Sym.Name << ".\n";
326         exit(1);
327       }
328       Symbol.st_shndx = Index;
329     } // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
330     Symbol.st_value = Sym.Value;
331     Symbol.st_size = Sym.Size;
332     Syms.push_back(Symbol);
333   }
334 }
335
336 template <class ELFT>
337 void
338 ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
339                                     const ELFYAML::RawContentSection &Section,
340                                     ContiguousBlobAccumulator &CBA) {
341   Section.Content.writeAsBinary(CBA.getOSAndAlignedOffset(SHeader.sh_offset));
342   SHeader.sh_entsize = 0;
343   SHeader.sh_size = Section.Content.binary_size();
344 }
345
346 template <class ELFT>
347 bool
348 ELFState<ELFT>::writeSectionContent(Elf_Shdr &SHeader,
349                                     const ELFYAML::RelocationSection &Section,
350                                     ContiguousBlobAccumulator &CBA) {
351   if (Section.Type != llvm::ELF::SHT_REL &&
352       Section.Type != llvm::ELF::SHT_RELA) {
353     errs() << "error: Invalid relocation section type.\n";
354     return false;
355   }
356
357   bool IsRela = Section.Type == llvm::ELF::SHT_RELA;
358   SHeader.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
359   SHeader.sh_size = SHeader.sh_entsize * Section.Relocations.size();
360
361   auto &OS = CBA.getOSAndAlignedOffset(SHeader.sh_offset);
362
363   for (const auto &Rel : Section.Relocations) {
364     unsigned SymIdx;
365     if (SymN2I.lookup(Rel.Symbol, SymIdx)) {
366       errs() << "error: Unknown symbol referenced: '" << Rel.Symbol
367              << "' at YAML relocation.\n";
368       return false;
369     }
370
371     if (IsRela) {
372       Elf_Rela REntry;
373       zero(REntry);
374       REntry.r_offset = Rel.Offset;
375       REntry.r_addend = Rel.Addend;
376       REntry.setSymbolAndType(SymIdx, Rel.Type);
377       OS.write((const char *)&REntry, sizeof(REntry));
378     } else {
379       Elf_Rel REntry;
380       zero(REntry);
381       REntry.r_offset = Rel.Offset;
382       REntry.setSymbolAndType(SymIdx, Rel.Type);
383       OS.write((const char *)&REntry, sizeof(REntry));
384     }
385   }
386   return true;
387 }
388
389 template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
390   SN2I.addName(".symtab", getDotSymTabSecNo());
391   SN2I.addName(".strtab", getDotStrTabSecNo());
392   SN2I.addName(".shstrtab", getDotShStrTabSecNo());
393
394   for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
395     StringRef Name = Doc.Sections[i]->Name;
396     if (Name.empty())
397       continue;
398     // "+ 1" to take into account the SHT_NULL entry.
399     if (SN2I.addName(Name, i + 1)) {
400       errs() << "error: Repeated section name: '" << Name
401              << "' at YAML section number " << i << ".\n";
402       return false;
403     }
404   }
405   return true;
406 }
407
408 template <class ELFT>
409 bool
410 ELFState<ELFT>::buildSymbolIndex(std::size_t &StartIndex,
411                                  const std::vector<ELFYAML::Symbol> &Symbols) {
412   for (const auto &Sym : Symbols) {
413     ++StartIndex;
414     if (Sym.Name.empty())
415       continue;
416     if (SymN2I.addName(Sym.Name, StartIndex)) {
417       errs() << "error: Repeated symbol name: '" << Sym.Name << "'.\n";
418       return false;
419     }
420   }
421   return true;
422 }
423
424 template <class ELFT>
425 int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
426   ELFState<ELFT> State(Doc);
427   if (!State.buildSectionIndex())
428     return 1;
429
430   std::size_t StartSymIndex = 0;
431   if (!State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Local) ||
432       !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Global) ||
433       !State.buildSymbolIndex(StartSymIndex, Doc.Symbols.Weak))
434     return 1;
435
436   Elf_Ehdr Header;
437   State.initELFHeader(Header);
438
439   // TODO: Flesh out section header support.
440   // TODO: Program headers.
441
442   // XXX: This offset is tightly coupled with the order that we write
443   // things to `OS`.
444   const size_t SectionContentBeginOffset =
445       Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
446   ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
447
448   std::vector<Elf_Shdr> SHeaders;
449   if(!State.initSectionHeaders(SHeaders, CBA))
450     return 1;
451
452   // .symtab section.
453   Elf_Shdr SymtabSHeader;
454   State.initSymtabSectionHeader(SymtabSHeader, CBA);
455   SHeaders.push_back(SymtabSHeader);
456
457   // .strtab string table header.
458   Elf_Shdr DotStrTabSHeader;
459   State.initStrtabSectionHeader(DotStrTabSHeader, ".strtab", State.DotStrtab,
460                                 CBA);
461   SHeaders.push_back(DotStrTabSHeader);
462
463   // .shstrtab string table header.
464   Elf_Shdr ShStrTabSHeader;
465   State.initStrtabSectionHeader(ShStrTabSHeader, ".shstrtab", State.DotShStrtab,
466                                 CBA);
467   SHeaders.push_back(ShStrTabSHeader);
468
469   OS.write((const char *)&Header, sizeof(Header));
470   writeArrayData(OS, makeArrayRef(SHeaders));
471   CBA.writeBlobToStream(OS);
472   return 0;
473 }
474
475 static bool is64Bit(const ELFYAML::Object &Doc) {
476   return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
477 }
478
479 static bool isLittleEndian(const ELFYAML::Object &Doc) {
480   return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
481 }
482
483 int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
484   yaml::Input YIn(Buf->getBuffer());
485   ELFYAML::Object Doc;
486   YIn >> Doc;
487   if (YIn.error()) {
488     errs() << "yaml2obj: Failed to parse YAML file!\n";
489     return 1;
490   }
491   using object::ELFType;
492   typedef ELFType<support::little, 8, true> LE64;
493   typedef ELFType<support::big, 8, true> BE64;
494   typedef ELFType<support::little, 4, false> LE32;
495   typedef ELFType<support::big, 4, false> BE32;
496   if (is64Bit(Doc)) {
497     if (isLittleEndian(Doc))
498       return ELFState<LE64>::writeELF(outs(), Doc);
499     else
500       return ELFState<BE64>::writeELF(outs(), Doc);
501   } else {
502     if (isLittleEndian(Doc))
503       return ELFState<LE32>::writeELF(outs(), Doc);
504     else
505       return ELFState<BE32>::writeELF(outs(), Doc);
506   }
507 }