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/ADT/ArrayRef.h"
17 #include "llvm/Object/ELFObjectFile.h"
18 #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"
26 // 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.
30 // This class has a deliberately small interface, since a lot of
31 // implementation variation is possible.
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.
38 class 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.
44 StringTableBuilder() {
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();
54 Buf.append(S.begin(), S.end());
61 void writeToStream(raw_ostream &OS) {
62 OS.write(Buf.data(), Buf.size());
65 } // end anonymous namespace
67 // 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
71 class ContiguousBlobAccumulator {
72 const uint64_t InitialOffset;
73 SmallVector<char, 128> Buf;
74 raw_svector_ostream OS;
76 /// \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)
82 return AlignedOffset; // == CurrentOffset;
86 ContiguousBlobAccumulator(uint64_t InitialOffset_)
87 : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
88 template <class Integer>
89 raw_ostream &getOSAndAlignedOffset(Integer &Offset, unsigned Align = 16) {
90 Offset = padToAlignment(Align);
93 void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
95 } // end anonymous namespace
97 // Used to keep track of section names, so that in the YAML file sections
98 // can be referenced by name instead of by index.
100 class SectionNameToIdxMap {
103 /// \returns true if name is already present in the map.
104 bool addName(StringRef SecName, unsigned i) {
105 StringMapEntry<int> &Entry = Map.GetOrCreateValue(SecName, -1);
106 if (Entry.getValue() != -1)
108 Entry.setValue((int)i);
111 /// \returns true if name is not present in the map
112 bool lookupSection(StringRef SecName, unsigned &Idx) const {
113 StringMap<int>::const_iterator I = Map.find(SecName);
120 } // end anonymous namespace
123 static size_t arrayDataSize(ArrayRef<T> A) {
124 return A.size() * sizeof(T);
128 static void writeArrayData(raw_ostream &OS, ArrayRef<T> A) {
129 OS.write((const char *)A.data(), arrayDataSize(A));
133 static void zero(T &Obj) {
134 memset(&Obj, 0, sizeof(Obj));
137 /// \brief Create a string table in `SHeader`, which we assume is already
139 template <class Elf_Shdr>
140 static void createStringTableSectionHeader(Elf_Shdr &SHeader,
141 StringTableBuilder &STB,
142 ContiguousBlobAccumulator &CBA) {
143 SHeader.sh_type = ELF::SHT_STRTAB;
144 STB.writeToStream(CBA.getOSAndAlignedOffset(SHeader.sh_offset));
145 SHeader.sh_size = STB.size();
146 SHeader.sh_addralign = 1;
150 /// \brief "Single point of truth" for the ELF file construction.
151 /// TODO: This class still has a ways to go before it is truly a "single
153 template <class ELFT>
155 /// \brief The future ".strtab" section.
156 StringTableBuilder DotStrtab;
157 /// \brief The section number of the ".strtab" section.
158 unsigned DotStrtabSecNo;
159 /// \brief The accumulated contents of all sections so far.
160 ContiguousBlobAccumulator &SectionContentAccum;
161 typedef typename object::ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
162 /// \brief The ELF file header.
165 SectionNameToIdxMap &SN2I;
169 ELFState(Elf_Ehdr &Header_, ContiguousBlobAccumulator &Accum,
170 unsigned DotStrtabSecNo_, SectionNameToIdxMap &SN2I_)
171 : DotStrtab(), DotStrtabSecNo(DotStrtabSecNo_),
172 SectionContentAccum(Accum), Header(Header_), SN2I(SN2I_) {}
174 unsigned getDotStrTabSecNo() const { return DotStrtabSecNo; }
175 StringTableBuilder &getStringTable() { return DotStrtab; }
176 ContiguousBlobAccumulator &getSectionContentAccum() {
177 return SectionContentAccum;
179 SectionNameToIdxMap &getSN2I() { return SN2I; }
181 } // end anonymous namespace
183 // FIXME: At this point it is fairly clear that we need to refactor these
184 // static functions into methods of a class sharing some typedefs. These
185 // ELF type names are insane.
186 template <class ELFT>
188 addSymbols(const std::vector<ELFYAML::Symbol> &Symbols, ELFState<ELFT> &State,
189 std::vector<typename object::ELFFile<ELFT>::Elf_Sym> &Syms,
190 unsigned SymbolBinding) {
191 typedef typename object::ELFFile<ELFT>::Elf_Sym Elf_Sym;
192 for (unsigned i = 0, e = Symbols.size(); i != e; ++i) {
193 const ELFYAML::Symbol &Sym = Symbols[i];
196 if (!Sym.Name.empty())
197 Symbol.st_name = State.getStringTable().addString(Sym.Name);
198 Symbol.setBindingAndType(SymbolBinding, Sym.Type);
199 if (!Sym.Section.empty()) {
201 if (State.getSN2I().lookupSection(Sym.Section, Index)) {
202 errs() << "error: Unknown section referenced: '" << Sym.Section
203 << "' by YAML symbol " << Sym.Name << ".\n";
206 Symbol.st_shndx = Index;
207 } // else Symbol.st_shndex == SHN_UNDEF (== 0), since it was zero'd earlier.
208 Symbol.st_value = Sym.Value;
209 Symbol.st_size = Sym.Size;
210 Syms.push_back(Symbol);
214 template <class ELFT>
216 handleSymtabSectionHeader(const ELFYAML::LocalGlobalWeakSymbols &Symbols,
217 ELFState<ELFT> &State,
218 typename object::ELFFile<ELFT>::Elf_Shdr &SHeader) {
220 typedef typename object::ELFFile<ELFT>::Elf_Sym Elf_Sym;
221 SHeader.sh_type = ELF::SHT_SYMTAB;
222 SHeader.sh_link = State.getDotStrTabSecNo();
223 // One greater than symbol table index of the last local symbol.
224 SHeader.sh_info = Symbols.Local.size() + 1;
225 SHeader.sh_entsize = sizeof(Elf_Sym);
227 std::vector<Elf_Sym> Syms;
229 // Ensure STN_UNDEF is present
234 addSymbols(Symbols.Local, State, Syms, ELF::STB_LOCAL);
235 addSymbols(Symbols.Global, State, Syms, ELF::STB_GLOBAL);
236 addSymbols(Symbols.Weak, State, Syms, ELF::STB_WEAK);
238 ContiguousBlobAccumulator &CBA = State.getSectionContentAccum();
239 writeArrayData(CBA.getOSAndAlignedOffset(SHeader.sh_offset),
241 SHeader.sh_size = arrayDataSize(makeArrayRef(Syms));
244 template <class ELFT>
245 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
246 using namespace llvm::ELF;
247 typedef typename object::ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
248 typedef typename object::ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
250 const ELFYAML::FileHeader &Hdr = Doc.Header;
254 Header.e_ident[EI_MAG0] = 0x7f;
255 Header.e_ident[EI_MAG1] = 'E';
256 Header.e_ident[EI_MAG2] = 'L';
257 Header.e_ident[EI_MAG3] = 'F';
258 Header.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
259 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
260 Header.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
261 Header.e_ident[EI_VERSION] = EV_CURRENT;
262 Header.e_ident[EI_OSABI] = Hdr.OSABI;
263 Header.e_ident[EI_ABIVERSION] = 0;
264 Header.e_type = Hdr.Type;
265 Header.e_machine = Hdr.Machine;
266 Header.e_version = EV_CURRENT;
267 Header.e_entry = Hdr.Entry;
268 Header.e_ehsize = sizeof(Elf_Ehdr);
270 // TODO: Flesh out section header support.
271 // TODO: Program headers.
273 Header.e_shentsize = sizeof(Elf_Shdr);
274 // Immediately following the ELF header.
275 Header.e_shoff = sizeof(Header);
276 const std::vector<ELFYAML::Section> &Sections = Doc.Sections;
278 // - SHT_NULL entry (placed first, i.e. 0'th entry)
279 // - symbol table (.symtab) (placed third to last)
280 // - string table (.strtab) (placed second to last)
281 // - section header string table. (placed last)
282 Header.e_shnum = Sections.size() + 4;
283 // Place section header string table last.
284 Header.e_shstrndx = Header.e_shnum - 1;
285 const unsigned DotStrtabSecNo = Header.e_shnum - 2;
287 // XXX: This offset is tightly coupled with the order that we write
289 const size_t SectionContentBeginOffset =
290 Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
291 ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
292 SectionNameToIdxMap SN2I;
293 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
294 StringRef Name = Sections[i].Name;
297 // "+ 1" to take into account the SHT_NULL entry.
298 if (SN2I.addName(Name, i + 1)) {
299 errs() << "error: Repeated section name: '" << Name
300 << "' at YAML section number " << i << ".\n";
305 ELFState<ELFT> State(Header, CBA, DotStrtabSecNo, SN2I);
307 StringTableBuilder SHStrTab;
308 std::vector<Elf_Shdr> SHeaders;
310 // Ensure SHN_UNDEF entry is present. An all-zero section header is a
311 // valid SHN_UNDEF entry since SHT_NULL == 0.
314 SHeaders.push_back(SHdr);
316 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
317 const ELFYAML::Section &Sec = Sections[i];
320 SHeader.sh_name = SHStrTab.addString(Sec.Name);
321 SHeader.sh_type = Sec.Type;
322 SHeader.sh_flags = Sec.Flags;
323 SHeader.sh_addr = Sec.Address;
325 Sec.Content.writeAsBinary(CBA.getOSAndAlignedOffset(SHeader.sh_offset));
326 SHeader.sh_size = Sec.Content.binary_size();
328 if (!Sec.Link.empty()) {
330 if (SN2I.lookupSection(Sec.Link, Index)) {
331 errs() << "error: Unknown section referenced: '" << Sec.Link
332 << "' at YAML section number " << i << ".\n";
335 SHeader.sh_link = Index;
338 SHeader.sh_addralign = Sec.AddressAlign;
339 SHeader.sh_entsize = 0;
340 SHeaders.push_back(SHeader);
344 Elf_Shdr SymtabSHeader;
346 SymtabSHeader.sh_name = SHStrTab.addString(StringRef(".symtab"));
347 handleSymtabSectionHeader<ELFT>(Doc.Symbols, State, SymtabSHeader);
348 SHeaders.push_back(SymtabSHeader);
350 // .strtab string table header.
351 Elf_Shdr DotStrTabSHeader;
352 zero(DotStrTabSHeader);
353 DotStrTabSHeader.sh_name = SHStrTab.addString(StringRef(".strtab"));
354 createStringTableSectionHeader(DotStrTabSHeader, State.getStringTable(), CBA);
355 SHeaders.push_back(DotStrTabSHeader);
357 // Section header string table header.
358 Elf_Shdr SHStrTabSHeader;
359 zero(SHStrTabSHeader);
360 createStringTableSectionHeader(SHStrTabSHeader, SHStrTab, CBA);
361 SHeaders.push_back(SHStrTabSHeader);
363 OS.write((const char *)&Header, sizeof(Header));
364 writeArrayData(OS, makeArrayRef(SHeaders));
365 CBA.writeBlobToStream(OS);
369 static bool is64Bit(const ELFYAML::Object &Doc) {
370 return Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64);
373 static bool isLittleEndian(const ELFYAML::Object &Doc) {
374 return Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB);
377 int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
378 yaml::Input YIn(Buf->getBuffer());
382 errs() << "yaml2obj: Failed to parse YAML file!\n";
385 using object::ELFType;
386 typedef ELFType<support::little, 8, true> LE64;
387 typedef ELFType<support::big, 8, true> BE64;
388 typedef ELFType<support::little, 4, false> LE32;
389 typedef ELFType<support::big, 4, false> BE32;
391 if (isLittleEndian(Doc))
392 return writeELF<LE64>(outs(), Doc);
394 return writeELF<BE64>(outs(), Doc);
396 if (isLittleEndian(Doc))
397 return writeELF<LE32>(outs(), Doc);
399 return writeELF<BE32>(outs(), Doc);