blob: e6a157cfd8878e2dc6e5e9d95ab45cbffa567e1a [file] [log] [blame]
Sean Silvaf99309c2013-06-10 23:44:15 +00001//===- 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
23using namespace llvm;
24
Sean Silva38205932013-06-13 22:19:48 +000025// 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.
36class 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;
41public:
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
Sean Silva46dffff2013-06-13 22:20:01 +000064// 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`).
67class ContiguousBlobAccumulator {
68 const uint64_t InitialOffset;
69 raw_svector_ostream OS;
70
71public:
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
Sean Silvaa6423eb2013-06-15 00:25:26 +000079// Used to keep track of section names, so that in the YAML file sections
80// can be referenced by name instead of by index.
81class SectionNameToIdxMap {
82 StringMap<int> Map;
83public:
84 /// \returns true if name is already present in the map.
85 bool addName(StringRef SecName, unsigned i) {
86 StringMapEntry<int> &Entry = Map.GetOrCreateValue(SecName, -1);
87 if (Entry.getValue() != -1)
88 return true;
89 Entry.setValue((int)i);
90 return false;
91 }
92 /// \returns true if name is not present in the map
93 bool lookupSection(StringRef SecName, unsigned &Idx) const {
94 StringMap<int>::const_iterator I = Map.find(SecName);
95 if (I == Map.end())
96 return true;
97 Idx = I->getValue();
98 return false;
99 }
100};
101
Sean Silva38205932013-06-13 22:19:48 +0000102template <class T>
103static size_t vectorDataSize(const std::vector<T> &Vec) {
104 return Vec.size() * sizeof(T);
105}
106
107template <class T>
108static void writeVectorData(raw_ostream &OS, const std::vector<T> &Vec) {
109 OS.write((const char *)Vec.data(), vectorDataSize(Vec));
110}
111
112template <class T>
113static void zero(T &Obj) {
114 memset(&Obj, 0, sizeof(Obj));
115}
116
Sean Silvaf99309c2013-06-10 23:44:15 +0000117template <class ELFT>
118static void writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Sean Silvaf99309c2013-06-10 23:44:15 +0000119 using namespace llvm::ELF;
120 using namespace llvm::object;
Sean Silva38205932013-06-13 22:19:48 +0000121 typedef typename ELFObjectFile<ELFT>::Elf_Ehdr Elf_Ehdr;
122 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
123
124 const ELFYAML::FileHeader &Hdr = Doc.Header;
125
126 Elf_Ehdr Header;
127 zero(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000128 Header.e_ident[EI_MAG0] = 0x7f;
129 Header.e_ident[EI_MAG1] = 'E';
130 Header.e_ident[EI_MAG2] = 'L';
131 Header.e_ident[EI_MAG3] = 'F';
132 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
133 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
134 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
Sean Silvaf99309c2013-06-10 23:44:15 +0000135 Header.e_ident[EI_VERSION] = EV_CURRENT;
Sean Silvaf99309c2013-06-10 23:44:15 +0000136 // TODO: Implement ELF_ELFOSABI enum.
137 Header.e_ident[EI_OSABI] = ELFOSABI_NONE;
138 // TODO: Implement ELF_ABIVERSION enum.
139 Header.e_ident[EI_ABIVERSION] = 0;
140 Header.e_type = Hdr.Type;
141 Header.e_machine = Hdr.Machine;
142 Header.e_version = EV_CURRENT;
143 Header.e_entry = Hdr.Entry;
Sean Silva38205932013-06-13 22:19:48 +0000144 Header.e_ehsize = sizeof(Elf_Ehdr);
Sean Silvaf99309c2013-06-10 23:44:15 +0000145
Sean Silva38205932013-06-13 22:19:48 +0000146 // TODO: Flesh out section header support.
147 // TODO: Program headers.
148
149 Header.e_shentsize = sizeof(Elf_Shdr);
150 // Immediately following the ELF header.
151 Header.e_shoff = sizeof(Header);
152 std::vector<ELFYAML::Section> Sections = Doc.Sections;
153 if (Sections.empty() || Sections.front().Type != SHT_NULL) {
154 ELFYAML::Section S;
155 S.Type = SHT_NULL;
156 zero(S.Flags);
157 Sections.insert(Sections.begin(), S);
158 }
159 // "+ 1" for string table.
160 Header.e_shnum = Sections.size() + 1;
161 // Place section header string table last.
162 Header.e_shstrndx = Sections.size();
163
Sean Silvaa6423eb2013-06-15 00:25:26 +0000164 SectionNameToIdxMap SN2I;
165 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
166 StringRef Name = Sections[i].Name;
167 if (Name.empty())
168 continue;
169 if (SN2I.addName(Name, i)) {
170 errs() << "error: Repeated section name: '" << Name
171 << "' at YAML section number " << i << ".\n";
172 return;
173 }
174 }
175
Sean Silva38205932013-06-13 22:19:48 +0000176 StringTableBuilder StrTab;
Sean Silva46dffff2013-06-13 22:20:01 +0000177 SmallVector<char, 128> Buf;
178 // XXX: This offset is tightly coupled with the order that we write
179 // things to `OS`.
180 const size_t SectionContentBeginOffset =
181 Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
182 ContiguousBlobAccumulator CBA(SectionContentBeginOffset, Buf);
Sean Silva38205932013-06-13 22:19:48 +0000183 std::vector<Elf_Shdr> SHeaders;
184 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
185 const ELFYAML::Section &Sec = Sections[i];
186 Elf_Shdr SHeader;
187 zero(SHeader);
188 SHeader.sh_name = StrTab.addString(Sec.Name);
189 SHeader.sh_type = Sec.Type;
190 SHeader.sh_flags = Sec.Flags;
Sean Silvaf4bfced2013-06-13 22:19:54 +0000191 SHeader.sh_addr = Sec.Address;
Sean Silva46dffff2013-06-13 22:20:01 +0000192
193 SHeader.sh_offset = CBA.currentOffset();
194 SHeader.sh_size = Sec.Content.binary_size();
195 Sec.Content.writeAsBinary(CBA.getOS());
196
Sean Silvaa6423eb2013-06-15 00:25:26 +0000197 if (!Sec.Link.empty()) {
198 unsigned Index;
199 if (SN2I.lookupSection(Sec.Link, Index)) {
200 errs() << "error: Unknown section referenced: '" << Sec.Link
201 << "' at YAML section number " << i << ".\n";
202 return;
203 }
204 SHeader.sh_link = Index;
205 }
Sean Silva38205932013-06-13 22:19:48 +0000206 SHeader.sh_info = 0;
Sean Silva0a409cf2013-06-14 00:38:02 +0000207 SHeader.sh_addralign = Sec.AddressAlign;
Sean Silva38205932013-06-13 22:19:48 +0000208 SHeader.sh_entsize = 0;
209 SHeaders.push_back(SHeader);
210 }
211
212 // String table header.
213 Elf_Shdr StrTabSHeader;
214 zero(StrTabSHeader);
215 StrTabSHeader.sh_name = 0;
216 StrTabSHeader.sh_type = SHT_STRTAB;
217 StrTabSHeader.sh_flags = 0;
218 StrTabSHeader.sh_addr = 0;
Sean Silva46dffff2013-06-13 22:20:01 +0000219 StrTabSHeader.sh_offset = CBA.currentOffset();
Sean Silva38205932013-06-13 22:19:48 +0000220 StrTabSHeader.sh_size = StrTab.size();
Sean Silva46dffff2013-06-13 22:20:01 +0000221 StrTab.writeToStream(CBA.getOS());
Sean Silva38205932013-06-13 22:19:48 +0000222 StrTabSHeader.sh_link = 0;
223 StrTabSHeader.sh_info = 0;
224 StrTabSHeader.sh_addralign = 1;
225 StrTabSHeader.sh_entsize = 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000226
227 OS.write((const char *)&Header, sizeof(Header));
Sean Silva38205932013-06-13 22:19:48 +0000228 writeVectorData(OS, SHeaders);
229 OS.write((const char *)&StrTabSHeader, sizeof(StrTabSHeader));
Sean Silva46dffff2013-06-13 22:20:01 +0000230 CBA.writeBlobToStream(OS);
Sean Silvaf99309c2013-06-10 23:44:15 +0000231}
232
233int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
234 yaml::Input YIn(Buf->getBuffer());
235 ELFYAML::Object Doc;
236 YIn >> Doc;
237 if (YIn.error()) {
238 errs() << "yaml2obj: Failed to parse YAML file!\n";
239 return 1;
240 }
241 if (Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64)) {
242 if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
243 writeELF<object::ELFType<support::little, 8, true> >(outs(), Doc);
244 else
245 writeELF<object::ELFType<support::big, 8, true> >(outs(), Doc);
246 } else {
247 if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
248 writeELF<object::ELFType<support::little, 4, false> >(outs(), Doc);
249 else
250 writeELF<object::ELFType<support::big, 4, false> >(outs(), Doc);
251 }
252
253 return 0;
254}