[yaml2obj] Add support for sh_addralign via `AddressAlign` key.
[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/Object/ELF.h"
17 #include "llvm/Object/ELFYAML.h"
18 #include "llvm/Support/ELF.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/YAMLTraits.h"
21 #include "llvm/Support/raw_ostream.h"
22
23 using namespace llvm;
24
25 // There is similar code in yaml2coff, but with some slight COFF-specific
26 // variations like different initial state. Might be able to deduplicate
27 // some day, but also want to make sure that the Mach-O use case is served.
28 //
29 // This class has a deliberately small interface, since a lot of
30 // implementation variation is possible.
31 //
32 // TODO: Use an ordered container with a suffix-based comparison in order
33 // to deduplicate suffixes. std::map<> with a custom comparator is likely
34 // to be the simplest implementation, but a suffix trie could be more
35 // suitable for the job.
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
64 // This class is used to build up a contiguous binary blob while keeping
65 // track of an offset in the output (which notionally begins at
66 // `InitialOffset`).
67 class ContiguousBlobAccumulator {
68   const uint64_t InitialOffset;
69   raw_svector_ostream OS;
70
71 public:
72   ContiguousBlobAccumulator(uint64_t InitialOffset_, SmallVectorImpl<char> &Buf)
73       : InitialOffset(InitialOffset_), OS(Buf) {}
74   raw_ostream &getOS() { return OS; }
75   uint64_t currentOffset() const { return InitialOffset + OS.tell(); }
76   void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
77 };
78
79 template <class T>
80 static size_t vectorDataSize(const std::vector<T> &Vec) {
81   return Vec.size() * sizeof(T);
82 }
83
84 template <class T>
85 static void writeVectorData(raw_ostream &OS, const std::vector<T> &Vec) {
86   OS.write((const char *)Vec.data(), vectorDataSize(Vec));
87 }
88
89 template <class T>
90 static void zero(T &Obj) {
91   memset(&Obj, 0, sizeof(Obj));
92 }
93
94 template <class ELFT>
95 static void writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
96   using namespace llvm::ELF;
97   using namespace llvm::object;
98   typedef typename ELFObjectFile<ELFT>::Elf_Ehdr Elf_Ehdr;
99   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
100
101   const ELFYAML::FileHeader &Hdr = Doc.Header;
102
103   Elf_Ehdr Header;
104   zero(Header);
105   Header.e_ident[EI_MAG0] = 0x7f;
106   Header.e_ident[EI_MAG1] = 'E';
107   Header.e_ident[EI_MAG2] = 'L';
108   Header.e_ident[EI_MAG3] = 'F';
109   Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
110   bool IsLittleEndian = ELFT::TargetEndianness == support::little;
111   Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
112   Header.e_ident[EI_VERSION] = EV_CURRENT;
113   // TODO: Implement ELF_ELFOSABI enum.
114   Header.e_ident[EI_OSABI] = ELFOSABI_NONE;
115   // TODO: Implement ELF_ABIVERSION enum.
116   Header.e_ident[EI_ABIVERSION] = 0;
117   Header.e_type = Hdr.Type;
118   Header.e_machine = Hdr.Machine;
119   Header.e_version = EV_CURRENT;
120   Header.e_entry = Hdr.Entry;
121   Header.e_ehsize = sizeof(Elf_Ehdr);
122
123   // TODO: Flesh out section header support.
124   // TODO: Program headers.
125
126   Header.e_shentsize = sizeof(Elf_Shdr);
127   // Immediately following the ELF header.
128   Header.e_shoff = sizeof(Header);
129   std::vector<ELFYAML::Section> Sections = Doc.Sections;
130   if (Sections.empty() || Sections.front().Type != SHT_NULL) {
131     ELFYAML::Section S;
132     S.Type = SHT_NULL;
133     zero(S.Flags);
134     Sections.insert(Sections.begin(), S);
135   }
136   // "+ 1" for string table.
137   Header.e_shnum = Sections.size() + 1;
138   // Place section header string table last.
139   Header.e_shstrndx = Sections.size();
140
141   StringTableBuilder StrTab;
142   SmallVector<char, 128> Buf;
143   // XXX: This offset is tightly coupled with the order that we write
144   // things to `OS`.
145   const size_t SectionContentBeginOffset =
146       Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
147   ContiguousBlobAccumulator CBA(SectionContentBeginOffset, Buf);
148   std::vector<Elf_Shdr> SHeaders;
149   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
150     const ELFYAML::Section &Sec = Sections[i];
151     Elf_Shdr SHeader;
152     zero(SHeader);
153     SHeader.sh_name = StrTab.addString(Sec.Name);
154     SHeader.sh_type = Sec.Type;
155     SHeader.sh_flags = Sec.Flags;
156     SHeader.sh_addr = Sec.Address;
157
158     SHeader.sh_offset = CBA.currentOffset();
159     SHeader.sh_size = Sec.Content.binary_size();
160     Sec.Content.writeAsBinary(CBA.getOS());
161
162     SHeader.sh_link = 0;
163     SHeader.sh_info = 0;
164     SHeader.sh_addralign = Sec.AddressAlign;
165     SHeader.sh_entsize = 0;
166     SHeaders.push_back(SHeader);
167   }
168
169   // String table header.
170   Elf_Shdr StrTabSHeader;
171   zero(StrTabSHeader);
172   StrTabSHeader.sh_name = 0;
173   StrTabSHeader.sh_type = SHT_STRTAB;
174   StrTabSHeader.sh_flags = 0;
175   StrTabSHeader.sh_addr = 0;
176   StrTabSHeader.sh_offset = CBA.currentOffset();
177   StrTabSHeader.sh_size = StrTab.size();
178   StrTab.writeToStream(CBA.getOS());
179   StrTabSHeader.sh_link = 0;
180   StrTabSHeader.sh_info = 0;
181   StrTabSHeader.sh_addralign = 1;
182   StrTabSHeader.sh_entsize = 0;
183
184   OS.write((const char *)&Header, sizeof(Header));
185   writeVectorData(OS, SHeaders);
186   OS.write((const char *)&StrTabSHeader, sizeof(StrTabSHeader));
187   CBA.writeBlobToStream(OS);
188 }
189
190 int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
191   yaml::Input YIn(Buf->getBuffer());
192   ELFYAML::Object Doc;
193   YIn >> Doc;
194   if (YIn.error()) {
195     errs() << "yaml2obj: Failed to parse YAML file!\n";
196     return 1;
197   }
198   if (Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64)) {
199     if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
200       writeELF<object::ELFType<support::little, 8, true> >(outs(), Doc);
201     else
202       writeELF<object::ELFType<support::big, 8, true> >(outs(), Doc);
203   } else {
204     if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
205       writeELF<object::ELFType<support::little, 4, false> >(outs(), Doc);
206     else
207       writeELF<object::ELFType<support::big, 4, false> >(outs(), Doc);
208   }
209
210   return 0;
211 }