OSDN Git Service

[yaml2obj][ELF] Just let this class own its buffer.
[android-x86/external-llvm.git] / tools / yaml2obj / yaml2elf.cpp
1 //===- 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"
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"
22
23 using namespace llvm;
24
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.
28 //
29 // This class has a deliberately small interface, since a lot of
30 // implementation variation is possible.
31 //
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.
36 namespace {
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.
41   std::string Buf;
42 public:
43   StringTableBuilder() {
44     Buf.push_back('\0');
45   }
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();
50     if (I != 0)
51       return I;
52     I = Buf.size();
53     Buf.append(S.begin(), S.end());
54     Buf.push_back('\0');
55     return I;
56   }
57   size_t size() const {
58     return Buf.size();
59   }
60   void writeToStream(raw_ostream &OS) {
61     OS.write(Buf.data(), Buf.size());
62   }
63 };
64 } // end anonymous namespace
65
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
68 // `InitialOffset`).
69 namespace {
70 class ContiguousBlobAccumulator {
71   const uint64_t InitialOffset;
72   SmallVector<char, 128> Buf;
73   raw_svector_ostream OS;
74
75 public:
76   ContiguousBlobAccumulator(uint64_t InitialOffset_)
77       : InitialOffset(InitialOffset_), Buf(), OS(Buf) {}
78   raw_ostream &getOS() { return OS; }
79   uint64_t currentOffset() const { return InitialOffset + OS.tell(); }
80   void writeBlobToStream(raw_ostream &Out) { Out << OS.str(); }
81 };
82 } // end anonymous namespace
83
84 // Used to keep track of section names, so that in the YAML file sections
85 // can be referenced by name instead of by index.
86 namespace {
87 class SectionNameToIdxMap {
88   StringMap<int> Map;
89 public:
90   /// \returns true if name is already present in the map.
91   bool addName(StringRef SecName, unsigned i) {
92     StringMapEntry<int> &Entry = Map.GetOrCreateValue(SecName, -1);
93     if (Entry.getValue() != -1)
94       return true;
95     Entry.setValue((int)i);
96     return false;
97   }
98   /// \returns true if name is not present in the map
99   bool lookupSection(StringRef SecName, unsigned &Idx) const {
100     StringMap<int>::const_iterator I = Map.find(SecName);
101     if (I == Map.end())
102       return true;
103     Idx = I->getValue();
104     return false;
105   }
106 };
107 } // end anonymous namespace
108
109 template <class T>
110 static size_t vectorDataSize(const std::vector<T> &Vec) {
111   return Vec.size() * sizeof(T);
112 }
113
114 template <class T>
115 static void writeVectorData(raw_ostream &OS, const std::vector<T> &Vec) {
116   OS.write((const char *)Vec.data(), vectorDataSize(Vec));
117 }
118
119 template <class T>
120 static void zero(T &Obj) {
121   memset(&Obj, 0, sizeof(Obj));
122 }
123
124 /// \brief Create a string table in `SHeader`, which we assume is already
125 /// zero'd.
126 template <class Elf_Shdr>
127 static void createStringTableSectionHeader(Elf_Shdr &SHeader,
128                                            StringTableBuilder &STB,
129                                            ContiguousBlobAccumulator &CBA) {
130   SHeader.sh_type = ELF::SHT_STRTAB;
131   SHeader.sh_offset = CBA.currentOffset();
132   SHeader.sh_size = STB.size();
133   STB.writeToStream(CBA.getOS());
134   SHeader.sh_addralign = 1;
135 }
136
137 // FIXME: This function is hideous. Between the sheer number of parameters
138 // and the hideous ELF typenames, it's just a travesty. Factor the ELF
139 // output into a class (templated on ELFT) and share some typedefs.
140 template <class ELFT>
141 static void handleSymtabSectionHeader(
142     const ELFYAML::Section &Sec,
143     typename object::ELFObjectFile<ELFT>::Elf_Shdr &SHeader,
144     StringTableBuilder &StrTab, ContiguousBlobAccumulator &CBA,
145     unsigned DotStrtabSecNo) {
146
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.
153   SHeader.sh_info = 0;
154   SHeader.sh_entsize = sizeof(Elf_Sym);
155
156   std::vector<Elf_Sym> Syms;
157   {
158     // Ensure STN_UNDEF is present
159     Elf_Sym Sym;
160     zero(Sym);
161     Syms.push_back(Sym);
162   }
163   for (unsigned i = 0, e = Sec.Symbols.size(); i != e; ++i) {
164     const ELFYAML::Symbol &Sym = Sec.Symbols[i];
165     Elf_Sym Symbol;
166     zero(Symbol);
167     if (!Sym.Name.empty())
168       Symbol.st_name = StrTab.addString(Sym.Name);
169     Symbol.setBindingAndType(Sym.Binding, Sym.Type);
170     Syms.push_back(Symbol);
171   }
172
173   SHeader.sh_offset = CBA.currentOffset();
174   SHeader.sh_size = vectorDataSize(Syms);
175   writeVectorData(CBA.getOS(), Syms);
176 }
177
178 template <class ELFT>
179 static int writeELF(raw_ostream &OS, const ELFYAML::Object &Doc) {
180   using namespace llvm::ELF;
181   typedef typename object::ELFObjectFile<ELFT>::Elf_Ehdr Elf_Ehdr;
182   typedef typename object::ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
183
184   const ELFYAML::FileHeader &Hdr = Doc.Header;
185
186   Elf_Ehdr Header;
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] = Hdr.OSABI;
197   Header.e_ident[EI_ABIVERSION] = 0;
198   Header.e_type = Hdr.Type;
199   Header.e_machine = Hdr.Machine;
200   Header.e_version = EV_CURRENT;
201   Header.e_entry = Hdr.Entry;
202   Header.e_ehsize = sizeof(Elf_Ehdr);
203
204   // TODO: Flesh out section header support.
205   // TODO: Program headers.
206
207   Header.e_shentsize = sizeof(Elf_Shdr);
208   // Immediately following the ELF header.
209   Header.e_shoff = sizeof(Header);
210   const std::vector<ELFYAML::Section> &Sections = Doc.Sections;
211   // "+ 3" for
212   // - SHT_NULL entry (placed first, i.e. 0'th entry)
213   // - string table (.strtab) (placed second to last)
214   // - section header string table. (placed last)
215   Header.e_shnum = Sections.size() + 3;
216   // Place section header string table last.
217   Header.e_shstrndx = Header.e_shnum - 1;
218   const unsigned DotStrtabSecNo = Header.e_shnum - 2;
219
220   SectionNameToIdxMap SN2I;
221   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
222     StringRef Name = Sections[i].Name;
223     if (Name.empty())
224       continue;
225     // "+ 1" to take into account the SHT_NULL entry.
226     if (SN2I.addName(Name, i + 1)) {
227       errs() << "error: Repeated section name: '" << Name
228              << "' at YAML section number " << i << ".\n";
229       return 1;
230     }
231   }
232
233   StringTableBuilder SHStrTab;
234   // XXX: This offset is tightly coupled with the order that we write
235   // things to `OS`.
236   const size_t SectionContentBeginOffset =
237       Header.e_ehsize + Header.e_shentsize * Header.e_shnum;
238   ContiguousBlobAccumulator CBA(SectionContentBeginOffset);
239   std::vector<Elf_Shdr> SHeaders;
240   {
241     // Ensure SHN_UNDEF entry is present. An all-zero section header is a
242     // valid SHN_UNDEF entry since SHT_NULL == 0.
243     Elf_Shdr SHdr;
244     zero(SHdr);
245     SHeaders.push_back(SHdr);
246   }
247   StringTableBuilder DotStrTab;
248   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
249     const ELFYAML::Section &Sec = Sections[i];
250     Elf_Shdr SHeader;
251     zero(SHeader);
252     SHeader.sh_name = SHStrTab.addString(Sec.Name);
253     SHeader.sh_type = Sec.Type;
254     SHeader.sh_flags = Sec.Flags;
255     SHeader.sh_addr = Sec.Address;
256
257     SHeader.sh_offset = CBA.currentOffset();
258     SHeader.sh_size = Sec.Content.binary_size();
259     Sec.Content.writeAsBinary(CBA.getOS());
260
261     if (!Sec.Link.empty()) {
262       unsigned Index;
263       if (SN2I.lookupSection(Sec.Link, Index)) {
264         errs() << "error: Unknown section referenced: '" << Sec.Link
265                << "' at YAML section number " << i << ".\n";
266         return 1;
267       }
268       SHeader.sh_link = Index;
269     }
270     SHeader.sh_info = 0;
271     SHeader.sh_addralign = Sec.AddressAlign;
272     SHeader.sh_entsize = 0;
273     // XXX: Really ugly right now. Need to put common state into a class.
274     if (Sec.Type == ELFYAML::ELF_SHT(SHT_SYMTAB))
275       handleSymtabSectionHeader<ELFT>(Sec, SHeader, DotStrTab, CBA,
276                                       DotStrtabSecNo);
277     SHeaders.push_back(SHeader);
278   }
279
280   // .strtab string table header.
281   Elf_Shdr DotStrTabSHeader;
282   zero(DotStrTabSHeader);
283   DotStrTabSHeader.sh_name = SHStrTab.addString(StringRef(".strtab"));
284   createStringTableSectionHeader(DotStrTabSHeader, DotStrTab, CBA);
285
286   // Section header string table header.
287   Elf_Shdr SHStrTabSHeader;
288   zero(SHStrTabSHeader);
289   createStringTableSectionHeader(SHStrTabSHeader, SHStrTab, CBA);
290
291   OS.write((const char *)&Header, sizeof(Header));
292   writeVectorData(OS, SHeaders);
293   OS.write((const char *)&DotStrTabSHeader, sizeof(DotStrTabSHeader));
294   OS.write((const char *)&SHStrTabSHeader, sizeof(SHStrTabSHeader));
295   CBA.writeBlobToStream(OS);
296   return 0;
297 }
298
299 int yaml2elf(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
300   yaml::Input YIn(Buf->getBuffer());
301   ELFYAML::Object Doc;
302   YIn >> Doc;
303   if (YIn.error()) {
304     errs() << "yaml2obj: Failed to parse YAML file!\n";
305     return 1;
306   }
307   if (Doc.Header.Class == ELFYAML::ELF_ELFCLASS(ELF::ELFCLASS64)) {
308     if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
309       return writeELF<object::ELFType<support::little, 8, true> >(outs(), Doc);
310     else
311       return writeELF<object::ELFType<support::big, 8, true> >(outs(), Doc);
312   } else {
313     if (Doc.Header.Data == ELFYAML::ELF_ELFDATA(ELF::ELFDATA2LSB))
314       return writeELF<object::ELFType<support::little, 4, false> >(outs(), Doc);
315     else
316       return writeELF<object::ELFType<support::big, 4, false> >(outs(), Doc);
317   }
318 }