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