blob: 501dc2b46f6f0133029ec477888725894eb6030f [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;
Sean Silvabd3bc692013-06-20 19:11:41 +000072 SmallVector<char, 128> Buf;
Sean Silva46dffff2013-06-13 22:20:01 +000073 raw_svector_ostream OS;
74
75public:
Sean Silvabd3bc692013-06-20 19:11:41 +000076 ContiguousBlobAccumulator(uint64_t InitialOffset_)
77 : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
Sean Silva46dffff2013-06-13 22:20:01 +000078 raw_ostream &getOS() { return OS; }
79 uint64_t currentOffset() const { return InitialOffset + OS.tell(); }
80 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
81};
Sean Silva2a74f702013-06-15 00:31:46 +000082} // end anonymous namespace
Sean Silva46dffff2013-06-13 22:20:01 +000083
Sean Silvaa6423eb2013-06-15 00:25:26 +000084// Used to keep track of section names, so that in the YAML file sections
85// can be referenced by name instead of by index.
Sean Silva2a74f702013-06-15 00:31:46 +000086namespace {
Sean Silvaa6423eb2013-06-15 00:25:26 +000087class SectionNameToIdxMap {
88 StringMap<int> Map;
89public:
90 /// \returns true if name is already present in the map.
91 bool addName(StringRef SecName, unsigned i) {
92 StringMapEntry<int> &Entry = Map.GetOrCreateValue(SecName, -1);
93 if (Entry.getValue() != -1)
94 return true;
95 Entry.setValue((int)i);
96 return false;
97 }
98 /// \returns true if name is not present in the map
99 bool lookupSection(StringRef SecName, unsigned &Idx) const {
100 StringMap<int>::const_iterator I = Map.find(SecName);
101 if (I == Map.end())
102 return true;
103 Idx = I->getValue();
104 return false;
105 }
106};
Sean Silva2a74f702013-06-15 00:31:46 +0000107} // end anonymous namespace
Sean Silvaa6423eb2013-06-15 00:25:26 +0000108
Sean Silva38205932013-06-13 22:19:48 +0000109template <class T>
110static size_t vectorDataSize(const std::vector<T> &Vec) {
111 return Vec.size() * sizeof(T);
112}
113
114template <class T>
115static void writeVectorData(raw_ostream &OS, const std::vector<T> &Vec) {
116 OS.write((const char *)Vec.data(), vectorDataSize(Vec));
117}
118
119template <class T>
120static void zero(T &Obj) {
121 memset(&Obj, 0, sizeof(Obj));
122}
123
Sean Silva85d3eeb2013-06-18 01:11:27 +0000124/// \brief Create a string table in `SHeader`, which we assume is already
125/// zero'd.
126template <class Elf_Shdr>
127static void createStringTableSectionHeader(Elf_Shdr &SHeader,
128 StringTableBuilder &STB,
129 ContiguousBlobAccumulator &CBA) {
130 SHeader.sh_type = ELF::SHT_STRTAB;
131 SHeader.sh_offset = CBA.currentOffset();
132 SHeader.sh_size = STB.size();
133 STB.writeToStream(CBA.getOS());
134 SHeader.sh_addralign = 1;
135}
136
Sean Silva08a75ae2013-06-20 19:11:44 +0000137namespace {
138/// \brief "Single point of truth" for the ELF file construction.
139/// TODO: This class still has a ways to go before it is truly a "single
140/// point of truth".
141template <class ELFT>
142class ELFState {
143 /// \brief The future ".strtab" section.
144 StringTableBuilder DotStrtab;
145 /// \brief The section number of the ".strtab" section.
146 unsigned DotStrtabSecNo;
147 /// \brief The accumulated contents of all sections so far.
148 ContiguousBlobAccumulator &SectionContentAccum;
149 typedef typename object::ELFObjectFile<ELFT>::Elf_Ehdr Elf_Ehdr;
150 /// \brief The ELF file header.
151 Elf_Ehdr &Header;
152
153public:
154
155 ELFState(Elf_Ehdr &Header_, ContiguousBlobAccumulator &Accum,
156 unsigned DotStrtabSecNo_)
157 : DotStrtab(), DotStrtabSecNo(DotStrtabSecNo_),
158 SectionContentAccum(Accum), Header(Header_) {}
159
160 unsigned getDotStrTabSecNo() const { return DotStrtabSecNo; }
161 StringTableBuilder &getStringTable() { return DotStrtab; }
162 ContiguousBlobAccumulator &getSectionContentAccum() {
163 return SectionContentAccum;
164 }
165};
166} // end anonymous namespace
167
168// FIXME: This function is hideous. The hideous ELF type names are hideous.
169// Factor the ELF output into a class (templated on ELFT) and share some
170// typedefs.
Sean Silva6b083882013-06-18 23:14:03 +0000171template <class ELFT>
172static void handleSymtabSectionHeader(
Sean Silva08a75ae2013-06-20 19:11:44 +0000173 const ELFYAML::Section &Sec, ELFState<ELFT> &State,
174 typename object::ELFObjectFile<ELFT>::Elf_Shdr &SHeader) {
Sean Silva6b083882013-06-18 23:14:03 +0000175
176 typedef typename object::ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
177 // TODO: Ensure that a manually specified `Link` field is diagnosed as an
178 // error for SHT_SYMTAB.
Sean Silva08a75ae2013-06-20 19:11:44 +0000179 SHeader.sh_link = State.getDotStrTabSecNo();
Sean Silva6b083882013-06-18 23:14:03 +0000180 // TODO: Once we handle symbol binding, this should be one greater than
181 // symbol table index of the last local symbol.
182 SHeader.sh_info = 0;
183 SHeader.sh_entsize = sizeof(Elf_Sym);
184
185 std::vector<Elf_Sym> Syms;
Sean Silvaabe18db2013-06-18 23:19:17 +0000186 {
187 // Ensure STN_UNDEF is present
188 Elf_Sym Sym;
189 zero(Sym);
190 Syms.push_back(Sym);
191 }
Sean Silva6b083882013-06-18 23:14:03 +0000192 for (unsigned i = 0, e = Sec.Symbols.size(); i != e; ++i) {
193 const ELFYAML::Symbol &Sym = Sec.Symbols[i];
194 Elf_Sym Symbol;
195 zero(Symbol);
196 if (!Sym.Name.empty())
Sean Silva08a75ae2013-06-20 19:11:44 +0000197 Symbol.st_name = State.getStringTable().addString(Sym.Name);
Sean Silvabba85592013-06-19 00:11:59 +0000198 Symbol.setBindingAndType(Sym.Binding, Sym.Type);
Sean Silva6b083882013-06-18 23:14:03 +0000199 Syms.push_back(Symbol);
200 }
201
Sean Silva08a75ae2013-06-20 19:11:44 +0000202 ContiguousBlobAccumulator &CBA = State.getSectionContentAccum();
Sean Silva6b083882013-06-18 23:14:03 +0000203 SHeader.sh_offset = CBA.currentOffset();
204 SHeader.sh_size = vectorDataSize(Syms);
205 writeVectorData(CBA.getOS(), Syms);
206}
207
Sean Silvaf99309c2013-06-10 23:44:15 +0000208template <class ELFT>
Sean Silva415d93f2013-06-17 20:14:59 +0000209static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Sean Silvaf99309c2013-06-10 23:44:15 +0000210 using namespace llvm::ELF;
Sean Silva67416d72013-06-19 01:13:28 +0000211 typedef typename object::ELFObjectFile<ELFT>::Elf_Ehdr Elf_Ehdr;
212 typedef typename object::ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Sean Silva38205932013-06-13 22:19:48 +0000213
214 const ELFYAML::FileHeader &Hdr = Doc.Header;
215
216 Elf_Ehdr Header;
217 zero(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000218 Header.e_ident[EI_MAG0] = 0x7f;
219 Header.e_ident[EI_MAG1] = 'E';
220 Header.e_ident[EI_MAG2] = 'L';
221 Header.e_ident[EI_MAG3] = 'F';
222 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
223 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
224 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
Sean Silvaf99309c2013-06-10 23:44:15 +0000225 Header.e_ident[EI_VERSION] = EV_CURRENT;
Sean Silvab3a013a2013-06-19 01:10:58 +0000226 Header.e_ident[EI_OSABI] = Hdr.OSABI;
Sean Silvaf99309c2013-06-10 23:44:15 +0000227 Header.e_ident[EI_ABIVERSION] = 0;
228 Header.e_type = Hdr.Type;
229 Header.e_machine = Hdr.Machine;
230 Header.e_version = EV_CURRENT;
231 Header.e_entry = Hdr.Entry;
Sean Silva38205932013-06-13 22:19:48 +0000232 Header.e_ehsize = sizeof(Elf_Ehdr);
Sean Silvaf99309c2013-06-10 23:44:15 +0000233
Sean Silva38205932013-06-13 22:19:48 +0000234 // TODO: Flesh out section header support.
235 // TODO: Program headers.
236
237 Header.e_shentsize = sizeof(Elf_Shdr);
238 // Immediately following the ELF header.
239 Header.e_shoff = sizeof(Header);
Sean Silvabdf19862013-06-18 23:37:23 +0000240 const std::vector<ELFYAML::Section> &Sections = Doc.Sections;
241 // "+ 3" for
242 // - SHT_NULL entry (placed first, i.e. 0'th entry)
243 // - string table (.strtab) (placed second to last)
244 // - section header string table. (placed last)
245 Header.e_shnum = Sections.size() + 3;
Sean Silva38205932013-06-13 22:19:48 +0000246 // Place section header string table last.
Sean Silvabdf19862013-06-18 23:37:23 +0000247 Header.e_shstrndx = Header.e_shnum - 1;
248 const unsigned DotStrtabSecNo = Header.e_shnum - 2;
Sean Silva38205932013-06-13 22:19:48 +0000249
Sean Silva08a75ae2013-06-20 19:11:44 +0000250 // XXX: This offset is tightly coupled with the order that we write
251 // things to `OS`.
252 const size_t SectionContentBeginOffset =
253 Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
254 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
255 ELFState<ELFT> State(Header, CBA, DotStrtabSecNo);
256
Sean Silvaa6423eb2013-06-15 00:25:26 +0000257 SectionNameToIdxMap SN2I;
258 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
259 StringRef Name = Sections[i].Name;
260 if (Name.empty())
261 continue;
Sean Silvabdf19862013-06-18 23:37:23 +0000262 // "+ 1" to take into account the SHT_NULL entry.
263 if (SN2I.addName(Name, i + 1)) {
Sean Silvaa6423eb2013-06-15 00:25:26 +0000264 errs() << "error: Repeated section name: '" << Name
265 << "' at YAML section number " << i << ".\n";
Sean Silva415d93f2013-06-17 20:14:59 +0000266 return 1;
Sean Silvaa6423eb2013-06-15 00:25:26 +0000267 }
268 }
269
Sean Silvafde4ab02013-06-18 01:11:24 +0000270 StringTableBuilder SHStrTab;
Sean Silva38205932013-06-13 22:19:48 +0000271 std::vector<Elf_Shdr> SHeaders;
Sean Silvabdf19862013-06-18 23:37:23 +0000272 {
273 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
274 // valid SHN_UNDEF entry since SHT_NULL == 0.
275 Elf_Shdr SHdr;
276 zero(SHdr);
277 SHeaders.push_back(SHdr);
278 }
Sean Silva38205932013-06-13 22:19:48 +0000279 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
280 const ELFYAML::Section &Sec = Sections[i];
281 Elf_Shdr SHeader;
282 zero(SHeader);
Sean Silvafde4ab02013-06-18 01:11:24 +0000283 SHeader.sh_name = SHStrTab.addString(Sec.Name);
Sean Silva38205932013-06-13 22:19:48 +0000284 SHeader.sh_type = Sec.Type;
285 SHeader.sh_flags = Sec.Flags;
Sean Silvaf4bfced2013-06-13 22:19:54 +0000286 SHeader.sh_addr = Sec.Address;
Sean Silva46dffff2013-06-13 22:20:01 +0000287
288 SHeader.sh_offset = CBA.currentOffset();
289 SHeader.sh_size = Sec.Content.binary_size();
290 Sec.Content.writeAsBinary(CBA.getOS());
291
Sean Silvaa6423eb2013-06-15 00:25:26 +0000292 if (!Sec.Link.empty()) {
293 unsigned Index;
294 if (SN2I.lookupSection(Sec.Link, Index)) {
295 errs() << "error: Unknown section referenced: '" << Sec.Link
296 << "' at YAML section number " << i << ".\n";
Sean Silva415d93f2013-06-17 20:14:59 +0000297 return 1;
Sean Silvaa6423eb2013-06-15 00:25:26 +0000298 }
299 SHeader.sh_link = Index;
300 }
Sean Silva38205932013-06-13 22:19:48 +0000301 SHeader.sh_info = 0;
Sean Silva0a409cf2013-06-14 00:38:02 +0000302 SHeader.sh_addralign = Sec.AddressAlign;
Sean Silva38205932013-06-13 22:19:48 +0000303 SHeader.sh_entsize = 0;
Sean Silva08a75ae2013-06-20 19:11:44 +0000304 // XXX: Really ugly right now. Should not be writing to `CBA` above
305 // (and setting sh_offset and sh_size) when going through this branch
306 // here.
Sean Silva6b083882013-06-18 23:14:03 +0000307 if (Sec.Type == ELFYAML::ELF_SHT(SHT_SYMTAB))
Sean Silva08a75ae2013-06-20 19:11:44 +0000308 handleSymtabSectionHeader<ELFT>(Sec, State, SHeader);
Sean Silva38205932013-06-13 22:19:48 +0000309 SHeaders.push_back(SHeader);
310 }
311
Sean Silva6b083882013-06-18 23:14:03 +0000312 // .strtab string table header.
Sean Silvac3131922013-06-18 21:37:50 +0000313 Elf_Shdr DotStrTabSHeader;
314 zero(DotStrTabSHeader);
315 DotStrTabSHeader.sh_name = SHStrTab.addString(StringRef(".strtab"));
Sean Silva08a75ae2013-06-20 19:11:44 +0000316 createStringTableSectionHeader(DotStrTabSHeader, State.getStringTable(), CBA);
Sean Silvac3131922013-06-18 21:37:50 +0000317
Sean Silvafde4ab02013-06-18 01:11:24 +0000318 // Section header string table header.
319 Elf_Shdr SHStrTabSHeader;
320 zero(SHStrTabSHeader);
Sean Silva85d3eeb2013-06-18 01:11:27 +0000321 createStringTableSectionHeader(SHStrTabSHeader, SHStrTab, CBA);
Sean Silvaf99309c2013-06-10 23:44:15 +0000322
323 OS.write((const char *)&Header, sizeof(Header));
Sean Silva38205932013-06-13 22:19:48 +0000324 writeVectorData(OS, SHeaders);
Sean Silvac3131922013-06-18 21:37:50 +0000325 OS.write((const char *)&DotStrTabSHeader, sizeof(DotStrTabSHeader));
Sean Silvafde4ab02013-06-18 01:11:24 +0000326 OS.write((const char *)&SHStrTabSHeader, sizeof(SHStrTabSHeader));
Sean Silva46dffff2013-06-13 22:20:01 +0000327 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000328 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000329}
330
331int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
332 yaml::Input YIn(Buf->getBuffer());
333 ELFYAML::Object Doc;
334 YIn >> Doc;
335 if (YIn.error()) {
336 errs() << "yaml2obj: Failed to parse YAML file!\n";
337 return 1;
338 }
339 if (Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64)) {
340 if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
Sean Silva415d93f2013-06-17 20:14:59 +0000341 return writeELF<object::ELFType<support::little, 8, true> >(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000342 else
Sean Silva415d93f2013-06-17 20:14:59 +0000343 return writeELF<object::ELFType<support::big, 8, true> >(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000344 } else {
345 if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
Sean Silva415d93f2013-06-17 20:14:59 +0000346 return writeELF<object::ELFType<support::little, 4, false> >(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000347 else
Sean Silva415d93f2013-06-17 20:14:59 +0000348 return writeELF<object::ELFType<support::big, 4, false> >(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000349 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000350}