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/ELFObjectFile.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 SmallVector<char, 128> Buf;
73 raw_svector_ostream OS;
75 /// \returns The new offset.
76 uint64_t padToAlignment(unsigned Align) {
77 uint64_t CurrentOffset = InitialOffset + OS.tell();
78 uint64_t AlignedOffset = RoundUpToAlignment(CurrentOffset, Align);
79 for (; CurrentOffset != AlignedOffset; ++CurrentOffset)
81 return AlignedOffset; // == CurrentOffset;
85 ContiguousBlobAccumulator(uint64_t InitialOffset_)
86 : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
87 template <class Integer>
88 raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align = 16) {
89 Offset = padToAlignment(Align);
92 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
94 } // end anonymous namespace
96 // Used to keep track of section names, so that in the YAML file sections
97 // can be referenced by name instead of by index.
99 class SectionNameToIdxMap {
102 /// \returns true if name is already present in the map.
103 bool addName(StringRef SecName, unsigned i) {
104 StringMapEntry<int> &Entry = Map.GetOrCreateValue(SecName, -1);
105 if (Entry.getValue() != -1)
107 Entry.setValue((int)i);
110 /// \returns true if name is not present in the map
111 bool lookupSection(StringRef SecName, unsigned &Idx) const {
112 StringMap<int>::const_iterator I = Map.find(SecName);
119 } // end anonymous namespace
122 static size_t vectorDataSize(const std::vector<T> &Vec) {
123 return Vec.size() * sizeof(T);
127 static void writeVectorData(raw_ostream &OS, const std::vector<T> &Vec) {
128 OS.write((const char *)Vec.data(), vectorDataSize(Vec));
132 static void zero(T &Obj) {
133 memset(&Obj, 0, sizeof(Obj));
136 /// \brief Create a string table in `SHeader`, which we assume is already
138 template <class Elf_Shdr>
139 static void createStringTableSectionHeader(Elf_Shdr &SHeader,
140 StringTableBuilder &STB,
141 ContiguousBlobAccumulator &CBA) {
142 SHeader.sh_type = ELF::SHT_STRTAB;
143 STB.writeToStream(CBA.getOSAndAlignedOffset(SHeader.sh_offset));
144 SHeader.sh_size = STB.size();
145 SHeader.sh_addralign = 1;
149 /// \brief "Single point of truth" for the ELF file construction.
150 /// TODO: This class still has a ways to go before it is truly a "single
152 template <class ELFT>
154 /// \brief The future ".strtab" section.
155 StringTableBuilder DotStrtab;
156 /// \brief The section number of the ".strtab" section.
157 unsigned DotStrtabSecNo;
158 /// \brief The accumulated contents of all sections so far.
159 ContiguousBlobAccumulator &SectionContentAccum;
160 typedef typename object::ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
161 /// \brief The ELF file header.
164 SectionNameToIdxMap &SN2I;
168 ELFState(Elf_Ehdr &Header_, ContiguousBlobAccumulator &Accum,
169 unsigned DotStrtabSecNo_, SectionNameToIdxMap &SN2I_)
170 : DotStrtab(), DotStrtabSecNo(DotStrtabSecNo_),
171 SectionContentAccum(Accum), Header(Header_), SN2I(SN2I_) {}
173 unsigned getDotStrTabSecNo() const { return DotStrtabSecNo; }
174 StringTableBuilder &getStringTable() { return DotStrtab; }
175 ContiguousBlobAccumulator &getSectionContentAccum() {
176 return SectionContentAccum;
178 SectionNameToIdxMap &getSN2I() { return SN2I; }
180 } // end anonymous namespace
182 // FIXME: At this point it is fairly clear that we need to refactor these
183 // static functions into methods of a class sharing some typedefs. These
184 // ELF type names are insane.
185 template <class ELFT>
187 addSymbols(const std::vector<ELFYAML::Symbol> &Symbols, ELFState<ELFT> &State,
188 std::vector<typename object::ELFFile<ELFT>::Elf_Sym> &Syms,
189 unsigned SymbolBinding) {
190 typedef typename object::ELFFile<ELFT>::Elf_Sym Elf_Sym;
191 for (unsigned i = 0, e = Symbols.size(); i != e; ++i) {
192 const ELFYAML::Symbol &Sym = Symbols[i];
195 if (!Sym.Name.empty())
196 Symbol.st_name = State.getStringTable().addString(Sym.Name);
197 Symbol.setBindingAndType(SymbolBinding, Sym.Type);
198 if (!Sym.Section.empty()) {
200 if (State.getSN2I().lookupSection(Sym.Section, Index)) {
201 errs() << "error: Unknown section referenced: '" << Sym.Section
202 << "' by YAML symbol " << Sym.Name << ".\n";
205 Symbol.st_shndx = Index;
206 } // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
207 Symbol.st_value = Sym.Value;
208 Symbol.st_size = Sym.Size;
209 Syms.push_back(Symbol);
213 template <class ELFT>
215 handleSymtabSectionHeader(const ELFYAML::LocalGlobalWeakSymbols &Symbols,
216 ELFState<ELFT> &State,
217 typename object::ELFFile<ELFT>::Elf_Shdr &SHeader) {
219 typedef typename object::ELFFile<ELFT>::Elf_Sym Elf_Sym;
220 SHeader.sh_type = ELF::SHT_SYMTAB;
221 SHeader.sh_link = State.getDotStrTabSecNo();
222 // One greater than symbol table index of the last local symbol.
223 SHeader.sh_info = Symbols.Local.size() + 1;
224 SHeader.sh_entsize = sizeof(Elf_Sym);
226 std::vector<Elf_Sym> Syms;
228 // Ensure STN_UNDEF is present
233 addSymbols(Symbols.Local, State, Syms, ELF::STB_LOCAL);
234 addSymbols(Symbols.Global, State, Syms, ELF::STB_GLOBAL);
235 addSymbols(Symbols.Weak, State, Syms, ELF::STB_WEAK);
237 ContiguousBlobAccumulator &CBA = State.getSectionContentAccum();
238 writeVectorData(CBA.getOSAndAlignedOffset(SHeader.sh_offset), Syms);
239 SHeader.sh_size = vectorDataSize(Syms);
242 template <class ELFT>
243 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
244 using namespace llvm::ELF;
245 typedef typename object::ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
246 typedef typename object::ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
248 const ELFYAML::FileHeader &Hdr = Doc.Header;
252 Header.e_ident[EI_MAG0] = 0x7f;
253 Header.e_ident[EI_MAG1] = 'E';
254 Header.e_ident[EI_MAG2] = 'L';
255 Header.e_ident[EI_MAG3] = 'F';
256 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
257 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
258 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
259 Header.e_ident[EI_VERSION] = EV_CURRENT;
260 Header.e_ident[EI_OSABI] = Hdr.OSABI;
261 Header.e_ident[EI_ABIVERSION] = 0;
262 Header.e_type = Hdr.Type;
263 Header.e_machine = Hdr.Machine;
264 Header.e_version = EV_CURRENT;
265 Header.e_entry = Hdr.Entry;
266 Header.e_ehsize = sizeof(Elf_Ehdr);
268 // TODO: Flesh out section header support.
269 // TODO: Program headers.
271 Header.e_shentsize = sizeof(Elf_Shdr);
272 // Immediately following the ELF header.
273 Header.e_shoff = sizeof(Header);
274 const std::vector<ELFYAML::Section> &Sections = Doc.Sections;
276 // - SHT_NULL entry (placed first, i.e. 0'th entry)
277 // - symbol table (.symtab) (placed third to last)
278 // - string table (.strtab) (placed second to last)
279 // - section header string table. (placed last)
280 Header.e_shnum = Sections.size() + 4;
281 // Place section header string table last.
282 Header.e_shstrndx = Header.e_shnum - 1;
283 const unsigned DotStrtabSecNo = Header.e_shnum - 2;
285 // XXX: This offset is tightly coupled with the order that we write
287 const size_t SectionContentBeginOffset =
288 Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
289 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
290 SectionNameToIdxMap SN2I;
291 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
292 StringRef Name = Sections[i].Name;
295 // "+ 1" to take into account the SHT_NULL entry.
296 if (SN2I.addName(Name, i + 1)) {
297 errs() << "error: Repeated section name: '" << Name
298 << "' at YAML section number " << i << ".\n";
303 ELFState<ELFT> State(Header, CBA, DotStrtabSecNo, SN2I);
305 StringTableBuilder SHStrTab;
306 std::vector<Elf_Shdr> SHeaders;
308 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
309 // valid SHN_UNDEF entry since SHT_NULL == 0.
312 SHeaders.push_back(SHdr);
314 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
315 const ELFYAML::Section &Sec = Sections[i];
318 SHeader.sh_name = SHStrTab.addString(Sec.Name);
319 SHeader.sh_type = Sec.Type;
320 SHeader.sh_flags = Sec.Flags;
321 SHeader.sh_addr = Sec.Address;
323 Sec.Content.writeAsBinary(CBA.getOSAndAlignedOffset(SHeader.sh_offset));
324 SHeader.sh_size = Sec.Content.binary_size();
326 if (!Sec.Link.empty()) {
328 if (SN2I.lookupSection(Sec.Link, Index)) {
329 errs() << "error: Unknown section referenced: '" << Sec.Link
330 << "' at YAML section number " << i << ".\n";
333 SHeader.sh_link = Index;
336 SHeader.sh_addralign = Sec.AddressAlign;
337 SHeader.sh_entsize = 0;
338 SHeaders.push_back(SHeader);
342 Elf_Shdr SymtabSHeader;
344 SymtabSHeader.sh_name = SHStrTab.addString(StringRef(".symtab"));
345 handleSymtabSectionHeader<ELFT>(Doc.Symbols, State, SymtabSHeader);
346 SHeaders.push_back(SymtabSHeader);
348 // .strtab string table header.
349 Elf_Shdr DotStrTabSHeader;
350 zero(DotStrTabSHeader);
351 DotStrTabSHeader.sh_name = SHStrTab.addString(StringRef(".strtab"));
352 createStringTableSectionHeader(DotStrTabSHeader, State.getStringTable(), CBA);
353 SHeaders.push_back(DotStrTabSHeader);
355 // Section header string table header.
356 Elf_Shdr SHStrTabSHeader;
357 zero(SHStrTabSHeader);
358 createStringTableSectionHeader(SHStrTabSHeader, SHStrTab, CBA);
359 SHeaders.push_back(SHStrTabSHeader);
361 OS.write((const char *)&Header, sizeof(Header));
362 writeVectorData(OS, SHeaders);
363 CBA.writeBlobToStream(OS);
367 static bool is64Bit(const ELFYAML::Object &Doc) {
368 return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
371 static bool isLittleEndian(const ELFYAML::Object &Doc) {
372 return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
375 int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
376 yaml::Input YIn(Buf->getBuffer());
380 errs() << "yaml2obj: Failed to parse YAML file!\n";
383 using object::ELFType;
384 typedef ELFType<support::little, 8, true> LE64;
385 typedef ELFType<support::big, 8, true> BE64;
386 typedef ELFType<support::little, 4, false> LE32;
387 typedef ELFType<support::big, 4, false> BE32;
389 if (isLittleEndian(Doc))
390 return writeELF<LE64>(outs(), Doc);
392 return writeELF<BE64>(outs(), Doc);
394 if (isLittleEndian(Doc))
395 return writeELF<LE32>(outs(), Doc);
397 return writeELF<BE32>(outs(), Doc);