5b758471bdcea15b413692ce8352b66f4bf1f7e5
[oota-llvm.git] / tools / yaml2obj / yaml2coff.cpp
1 //===- yaml2coff - Convert YAML to a COFF 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 COFF component of yaml2obj.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #include "yaml2obj.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/Object/COFFYAML.h"
21 #include "llvm/Support/Endian.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <vector>
26
27 using namespace llvm;
28
29 /// This parses a yaml stream that represents a COFF object file.
30 /// See docs/yaml2obj for the yaml scheema.
31 struct COFFParser {
32   COFFParser(COFFYAML::Object &Obj) : Obj(Obj) {
33     // A COFF string table always starts with a 4 byte size field. Offsets into
34     // it include this size, so allocate it now.
35     StringTable.append(4, 0);
36   }
37
38   bool parseSections() {
39     for (std::vector<COFFYAML::Section>::iterator i = Obj.Sections.begin(),
40            e = Obj.Sections.end(); i != e; ++i) {
41       COFFYAML::Section &Sec = *i;
42
43       // If the name is less than 8 bytes, store it in place, otherwise
44       // store it in the string table.
45       StringRef Name = Sec.Name;
46
47       if (Name.size() <= COFF::NameSize) {
48         std::copy(Name.begin(), Name.end(), Sec.Header.Name);
49       } else {
50         // Add string to the string table and format the index for output.
51         unsigned Index = getStringIndex(Name);
52         std::string str = utostr(Index);
53         if (str.size() > 7) {
54           errs() << "String table got too large";
55           return false;
56         }
57         Sec.Header.Name[0] = '/';
58         std::copy(str.begin(), str.end(), Sec.Header.Name + 1);
59       }
60
61       Sec.Header.Characteristics |= (Log2_32(Sec.Alignment) + 1) << 20;
62     }
63     return true;
64   }
65
66   bool parseSymbols() {
67     for (std::vector<COFFYAML::Symbol>::iterator i = Obj.Symbols.begin(),
68            e = Obj.Symbols.end(); i != e; ++i) {
69       COFFYAML::Symbol &Sym = *i;
70
71       // If the name is less than 8 bytes, store it in place, otherwise
72       // store it in the string table.
73       StringRef Name = Sym.Name;
74       if (Name.size() <= COFF::NameSize) {
75         std::copy(Name.begin(), Name.end(), Sym.Header.Name);
76       } else {
77         // Add string to the string table and format the index for output.
78         unsigned Index = getStringIndex(Name);
79         *reinterpret_cast<support::aligned_ulittle32_t*>(
80             Sym.Header.Name + 4) = Index;
81       }
82
83       Sym.Header.Type = Sym.SimpleType;
84       Sym.Header.Type |= Sym.ComplexType << COFF::SCT_COMPLEX_TYPE_SHIFT;
85     }
86     return true;
87   }
88
89   bool parse() {
90     if (!parseSections())
91       return false;
92     if (!parseSymbols())
93       return false;
94     return true;
95   }
96
97   unsigned getStringIndex(StringRef Str) {
98     StringMap<unsigned>::iterator i = StringTableMap.find(Str);
99     if (i == StringTableMap.end()) {
100       unsigned Index = StringTable.size();
101       StringTable.append(Str.begin(), Str.end());
102       StringTable.push_back(0);
103       StringTableMap[Str] = Index;
104       return Index;
105     }
106     return i->second;
107   }
108
109   COFFYAML::Object &Obj;
110
111   StringMap<unsigned> StringTableMap;
112   std::string StringTable;
113 };
114
115 // Take a CP and assign addresses and sizes to everything. Returns false if the
116 // layout is not valid to do.
117 static bool layoutCOFF(COFFParser &CP) {
118   uint32_t SectionTableStart = 0;
119   uint32_t SectionTableSize  = 0;
120
121   // The section table starts immediately after the header, including the
122   // optional header.
123   SectionTableStart = sizeof(COFF::header) + CP.Obj.Header.SizeOfOptionalHeader;
124   SectionTableSize = sizeof(COFF::section) * CP.Obj.Sections.size();
125
126   uint32_t CurrentSectionDataOffset = SectionTableStart + SectionTableSize;
127
128   // Assign each section data address consecutively.
129   for (std::vector<COFFYAML::Section>::iterator i = CP.Obj.Sections.begin(),
130                                                 e = CP.Obj.Sections.end();
131                                                 i != e; ++i) {
132     StringRef SecData = i->SectionData.getHex();
133     if (!SecData.empty()) {
134       i->Header.SizeOfRawData = SecData.size()/2;
135       i->Header.PointerToRawData = CurrentSectionDataOffset;
136       CurrentSectionDataOffset += i->Header.SizeOfRawData;
137       if (!i->Relocations.empty()) {
138         i->Header.PointerToRelocations = CurrentSectionDataOffset;
139         i->Header.NumberOfRelocations = i->Relocations.size();
140         CurrentSectionDataOffset += i->Header.NumberOfRelocations *
141           COFF::RelocationSize;
142       }
143       // TODO: Handle alignment.
144     } else {
145       i->Header.SizeOfRawData = 0;
146       i->Header.PointerToRawData = 0;
147     }
148   }
149
150   uint32_t SymbolTableStart = CurrentSectionDataOffset;
151
152   // Calculate number of symbols.
153   uint32_t NumberOfSymbols = 0;
154   for (std::vector<COFFYAML::Symbol>::iterator i = CP.Obj.Symbols.begin(),
155                                                e = CP.Obj.Symbols.end();
156                                                i != e; ++i) {
157     unsigned AuxBytes = i->AuxiliaryData.getHex().size() / 2;
158     if (AuxBytes % COFF::SymbolSize != 0) {
159       errs() << "AuxiliaryData size not a multiple of symbol size!\n";
160       return false;
161     }
162     i->Header.NumberOfAuxSymbols = AuxBytes / COFF::SymbolSize;
163     NumberOfSymbols += 1 + i->Header.NumberOfAuxSymbols;
164   }
165
166   // Store all the allocated start addresses in the header.
167   CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size();
168   CP.Obj.Header.NumberOfSymbols = NumberOfSymbols;
169   CP.Obj.Header.PointerToSymbolTable = SymbolTableStart;
170
171   *reinterpret_cast<support::ulittle32_t *>(&CP.StringTable[0])
172     = CP.StringTable.size();
173
174   return true;
175 }
176
177 template <typename value_type>
178 struct binary_le_impl {
179   value_type Value;
180   binary_le_impl(value_type V) : Value(V) {}
181 };
182
183 template <typename value_type>
184 raw_ostream &operator <<( raw_ostream &OS
185                         , const binary_le_impl<value_type> &BLE) {
186   char Buffer[sizeof(BLE.Value)];
187   support::endian::write<value_type, support::little, support::unaligned>(
188     Buffer, BLE.Value);
189   OS.write(Buffer, sizeof(BLE.Value));
190   return OS;
191 }
192
193 template <typename value_type>
194 binary_le_impl<value_type> binary_le(value_type V) {
195   return binary_le_impl<value_type>(V);
196 }
197
198 bool writeCOFF(COFFParser &CP, raw_ostream &OS) {
199   OS << binary_le(CP.Obj.Header.Machine)
200      << binary_le(CP.Obj.Header.NumberOfSections)
201      << binary_le(CP.Obj.Header.TimeDateStamp)
202      << binary_le(CP.Obj.Header.PointerToSymbolTable)
203      << binary_le(CP.Obj.Header.NumberOfSymbols)
204      << binary_le(CP.Obj.Header.SizeOfOptionalHeader)
205      << binary_le(CP.Obj.Header.Characteristics);
206
207   // Output section table.
208   for (std::vector<COFFYAML::Section>::iterator i = CP.Obj.Sections.begin(),
209                                                 e = CP.Obj.Sections.end();
210                                                 i != e; ++i) {
211     OS.write(i->Header.Name, COFF::NameSize);
212     OS << binary_le(i->Header.VirtualSize)
213        << binary_le(i->Header.VirtualAddress)
214        << binary_le(i->Header.SizeOfRawData)
215        << binary_le(i->Header.PointerToRawData)
216        << binary_le(i->Header.PointerToRelocations)
217        << binary_le(i->Header.PointerToLineNumbers)
218        << binary_le(i->Header.NumberOfRelocations)
219        << binary_le(i->Header.NumberOfLineNumbers)
220        << binary_le(i->Header.Characteristics);
221   }
222
223   // Output section data.
224   for (std::vector<COFFYAML::Section>::iterator i = CP.Obj.Sections.begin(),
225                                                 e = CP.Obj.Sections.end();
226                                                 i != e; ++i) {
227     i->SectionData.writeAsBinary(OS);
228     for (unsigned I2 = 0, E2 = i->Relocations.size(); I2 != E2; ++I2) {
229       const COFF::relocation &R = i->Relocations[I2];
230       OS << binary_le(R.VirtualAddress)
231          << binary_le(R.SymbolTableIndex)
232          << binary_le(R.Type);
233     }
234   }
235
236   // Output symbol table.
237
238   for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(),
239                                                      e = CP.Obj.Symbols.end();
240                                                      i != e; ++i) {
241     OS.write(i->Header.Name, COFF::NameSize);
242     OS << binary_le(i->Header.Value)
243        << binary_le(i->Header.SectionNumber)
244        << binary_le(i->Header.Type)
245        << binary_le(i->Header.StorageClass)
246        << binary_le(i->Header.NumberOfAuxSymbols);
247     i->AuxiliaryData.writeAsBinary(OS);
248   }
249
250   // Output string table.
251   OS.write(&CP.StringTable[0], CP.StringTable.size());
252   return true;
253 }
254
255 int yaml2coff(llvm::raw_ostream &Out, llvm::MemoryBuffer *Buf) {
256   yaml::Input YIn(Buf->getBuffer());
257   COFFYAML::Object Doc;
258   YIn >> Doc;
259   if (YIn.error()) {
260     errs() << "yaml2obj: Failed to parse YAML file!\n";
261     return 1;
262   }
263
264   COFFParser CP(Doc);
265   if (!CP.parse()) {
266     errs() << "yaml2obj: Failed to parse YAML file!\n";
267     return 1;
268   }
269
270   if (!layoutCOFF(CP)) {
271     errs() << "yaml2obj: Failed to layout COFF file!\n";
272     return 1;
273   }
274   if (!writeCOFF(CP, Out)) {
275     errs() << "yaml2obj: Failed to write COFF file!\n";
276     return 1;
277   }
278   return 0;
279 }