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 template <class ELFT>
124 static void writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
125 using namespace llvm::ELF;
126 using namespace llvm::object;
127 typedef typename ELFObjectFile<ELFT>::Elf_Ehdr Elf_Ehdr;
128 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
130 const ELFYAML::FileHeader &Hdr = Doc.Header;
134 Header.e_ident[EI_MAG0] = 0x7f;
135 Header.e_ident[EI_MAG1] = 'E';
136 Header.e_ident[EI_MAG2] = 'L';
137 Header.e_ident[EI_MAG3] = 'F';
138 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
139 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
140 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
141 Header.e_ident[EI_VERSION] = EV_CURRENT;
142 // TODO: Implement ELF_ELFOSABI enum.
143 Header.e_ident[EI_OSABI] = ELFOSABI_NONE;
144 // TODO: Implement ELF_ABIVERSION enum.
145 Header.e_ident[EI_ABIVERSION] = 0;
146 Header.e_type = Hdr.Type;
147 Header.e_machine = Hdr.Machine;
148 Header.e_version = EV_CURRENT;
149 Header.e_entry = Hdr.Entry;
150 Header.e_ehsize = sizeof(Elf_Ehdr);
152 // TODO: Flesh out section header support.
153 // TODO: Program headers.
155 Header.e_shentsize = sizeof(Elf_Shdr);
156 // Immediately following the ELF header.
157 Header.e_shoff = sizeof(Header);
158 std::vector<ELFYAML::Section> Sections = Doc.Sections;
159 if (Sections.empty() || Sections.front().Type != SHT_NULL) {
163 Sections.insert(Sections.begin(), S);
165 // "+ 1" for string table.
166 Header.e_shnum = Sections.size() + 1;
167 // Place section header string table last.
168 Header.e_shstrndx = Sections.size();
170 SectionNameToIdxMap SN2I;
171 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
172 StringRef Name = Sections[i].Name;
175 if (SN2I.addName(Name, i)) {
176 errs() << "error: Repeated section name: '" << Name
177 << "' at YAML section number " << i << ".\n";
182 StringTableBuilder StrTab;
183 SmallVector<char, 128> Buf;
184 // XXX: This offset is tightly coupled with the order that we write
186 const size_t SectionContentBeginOffset =
187 Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
188 ContiguousBlobAccumulator CBA(SectionContentBeginOffset, Buf);
189 std::vector<Elf_Shdr> SHeaders;
190 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
191 const ELFYAML::Section &Sec = Sections[i];
194 SHeader.sh_name = StrTab.addString(Sec.Name);
195 SHeader.sh_type = Sec.Type;
196 SHeader.sh_flags = Sec.Flags;
197 SHeader.sh_addr = Sec.Address;
199 SHeader.sh_offset = CBA.currentOffset();
200 SHeader.sh_size = Sec.Content.binary_size();
201 Sec.Content.writeAsBinary(CBA.getOS());
203 if (!Sec.Link.empty()) {
205 if (SN2I.lookupSection(Sec.Link, Index)) {
206 errs() << "error: Unknown section referenced: '" << Sec.Link
207 << "' at YAML section number " << i << ".\n";
210 SHeader.sh_link = Index;
213 SHeader.sh_addralign = Sec.AddressAlign;
214 SHeader.sh_entsize = 0;
215 SHeaders.push_back(SHeader);
218 // String table header.
219 Elf_Shdr StrTabSHeader;
221 StrTabSHeader.sh_name = 0;
222 StrTabSHeader.sh_type = SHT_STRTAB;
223 StrTabSHeader.sh_flags = 0;
224 StrTabSHeader.sh_addr = 0;
225 StrTabSHeader.sh_offset = CBA.currentOffset();
226 StrTabSHeader.sh_size = StrTab.size();
227 StrTab.writeToStream(CBA.getOS());
228 StrTabSHeader.sh_link = 0;
229 StrTabSHeader.sh_info = 0;
230 StrTabSHeader.sh_addralign = 1;
231 StrTabSHeader.sh_entsize = 0;
233 OS.write((const char *)&Header, sizeof(Header));
234 writeVectorData(OS, SHeaders);
235 OS.write((const char *)&StrTabSHeader, sizeof(StrTabSHeader));
236 CBA.writeBlobToStream(OS);
239 int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
240 yaml::Input YIn(Buf->getBuffer());
244 errs() << "yaml2obj: Failed to parse YAML file!\n";
247 if (Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64)) {
248 if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
249 writeELF<object::ELFType<support::little, 8, true> >(outs(), Doc);
251 writeELF<object::ELFType<support::big, 8, true> >(outs(), Doc);
253 if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
254 writeELF<object::ELFType<support::little, 4, false> >(outs(), Doc);
256 writeELF<object::ELFType<support::big, 4, false> >(outs(), Doc);