1 //===- yaml2elf - Convert YAML to a ELF object file -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief The ELF component of yaml2obj.
13 //===----------------------------------------------------------------------===//
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"
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.
29 // This class has a deliberately small interface, since a lot of
30 // implementation variation is possible.
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.
37 class 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.
43 StringTableBuilder() {
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();
53 Buf.append(S.begin(), S.end());
60 void writeToStream(raw_ostream &OS) {
61 OS.write(Buf.data(), Buf.size());
64 } // end anonymous namespace
66 // 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
70 class ContiguousBlobAccumulator {
71 const uint64_t InitialOffset;
72 raw_svector_ostream OS;
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(); }
81 } // end anonymous namespace
83 // Used to keep track of section names, so that in the YAML file sections
84 // can be referenced by name instead of by index.
86 class SectionNameToIdxMap {
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)
94 Entry.setValue((int)i);
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);
106 } // end anonymous namespace
109 static size_t vectorDataSize(const std::vector<T> &Vec) {
110 return Vec.size() * sizeof(T);
114 static void writeVectorData(raw_ostream &OS, const std::vector<T> &Vec) {
115 OS.write((const char *)Vec.data(), vectorDataSize(Vec));
119 static void zero(T &Obj) {
120 memset(&Obj, 0, sizeof(Obj));
123 /// \brief Create a string table in `SHeader`, which we assume is already
125 template <class Elf_Shdr>
126 static 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;
136 // FIXME: This function is hideous. Between the sheer number of parameters
137 // and the hideous ELF typenames, it's just a travesty. Factor the ELF
138 // output into a class (templated on ELFT) and share some typedefs.
139 template <class ELFT>
140 static void handleSymtabSectionHeader(
141 const ELFYAML::Section &Sec,
142 const typename object::ELFObjectFile<ELFT>::Elf_Ehdr &Header,
143 typename object::ELFObjectFile<ELFT>::Elf_Shdr &SHeader,
144 StringTableBuilder &StrTab, ContiguousBlobAccumulator &CBA,
145 unsigned DotStrtabSecNo) {
147 typedef typename object::ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
148 // TODO: Ensure that a manually specified `Link` field is diagnosed as an
149 // error for SHT_SYMTAB.
150 SHeader.sh_link = DotStrtabSecNo;
151 // TODO: Once we handle symbol binding, this should be one greater than
152 // symbol table index of the last local symbol.
154 SHeader.sh_entsize = sizeof(Elf_Sym);
156 std::vector<Elf_Sym> Syms;
158 // Ensure STN_UNDEF is present
163 for (unsigned i = 0, e = Sec.Symbols.size(); i != e; ++i) {
164 const ELFYAML::Symbol &Sym = Sec.Symbols[i];
167 if (!Sym.Name.empty())
168 Symbol.st_name = StrTab.addString(Sym.Name);
169 Syms.push_back(Symbol);
172 SHeader.sh_offset = CBA.currentOffset();
173 SHeader.sh_size = vectorDataSize(Syms);
174 writeVectorData(CBA.getOS(), Syms);
177 template <class ELFT>
178 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
179 using namespace llvm::ELF;
180 using namespace llvm::object;
181 typedef typename ELFObjectFile<ELFT>::Elf_Ehdr Elf_Ehdr;
182 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
184 const ELFYAML::FileHeader &Hdr = Doc.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 // TODO: Implement ELF_ELFOSABI enum.
197 Header.e_ident[EI_OSABI] = ELFOSABI_NONE;
198 // TODO: Implement ELF_ABIVERSION enum.
199 Header.e_ident[EI_ABIVERSION] = 0;
200 Header.e_type = Hdr.Type;
201 Header.e_machine = Hdr.Machine;
202 Header.e_version = EV_CURRENT;
203 Header.e_entry = Hdr.Entry;
204 Header.e_ehsize = sizeof(Elf_Ehdr);
206 // TODO: Flesh out section header support.
207 // TODO: Program headers.
209 Header.e_shentsize = sizeof(Elf_Shdr);
210 // Immediately following the ELF header.
211 Header.e_shoff = sizeof(Header);
212 const std::vector<ELFYAML::Section> &Sections = Doc.Sections;
214 // - SHT_NULL entry (placed first, i.e. 0'th entry)
215 // - string table (.strtab) (placed second to last)
216 // - section header string table. (placed last)
217 Header.e_shnum = Sections.size() + 3;
218 // Place section header string table last.
219 Header.e_shstrndx = Header.e_shnum - 1;
220 const unsigned DotStrtabSecNo = Header.e_shnum - 2;
222 SectionNameToIdxMap SN2I;
223 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
224 StringRef Name = Sections[i].Name;
227 // "+ 1" to take into account the SHT_NULL entry.
228 if (SN2I.addName(Name, i + 1)) {
229 errs() << "error: Repeated section name: '" << Name
230 << "' at YAML section number " << i << ".\n";
235 StringTableBuilder SHStrTab;
236 SmallVector<char, 128> Buf;
237 // XXX: This offset is tightly coupled with the order that we write
239 const size_t SectionContentBeginOffset =
240 Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
241 ContiguousBlobAccumulator CBA(SectionContentBeginOffset, Buf);
242 std::vector<Elf_Shdr> SHeaders;
244 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
245 // valid SHN_UNDEF entry since SHT_NULL == 0.
248 SHeaders.push_back(SHdr);
250 StringTableBuilder DotStrTab;
251 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
252 const ELFYAML::Section &Sec = Sections[i];
255 SHeader.sh_name = SHStrTab.addString(Sec.Name);
256 SHeader.sh_type = Sec.Type;
257 SHeader.sh_flags = Sec.Flags;
258 SHeader.sh_addr = Sec.Address;
260 SHeader.sh_offset = CBA.currentOffset();
261 SHeader.sh_size = Sec.Content.binary_size();
262 Sec.Content.writeAsBinary(CBA.getOS());
264 if (!Sec.Link.empty()) {
266 if (SN2I.lookupSection(Sec.Link, Index)) {
267 errs() << "error: Unknown section referenced: '" << Sec.Link
268 << "' at YAML section number " << i << ".\n";
271 SHeader.sh_link = Index;
274 SHeader.sh_addralign = Sec.AddressAlign;
275 SHeader.sh_entsize = 0;
276 // XXX: Really ugly right now. Need to put common state into a class.
277 if (Sec.Type == ELFYAML::ELF_SHT(SHT_SYMTAB))
278 handleSymtabSectionHeader<ELFT>(Sec, Header, SHeader, DotStrTab, CBA,
280 SHeaders.push_back(SHeader);
283 // .strtab string table header.
284 Elf_Shdr DotStrTabSHeader;
285 zero(DotStrTabSHeader);
286 DotStrTabSHeader.sh_name = SHStrTab.addString(StringRef(".strtab"));
287 createStringTableSectionHeader(DotStrTabSHeader, DotStrTab, CBA);
289 // Section header string table header.
290 Elf_Shdr SHStrTabSHeader;
291 zero(SHStrTabSHeader);
292 createStringTableSectionHeader(SHStrTabSHeader, SHStrTab, CBA);
294 OS.write((const char *)&Header, sizeof(Header));
295 writeVectorData(OS, SHeaders);
296 OS.write((const char *)&DotStrTabSHeader, sizeof(DotStrTabSHeader));
297 OS.write((const char *)&SHStrTabSHeader, sizeof(SHStrTabSHeader));
298 CBA.writeBlobToStream(OS);
302 int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
303 yaml::Input YIn(Buf->getBuffer());
307 errs() << "yaml2obj: Failed to parse YAML file!\n";
310 if (Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64)) {
311 if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
312 return writeELF<object::ELFType<support::little, 8, true> >(outs(), Doc);
314 return writeELF<object::ELFType<support::big, 8, true> >(outs(), Doc);
316 if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
317 return writeELF<object::ELFType<support::little, 4, false> >(outs(), Doc);
319 return writeELF<object::ELFType<support::big, 4, false> >(outs(), Doc);