blob: b83dd1d1a3549a6e51e72cff7c170b57c6fe43fc [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.
Sean Silva2a74f702013-06-15 00:31:46 +000036namespace {
Sean Silva38205932013-06-13 22:19:48 +000037class StringTableBuilder {
38 /// \brief Indices of strings currently present in `Buf`.
39 StringMap<unsigned> StringIndices;
40 /// \brief The contents of the string table as we build it.
41 std::string Buf;
42public:
43 StringTableBuilder() {
44 Buf.push_back('\0');
45 }
46 /// \returns Index of string in string table.
47 unsigned addString(StringRef S) {
48 StringMapEntry<unsigned> &Entry = StringIndices.GetOrCreateValue(S);
49 unsigned &I = Entry.getValue();
50 if (I != 0)
51 return I;
52 I = Buf.size();
53 Buf.append(S.begin(), S.end());
54 Buf.push_back('\0');
55 return I;
56 }
57 size_t size() const {
58 return Buf.size();
59 }
60 void writeToStream(raw_ostream &OS) {
61 OS.write(Buf.data(), Buf.size());
62 }
63};
Sean Silva2a74f702013-06-15 00:31:46 +000064} // end anonymous namespace
Sean Silva38205932013-06-13 22:19:48 +000065
Sean Silva46dffff2013-06-13 22:20:01 +000066// This class is used to build up a contiguous binary blob while keeping
67// track of an offset in the output (which notionally begins at
68// `InitialOffset`).
Sean Silva2a74f702013-06-15 00:31:46 +000069namespace {
Sean Silva46dffff2013-06-13 22:20:01 +000070class ContiguousBlobAccumulator {
71 const uint64_t InitialOffset;
72 raw_svector_ostream OS;
73
74public:
75 ContiguousBlobAccumulator(uint64_t InitialOffset_, SmallVectorImpl<char> &Buf)
76 : InitialOffset(InitialOffset_), OS(Buf) {}
77 raw_ostream &getOS() { return OS; }
78 uint64_t currentOffset() const { return InitialOffset + OS.tell(); }
79 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
80};
Sean Silva2a74f702013-06-15 00:31:46 +000081} // end anonymous namespace
Sean Silva46dffff2013-06-13 22:20:01 +000082
Sean Silvaa6423eb2013-06-15 00:25:26 +000083// Used to keep track of section names, so that in the YAML file sections
84// can be referenced by name instead of by index.
Sean Silva2a74f702013-06-15 00:31:46 +000085namespace {
Sean Silvaa6423eb2013-06-15 00:25:26 +000086class SectionNameToIdxMap {
87 StringMap<int> Map;
88public:
89 /// \returns true if name is already present in the map.
90 bool addName(StringRef SecName, unsigned i) {
91 StringMapEntry<int> &Entry = Map.GetOrCreateValue(SecName, -1);
92 if (Entry.getValue() != -1)
93 return true;
94 Entry.setValue((int)i);
95 return false;
96 }
97 /// \returns true if name is not present in the map
98 bool lookupSection(StringRef SecName, unsigned &Idx) const {
99 StringMap<int>::const_iterator I = Map.find(SecName);
100 if (I == Map.end())
101 return true;
102 Idx = I->getValue();
103 return false;
104 }
105};
Sean Silva2a74f702013-06-15 00:31:46 +0000106} // end anonymous namespace
Sean Silvaa6423eb2013-06-15 00:25:26 +0000107
Sean Silva38205932013-06-13 22:19:48 +0000108template <class T>
109static size_t vectorDataSize(const std::vector<T> &Vec) {
110 return Vec.size() * sizeof(T);
111}
112
113template <class T>
114static void writeVectorData(raw_ostream &OS, const std::vector<T> &Vec) {
115 OS.write((const char *)Vec.data(), vectorDataSize(Vec));
116}
117
118template <class T>
119static void zero(T &Obj) {
120 memset(&Obj, 0, sizeof(Obj));
121}
122
Sean Silva85d3eeb2013-06-18 01:11:27 +0000123/// \brief Create a string table in `SHeader`, which we assume is already
124/// zero'd.
125template <class Elf_Shdr>
126static void createStringTableSectionHeader(Elf_Shdr &SHeader,
127 StringTableBuilder &STB,
128 ContiguousBlobAccumulator &CBA) {
129 SHeader.sh_type = ELF::SHT_STRTAB;
130 SHeader.sh_offset = CBA.currentOffset();
131 SHeader.sh_size = STB.size();
132 STB.writeToStream(CBA.getOS());
133 SHeader.sh_addralign = 1;
134}
135
Sean Silvaf99309c2013-06-10 23:44:15 +0000136template <class ELFT>
Sean Silva415d93f2013-06-17 20:14:59 +0000137static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Sean Silvaf99309c2013-06-10 23:44:15 +0000138 using namespace llvm::ELF;
139 using namespace llvm::object;
Sean Silva38205932013-06-13 22:19:48 +0000140 typedef typename ELFObjectFile<ELFT>::Elf_Ehdr Elf_Ehdr;
141 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
142
143 const ELFYAML::FileHeader &Hdr = Doc.Header;
144
145 Elf_Ehdr Header;
146 zero(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000147 Header.e_ident[EI_MAG0] = 0x7f;
148 Header.e_ident[EI_MAG1] = 'E';
149 Header.e_ident[EI_MAG2] = 'L';
150 Header.e_ident[EI_MAG3] = 'F';
151 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
152 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
153 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
Sean Silvaf99309c2013-06-10 23:44:15 +0000154 Header.e_ident[EI_VERSION] = EV_CURRENT;
Sean Silvaf99309c2013-06-10 23:44:15 +0000155 // TODO: Implement ELF_ELFOSABI enum.
156 Header.e_ident[EI_OSABI] = ELFOSABI_NONE;
157 // TODO: Implement ELF_ABIVERSION enum.
158 Header.e_ident[EI_ABIVERSION] = 0;
159 Header.e_type = Hdr.Type;
160 Header.e_machine = Hdr.Machine;
161 Header.e_version = EV_CURRENT;
162 Header.e_entry = Hdr.Entry;
Sean Silva38205932013-06-13 22:19:48 +0000163 Header.e_ehsize = sizeof(Elf_Ehdr);
Sean Silvaf99309c2013-06-10 23:44:15 +0000164
Sean Silva38205932013-06-13 22:19:48 +0000165 // TODO: Flesh out section header support.
166 // TODO: Program headers.
167
168 Header.e_shentsize = sizeof(Elf_Shdr);
169 // Immediately following the ELF header.
170 Header.e_shoff = sizeof(Header);
171 std::vector<ELFYAML::Section> Sections = Doc.Sections;
172 if (Sections.empty() || Sections.front().Type != SHT_NULL) {
173 ELFYAML::Section S;
174 S.Type = SHT_NULL;
175 zero(S.Flags);
Sean Silvaf62a6002013-06-18 01:11:21 +0000176 zero(S.Address);
177 zero(S.AddressAlign);
Sean Silva38205932013-06-13 22:19:48 +0000178 Sections.insert(Sections.begin(), S);
179 }
Sean Silvac3131922013-06-18 21:37:50 +0000180 // "+ 2" for string table and section header string table.
181 Header.e_shnum = Sections.size() + 2;
Sean Silva38205932013-06-13 22:19:48 +0000182 // Place section header string table last.
Sean Silvac3131922013-06-18 21:37:50 +0000183 Header.e_shstrndx = Sections.size() + 1;
Sean Silva38205932013-06-13 22:19:48 +0000184
Sean Silvaa6423eb2013-06-15 00:25:26 +0000185 SectionNameToIdxMap SN2I;
186 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
187 StringRef Name = Sections[i].Name;
188 if (Name.empty())
189 continue;
190 if (SN2I.addName(Name, i)) {
191 errs() << "error: Repeated section name: '" << Name
192 << "' at YAML section number " << i << ".\n";
Sean Silva415d93f2013-06-17 20:14:59 +0000193 return 1;
Sean Silvaa6423eb2013-06-15 00:25:26 +0000194 }
195 }
196
Sean Silvafde4ab02013-06-18 01:11:24 +0000197 StringTableBuilder SHStrTab;
Sean Silva46dffff2013-06-13 22:20:01 +0000198 SmallVector<char, 128> Buf;
199 // XXX: This offset is tightly coupled with the order that we write
200 // things to `OS`.
201 const size_t SectionContentBeginOffset =
202 Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
203 ContiguousBlobAccumulator CBA(SectionContentBeginOffset, Buf);
Sean Silva38205932013-06-13 22:19:48 +0000204 std::vector<Elf_Shdr> SHeaders;
205 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
206 const ELFYAML::Section &Sec = Sections[i];
207 Elf_Shdr SHeader;
208 zero(SHeader);
Sean Silvafde4ab02013-06-18 01:11:24 +0000209 SHeader.sh_name = SHStrTab.addString(Sec.Name);
Sean Silva38205932013-06-13 22:19:48 +0000210 SHeader.sh_type = Sec.Type;
211 SHeader.sh_flags = Sec.Flags;
Sean Silvaf4bfced2013-06-13 22:19:54 +0000212 SHeader.sh_addr = Sec.Address;
Sean Silva46dffff2013-06-13 22:20:01 +0000213
214 SHeader.sh_offset = CBA.currentOffset();
215 SHeader.sh_size = Sec.Content.binary_size();
216 Sec.Content.writeAsBinary(CBA.getOS());
217
Sean Silvaa6423eb2013-06-15 00:25:26 +0000218 if (!Sec.Link.empty()) {
219 unsigned Index;
220 if (SN2I.lookupSection(Sec.Link, Index)) {
221 errs() << "error: Unknown section referenced: '" << Sec.Link
222 << "' at YAML section number " << i << ".\n";
Sean Silva415d93f2013-06-17 20:14:59 +0000223 return 1;
Sean Silvaa6423eb2013-06-15 00:25:26 +0000224 }
225 SHeader.sh_link = Index;
226 }
Sean Silva38205932013-06-13 22:19:48 +0000227 SHeader.sh_info = 0;
Sean Silva0a409cf2013-06-14 00:38:02 +0000228 SHeader.sh_addralign = Sec.AddressAlign;
Sean Silva38205932013-06-13 22:19:48 +0000229 SHeader.sh_entsize = 0;
230 SHeaders.push_back(SHeader);
231 }
232
Sean Silvac3131922013-06-18 21:37:50 +0000233 // .strtab string table header. Currently emitted empty.
234 StringTableBuilder DotStrTab;
235 Elf_Shdr DotStrTabSHeader;
236 zero(DotStrTabSHeader);
237 DotStrTabSHeader.sh_name = SHStrTab.addString(StringRef(".strtab"));
238 createStringTableSectionHeader(DotStrTabSHeader, DotStrTab, CBA);
239
Sean Silvafde4ab02013-06-18 01:11:24 +0000240 // Section header string table header.
241 Elf_Shdr SHStrTabSHeader;
242 zero(SHStrTabSHeader);
Sean Silva85d3eeb2013-06-18 01:11:27 +0000243 createStringTableSectionHeader(SHStrTabSHeader, SHStrTab, CBA);
Sean Silvaf99309c2013-06-10 23:44:15 +0000244
245 OS.write((const char *)&Header, sizeof(Header));
Sean Silva38205932013-06-13 22:19:48 +0000246 writeVectorData(OS, SHeaders);
Sean Silvac3131922013-06-18 21:37:50 +0000247 OS.write((const char *)&DotStrTabSHeader, sizeof(DotStrTabSHeader));
Sean Silvafde4ab02013-06-18 01:11:24 +0000248 OS.write((const char *)&SHStrTabSHeader, sizeof(SHStrTabSHeader));
Sean Silva46dffff2013-06-13 22:20:01 +0000249 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000250 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000251}
252
253int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
254 yaml::Input YIn(Buf->getBuffer());
255 ELFYAML::Object Doc;
256 YIn >> Doc;
257 if (YIn.error()) {
258 errs() << "yaml2obj: Failed to parse YAML file!\n";
259 return 1;
260 }
261 if (Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64)) {
262 if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
Sean Silva415d93f2013-06-17 20:14:59 +0000263 return writeELF<object::ELFType<support::little, 8, true> >(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000264 else
Sean Silva415d93f2013-06-17 20:14:59 +0000265 return writeELF<object::ELFType<support::big, 8, true> >(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000266 } else {
267 if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
Sean Silva415d93f2013-06-17 20:14:59 +0000268 return writeELF<object::ELFType<support::little, 4, false> >(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000269 else
Sean Silva415d93f2013-06-17 20:14:59 +0000270 return writeELF<object::ELFType<support::big, 4, false> >(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000271 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000272}