blob: 4e9ee4dcd671183eec8d8b12d117d8d5dd86b630 [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"
Will Dietz0b48c732013-10-12 21:29:16 +000016#include "llvm/ADT/ArrayRef.h"
Michael J. Spencer126973b2013-08-08 22:27:13 +000017#include "llvm/Object/ELFObjectFile.h"
Sean Silvaf99309c2013-06-10 23:44:15 +000018#include "llvm/Object/ELFYAML.h"
19#include "llvm/Support/ELF.h"
20#include "llvm/Support/MemoryBuffer.h"
21#include "llvm/Support/YAMLTraits.h"
22#include "llvm/Support/raw_ostream.h"
23
24using namespace llvm;
25
Sean Silva38205932013-06-13 22:19:48 +000026// There is similar code in yaml2coff, but with some slight COFF-specific
27// variations like different initial state. Might be able to deduplicate
28// some day, but also want to make sure that the Mach-O use case is served.
29//
30// This class has a deliberately small interface, since a lot of
31// implementation variation is possible.
32//
33// TODO: Use an ordered container with a suffix-based comparison in order
34// to deduplicate suffixes. std::map<> with a custom comparator is likely
35// to be the simplest implementation, but a suffix trie could be more
36// suitable for the job.
Sean Silva2a74f702013-06-15 00:31:46 +000037namespace {
Sean Silva38205932013-06-13 22:19:48 +000038class StringTableBuilder {
39 /// \brief Indices of strings currently present in `Buf`.
40 StringMap<unsigned> StringIndices;
41 /// \brief The contents of the string table as we build it.
42 std::string Buf;
43public:
44 StringTableBuilder() {
45 Buf.push_back('\0');
46 }
47 /// \returns Index of string in string table.
48 unsigned addString(StringRef S) {
49 StringMapEntry<unsigned> &Entry = StringIndices.GetOrCreateValue(S);
50 unsigned &I = Entry.getValue();
51 if (I != 0)
52 return I;
53 I = Buf.size();
54 Buf.append(S.begin(), S.end());
55 Buf.push_back('\0');
56 return I;
57 }
58 size_t size() const {
59 return Buf.size();
60 }
61 void writeToStream(raw_ostream &OS) {
62 OS.write(Buf.data(), Buf.size());
63 }
64};
Sean Silva2a74f702013-06-15 00:31:46 +000065} // end anonymous namespace
Sean Silva38205932013-06-13 22:19:48 +000066
Sean Silva46dffff2013-06-13 22:20:01 +000067// This class is used to build up a contiguous binary blob while keeping
68// track of an offset in the output (which notionally begins at
69// `InitialOffset`).
Sean Silva2a74f702013-06-15 00:31:46 +000070namespace {
Sean Silva46dffff2013-06-13 22:20:01 +000071class ContiguousBlobAccumulator {
72 const uint64_t InitialOffset;
Sean Silvabd3bc692013-06-20 19:11:41 +000073 SmallVector<char, 128> Buf;
Sean Silva46dffff2013-06-13 22:20:01 +000074 raw_svector_ostream OS;
75
Sean Silvad93323f2013-06-22 00:47:43 +000076 /// \returns The new offset.
77 uint64_t padToAlignment(unsigned Align) {
78 uint64_t CurrentOffset = InitialOffset + OS.tell();
79 uint64_t AlignedOffset = RoundUpToAlignment(CurrentOffset, Align);
80 for (; CurrentOffset != AlignedOffset; ++CurrentOffset)
81 OS.write('\0');
82 return AlignedOffset; // == CurrentOffset;
83 }
84
Sean Silva46dffff2013-06-13 22:20:01 +000085public:
Sean Silvabd3bc692013-06-20 19:11:41 +000086 ContiguousBlobAccumulator(uint64_t InitialOffset_)
87 : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
Sean Silvad93323f2013-06-22 00:47:43 +000088 template <class Integer>
89 raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align = 16) {
90 Offset = padToAlignment(Align);
91 return OS;
92 }
Sean Silva46dffff2013-06-13 22:20:01 +000093 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
94};
Sean Silva2a74f702013-06-15 00:31:46 +000095} // end anonymous namespace
Sean Silva46dffff2013-06-13 22:20:01 +000096
Simon Atanasyan35babf92014-04-06 09:02:55 +000097// Used to keep track of section and symbol names, so that in the YAML file
98// sections and symbols can be referenced by name instead of by index.
Sean Silva2a74f702013-06-15 00:31:46 +000099namespace {
Simon Atanasyan35babf92014-04-06 09:02:55 +0000100class NameToIdxMap {
Sean Silvaa6423eb2013-06-15 00:25:26 +0000101 StringMap<int> Map;
102public:
103 /// \returns true if name is already present in the map.
Simon Atanasyan35babf92014-04-06 09:02:55 +0000104 bool addName(StringRef Name, unsigned i) {
105 StringMapEntry<int> &Entry = Map.GetOrCreateValue(Name, -1);
Sean Silvaa6423eb2013-06-15 00:25:26 +0000106 if (Entry.getValue() != -1)
107 return true;
108 Entry.setValue((int)i);
109 return false;
110 }
111 /// \returns true if name is not present in the map
Simon Atanasyan35babf92014-04-06 09:02:55 +0000112 bool lookup(StringRef Name, unsigned &Idx) const {
113 StringMap<int>::const_iterator I = Map.find(Name);
Sean Silvaa6423eb2013-06-15 00:25:26 +0000114 if (I == Map.end())
115 return true;
116 Idx = I->getValue();
117 return false;
118 }
119};
Sean Silva2a74f702013-06-15 00:31:46 +0000120} // end anonymous namespace
Sean Silvaa6423eb2013-06-15 00:25:26 +0000121
Sean Silva38205932013-06-13 22:19:48 +0000122template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +0000123static size_t arrayDataSize(ArrayRef<T> A) {
124 return A.size() * sizeof(T);
Sean Silva38205932013-06-13 22:19:48 +0000125}
126
127template <class T>
Will Dietz0b48c732013-10-12 21:29:16 +0000128static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
129 OS.write((const char *)A.data(), arrayDataSize(A));
Sean Silva38205932013-06-13 22:19:48 +0000130}
131
132template <class T>
133static void zero(T &Obj) {
134 memset(&Obj, 0, sizeof(Obj));
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 {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000143 typedef typename object::ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
144 typedef typename object::ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
145 typedef typename object::ELFFile<ELFT>::Elf_Sym Elf_Sym;
146
Sean Silva08a75ae2013-06-20 19:11:44 +0000147 /// \brief The future ".strtab" section.
148 StringTableBuilder DotStrtab;
Sean Silva08a75ae2013-06-20 19:11:44 +0000149
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000150 /// \brief The future ".shstrtab" section.
151 StringTableBuilder DotShStrtab;
152
Simon Atanasyan35babf92014-04-06 09:02:55 +0000153 NameToIdxMap SN2I;
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000154 const ELFYAML::Object &Doc;
Sean Silvac1c290b2013-06-20 20:59:34 +0000155
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000156 bool buildSectionIndex();
157 void initELFHeader(Elf_Ehdr &Header);
158 bool initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
159 ContiguousBlobAccumulator &CBA);
160 void initSymtabSectionHeader(Elf_Shdr &SHeader,
161 ContiguousBlobAccumulator &CBA);
162 void initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
163 StringTableBuilder &STB,
164 ContiguousBlobAccumulator &CBA);
165 void addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
166 std::vector<Elf_Sym> &Syms, unsigned SymbolBinding);
Sean Silva08a75ae2013-06-20 19:11:44 +0000167
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000168 // - SHT_NULL entry (placed first, i.e. 0'th entry)
169 // - symbol table (.symtab) (placed third to last)
170 // - string table (.strtab) (placed second to last)
171 // - section header string table (.shstrtab) (placed last)
172 unsigned getDotSymTabSecNo() const { return Doc.Sections.size() + 1; }
173 unsigned getDotStrTabSecNo() const { return Doc.Sections.size() + 2; }
174 unsigned getDotShStrTabSecNo() const { return Doc.Sections.size() + 3; }
175 unsigned getSectionCount() const { return Doc.Sections.size() + 4; }
176
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000177 ELFState(const ELFYAML::Object &D) : Doc(D) {}
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000178
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000179public:
180 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc);
Sean Silva08a75ae2013-06-20 19:11:44 +0000181};
182} // end anonymous namespace
183
Sean Silva37e817c2013-06-21 00:33:01 +0000184template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000185void ELFState<ELFT>::initELFHeader(Elf_Ehdr &Header) {
186 using namespace llvm::ELF;
187 zero(Header);
188 Header.e_ident[EI_MAG0] = 0x7f;
189 Header.e_ident[EI_MAG1] = 'E';
190 Header.e_ident[EI_MAG2] = 'L';
191 Header.e_ident[EI_MAG3] = 'F';
192 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
193 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
194 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
195 Header.e_ident[EI_VERSION] = EV_CURRENT;
196 Header.e_ident[EI_OSABI] = Doc.Header.OSABI;
197 Header.e_ident[EI_ABIVERSION] = 0;
198 Header.e_type = Doc.Header.Type;
199 Header.e_machine = Doc.Header.Machine;
200 Header.e_version = EV_CURRENT;
201 Header.e_entry = Doc.Header.Entry;
202 Header.e_flags = Doc.Header.Flags;
203 Header.e_ehsize = sizeof(Elf_Ehdr);
204 Header.e_shentsize = sizeof(Elf_Shdr);
205 // Immediately following the ELF header.
206 Header.e_shoff = sizeof(Header);
207 Header.e_shnum = getSectionCount();
208 Header.e_shstrndx = getDotShStrTabSecNo();
209}
210
211template <class ELFT>
212bool ELFState<ELFT>::initSectionHeaders(std::vector<Elf_Shdr> &SHeaders,
213 ContiguousBlobAccumulator &CBA) {
214 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
215 // valid SHN_UNDEF entry since SHT_NULL == 0.
216 Elf_Shdr SHeader;
217 zero(SHeader);
218 SHeaders.push_back(SHeader);
219
220 for (const auto &Sec : Doc.Sections) {
221 zero(SHeader);
222 SHeader.sh_name = DotShStrtab.addString(Sec.Name);
223 SHeader.sh_type = Sec.Type;
224 SHeader.sh_flags = Sec.Flags;
225 SHeader.sh_addr = Sec.Address;
226
227 Sec.Content.writeAsBinary(CBA.getOSAndAlignedOffset(SHeader.sh_offset));
228 SHeader.sh_size = Sec.Content.binary_size();
229
230 if (!Sec.Link.empty()) {
231 unsigned Index;
Simon Atanasyan35babf92014-04-06 09:02:55 +0000232 if (SN2I.lookup(Sec.Link, Index)) {
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000233 errs() << "error: Unknown section referenced: '" << Sec.Link
234 << "' at YAML section '" << Sec.Name << "'.\n";
235 return false;;
236 }
237 SHeader.sh_link = Index;
238 }
239 SHeader.sh_info = 0;
240 SHeader.sh_addralign = Sec.AddressAlign;
241 SHeader.sh_entsize = 0;
242 SHeaders.push_back(SHeader);
243 }
244 return true;
245}
246
247template <class ELFT>
248void ELFState<ELFT>::initSymtabSectionHeader(Elf_Shdr &SHeader,
249 ContiguousBlobAccumulator &CBA) {
250 zero(SHeader);
251 SHeader.sh_name = DotShStrtab.addString(StringRef(".symtab"));
252 SHeader.sh_type = ELF::SHT_SYMTAB;
253 SHeader.sh_link = getDotStrTabSecNo();
254 // One greater than symbol table index of the last local symbol.
255 SHeader.sh_info = Doc.Symbols.Local.size() + 1;
256 SHeader.sh_entsize = sizeof(Elf_Sym);
257
258 std::vector<Elf_Sym> Syms;
259 {
260 // Ensure STN_UNDEF is present
261 Elf_Sym Sym;
262 zero(Sym);
263 Syms.push_back(Sym);
264 }
265 addSymbols(Doc.Symbols.Local, Syms, ELF::STB_LOCAL);
266 addSymbols(Doc.Symbols.Global, Syms, ELF::STB_GLOBAL);
267 addSymbols(Doc.Symbols.Weak, Syms, ELF::STB_WEAK);
268
269 writeArrayData(CBA.getOSAndAlignedOffset(SHeader.sh_offset),
270 makeArrayRef(Syms));
271 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
272}
273
274template <class ELFT>
275void ELFState<ELFT>::initStrtabSectionHeader(Elf_Shdr &SHeader, StringRef Name,
276 StringTableBuilder &STB,
277 ContiguousBlobAccumulator &CBA) {
278 zero(SHeader);
279 SHeader.sh_name = DotShStrtab.addString(Name);
280 SHeader.sh_type = ELF::SHT_STRTAB;
281 STB.writeToStream(CBA.getOSAndAlignedOffset(SHeader.sh_offset));
282 SHeader.sh_size = STB.size();
283 SHeader.sh_addralign = 1;
284}
285
286template <class ELFT>
287void ELFState<ELFT>::addSymbols(const std::vector<ELFYAML::Symbol> &Symbols,
288 std::vector<Elf_Sym> &Syms,
289 unsigned SymbolBinding) {
Simon Atanasyan048baca2014-03-14 06:53:30 +0000290 for (const auto &Sym : Symbols) {
Sean Silva6b083882013-06-18 23:14:03 +0000291 Elf_Sym Symbol;
292 zero(Symbol);
293 if (!Sym.Name.empty())
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000294 Symbol.st_name = DotStrtab.addString(Sym.Name);
Sean Silvaaff51252013-06-21 00:27:50 +0000295 Symbol.setBindingAndType(SymbolBinding, Sym.Type);
Sean Silvac4afa6d2013-06-21 01:11:48 +0000296 if (!Sym.Section.empty()) {
297 unsigned Index;
Simon Atanasyan35babf92014-04-06 09:02:55 +0000298 if (SN2I.lookup(Sym.Section, Index)) {
Sean Silvac4afa6d2013-06-21 01:11:48 +0000299 errs() << "error: Unknown section referenced: '" << Sym.Section
300 << "' by YAML symbol " << Sym.Name << ".\n";
301 exit(1);
302 }
303 Symbol.st_shndx = Index;
304 } // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
Sean Silva05001b92013-06-20 20:59:47 +0000305 Symbol.st_value = Sym.Value;
306 Symbol.st_size = Sym.Size;
Sean Silva6b083882013-06-18 23:14:03 +0000307 Syms.push_back(Symbol);
308 }
Sean Silvaaff51252013-06-21 00:27:50 +0000309}
310
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000311template <class ELFT> bool ELFState<ELFT>::buildSectionIndex() {
312 SN2I.addName(".symtab", getDotSymTabSecNo());
313 SN2I.addName(".strtab", getDotStrTabSecNo());
314 SN2I.addName(".shstrtab", getDotShStrTabSecNo());
Sean Silvaaff51252013-06-21 00:27:50 +0000315
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000316 for (unsigned i = 0, e = Doc.Sections.size(); i != e; ++i) {
317 StringRef Name = Doc.Sections[i].Name;
318 if (Name.empty())
319 continue;
320 // "+ 1" to take into account the SHT_NULL entry.
321 if (SN2I.addName(Name, i + 1)) {
322 errs() << "error: Repeated section name: '" << Name
323 << "' at YAML section number " << i << ".\n";
324 return false;
325 }
Sean Silvaaff51252013-06-21 00:27:50 +0000326 }
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000327 return true;
Sean Silva6b083882013-06-18 23:14:03 +0000328}
329
Sean Silvaf99309c2013-06-10 23:44:15 +0000330template <class ELFT>
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000331int ELFState<ELFT>::writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
Simon Atanasyan220c54a2014-04-02 16:34:40 +0000332 ELFState<ELFT> State(Doc);
333 if (!State.buildSectionIndex())
334 return 1;
335
Sean Silva38205932013-06-13 22:19:48 +0000336 Elf_Ehdr Header;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000337 State.initELFHeader(Header);
Sean Silvaf99309c2013-06-10 23:44:15 +0000338
Sean Silva38205932013-06-13 22:19:48 +0000339 // TODO: Flesh out section header support.
340 // TODO: Program headers.
341
Sean Silva08a75ae2013-06-20 19:11:44 +0000342 // XXX: This offset is tightly coupled with the order that we write
343 // things to `OS`.
344 const size_t SectionContentBeginOffset =
345 Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
346 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
Sean Silvac1c290b2013-06-20 20:59:34 +0000347
Sean Silva38205932013-06-13 22:19:48 +0000348 std::vector<Elf_Shdr> SHeaders;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000349 if(!State.initSectionHeaders(SHeaders, CBA))
350 return 1;
Sean Silva38205932013-06-13 22:19:48 +0000351
Sean Silva82177572013-06-22 01:38:00 +0000352 // .symtab section.
353 Elf_Shdr SymtabSHeader;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000354 State.initSymtabSectionHeader(SymtabSHeader, CBA);
Sean Silva82177572013-06-22 01:38:00 +0000355 SHeaders.push_back(SymtabSHeader);
356
Sean Silva6b083882013-06-18 23:14:03 +0000357 // .strtab string table header.
Sean Silvac3131922013-06-18 21:37:50 +0000358 Elf_Shdr DotStrTabSHeader;
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000359 State.initStrtabSectionHeader(DotStrTabSHeader, ".strtab", State.DotStrtab,
360 CBA);
Sean Silva7d617222013-06-22 01:06:12 +0000361 SHeaders.push_back(DotStrTabSHeader);
Sean Silvac3131922013-06-18 21:37:50 +0000362
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000363 // .shstrtab string table header.
364 Elf_Shdr ShStrTabSHeader;
365 State.initStrtabSectionHeader(ShStrTabSHeader, ".shstrtab", State.DotShStrtab,
366 CBA);
367 SHeaders.push_back(ShStrTabSHeader);
Sean Silvaf99309c2013-06-10 23:44:15 +0000368
369 OS.write((const char *)&Header, sizeof(Header));
Will Dietz0b48c732013-10-12 21:29:16 +0000370 writeArrayData(OS, makeArrayRef(SHeaders));
Sean Silva46dffff2013-06-13 22:20:01 +0000371 CBA.writeBlobToStream(OS);
Sean Silva415d93f2013-06-17 20:14:59 +0000372 return 0;
Sean Silvaf99309c2013-06-10 23:44:15 +0000373}
374
Sean Silva11caeba2013-06-22 01:03:35 +0000375static bool is64Bit(const ELFYAML::Object &Doc) {
376 return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
377}
378
379static bool isLittleEndian(const ELFYAML::Object &Doc) {
380 return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
381}
382
Sean Silvaf99309c2013-06-10 23:44:15 +0000383int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
384 yaml::Input YIn(Buf->getBuffer());
385 ELFYAML::Object Doc;
386 YIn >> Doc;
387 if (YIn.error()) {
388 errs() << "yaml2obj: Failed to parse YAML file!\n";
389 return 1;
390 }
Sean Silva11caeba2013-06-22 01:03:35 +0000391 using object::ELFType;
392 typedef ELFType<support::little, 8, true> LE64;
393 typedef ELFType<support::big, 8, true> BE64;
394 typedef ELFType<support::little, 4, false> LE32;
395 typedef ELFType<support::big, 4, false> BE32;
396 if (is64Bit(Doc)) {
397 if (isLittleEndian(Doc))
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000398 return ELFState<LE64>::writeELF(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000399 else
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000400 return ELFState<BE64>::writeELF(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000401 } else {
Sean Silva11caeba2013-06-22 01:03:35 +0000402 if (isLittleEndian(Doc))
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000403 return ELFState<LE32>::writeELF(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000404 else
Simon Atanasyan3ee21b02014-04-02 16:34:54 +0000405 return ELFState<BE32>::writeELF(outs(), Doc);
Sean Silvaf99309c2013-06-10 23:44:15 +0000406 }
Sean Silvaf99309c2013-06-10 23:44:15 +0000407}