Remove COFFYAML::Header.
[oota-llvm.git] / tools / yaml2obj / yaml2obj.cpp
1 //===- yaml2obj - Convert YAML to a binary 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 // This program takes a YAML description of an object file and outputs the
11 // binary equivalent.
12 //
13 // This is used for writing tests that require binary files.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Support/COFF.h"
22 #include "llvm/Support/Casting.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/PrettyStackTrace.h"
28 #include "llvm/Support/Signals.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/YAMLTraits.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/system_error.h"
33 #include <vector>
34
35 using namespace llvm;
36
37 static cl::opt<std::string>
38   Input(cl::Positional, cl::desc("<input>"), cl::init("-"));
39
40 template<class T>
41 typename llvm::enable_if_c<std::numeric_limits<T>::is_integer, bool>::type
42 getAs(const llvm::yaml::ScalarNode *SN, T &Result) {
43   SmallString<4> Storage;
44   StringRef Value = SN->getValue(Storage);
45   if (Value.getAsInteger(0, Result))
46     return false;
47   return true;
48 }
49
50 // Given a container with begin and end with ::value_type of a character type.
51 // Iterate through pairs of characters in the the set of [a-fA-F0-9] ignoring
52 // all other characters.
53 struct hex_pair_iterator {
54   StringRef::const_iterator Current, End;
55   typedef SmallVector<char, 2> value_type;
56   value_type Pair;
57   bool IsDone;
58
59   hex_pair_iterator(StringRef C)
60     : Current(C.begin()), End(C.end()), IsDone(false) {
61     // Initalize Pair.
62     ++*this;
63   }
64
65   // End iterator.
66   hex_pair_iterator() : Current(), End(), IsDone(true) {}
67
68   value_type operator *() const {
69     return Pair;
70   }
71
72   hex_pair_iterator operator ++() {
73     // We're at the end of the input.
74     if (Current == End) {
75       IsDone = true;
76       return *this;
77     }
78     Pair = value_type();
79     for (; Current != End && Pair.size() != 2; ++Current) {
80       // Is a valid hex digit.
81       if ((*Current >= '0' && *Current <= '9') ||
82           (*Current >= 'a' && *Current <= 'f') ||
83           (*Current >= 'A' && *Current <= 'F'))
84         Pair.push_back(*Current);
85     }
86     // Hit the end without getting 2 hex digits. Pair is invalid.
87     if (Pair.size() != 2)
88       IsDone = true;
89     return *this;
90   }
91
92   bool operator ==(const hex_pair_iterator Other) {
93     return (IsDone == Other.IsDone) ||
94            (Current == Other.Current && End == Other.End);
95   }
96
97   bool operator !=(const hex_pair_iterator Other) {
98     return !(*this == Other);
99   }
100 };
101
102 template <class ContainerOut>
103 static bool hexStringToByteArray(StringRef Str, ContainerOut &Out) {
104   for (hex_pair_iterator I(Str), E; I != E; ++I) {
105     typename hex_pair_iterator::value_type Pair = *I;
106     typename ContainerOut::value_type Byte;
107     if (StringRef(Pair.data(), 2).getAsInteger(16, Byte))
108       return false;
109     Out.push_back(Byte);
110   }
111   return true;
112 }
113
114 // The structure of the yaml files is not an exact 1:1 match to COFF. In order
115 // to use yaml::IO, we use these structures which are closer to the source.
116 namespace COFFYAML {
117   struct Section {
118     COFF::SectionCharacteristics Characteristics;
119     StringRef SectionData;
120     std::vector<COFF::relocation> Relocations;
121     StringRef Name;
122   };
123
124   struct Symbol {
125     COFF::SymbolBaseType SimpleType;
126     uint8_t NumberOfAuxSymbols;
127     StringRef Name;
128     COFF::SymbolStorageClass StorageClass;
129     StringRef AuxillaryData;
130     COFF::SymbolComplexType ComplexType;
131     uint32_t Value;
132     uint16_t SectionNumber;
133   };
134
135   struct Object {
136     COFF::header HeaderData;
137     std::vector<Section> Sections;
138     std::vector<Symbol> Symbols;
139   };
140 }
141
142 /// This parses a yaml stream that represents a COFF object file.
143 /// See docs/yaml2obj for the yaml scheema.
144 struct COFFParser {
145   COFFParser(COFFYAML::Object &Obj) : Obj(Obj) {
146     std::memset(&Header, 0, sizeof(Header));
147     // A COFF string table always starts with a 4 byte size field. Offsets into
148     // it include this size, so allocate it now.
149     StringTable.append(4, 0);
150   }
151
152   void parseHeader() {
153     Header.Machine = Obj.HeaderData.Machine;
154     Header.Characteristics = Obj.HeaderData.Characteristics;
155   }
156
157   bool parseSections() {
158     for (std::vector<COFFYAML::Section>::iterator i = Obj.Sections.begin(),
159            e = Obj.Sections.end(); i != e; ++i) {
160       const COFFYAML::Section &YamlSection = *i;
161       Section Sec;
162       std::memset(&Sec.Header, 0, sizeof(Sec.Header));
163
164       // If the name is less than 8 bytes, store it in place, otherwise
165       // store it in the string table.
166       StringRef Name = YamlSection.Name;
167       std::fill_n(Sec.Header.Name, unsigned(COFF::NameSize), 0);
168       if (Name.size() <= COFF::NameSize) {
169         std::copy(Name.begin(), Name.end(), Sec.Header.Name);
170       } else {
171         // Add string to the string table and format the index for output.
172         unsigned Index = getStringIndex(Name);
173         std::string str = utostr(Index);
174         if (str.size() > 7) {
175           errs() << "String table got too large";
176           return false;
177         }
178         Sec.Header.Name[0] = '/';
179         std::copy(str.begin(), str.end(), Sec.Header.Name + 1);
180       }
181
182       Sec.Header.Characteristics = YamlSection.Characteristics;
183
184       StringRef Data = YamlSection.SectionData;
185       if (!hexStringToByteArray(Data, Sec.Data)) {
186         errs() << "SectionData must be a collection of pairs of hex bytes";
187         return false;
188       }
189       Sections.push_back(Sec);
190     }
191     return true;
192   }
193
194   bool parseSymbols() {
195     for (std::vector<COFFYAML::Symbol>::iterator i = Obj.Symbols.begin(),
196            e = Obj.Symbols.end(); i != e; ++i) {
197       COFFYAML::Symbol YamlSymbol = *i;
198       Symbol Sym;
199       std::memset(&Sym.Header, 0, sizeof(Sym.Header));
200
201       // If the name is less than 8 bytes, store it in place, otherwise
202       // store it in the string table.
203       StringRef Name = YamlSymbol.Name;
204       std::fill_n(Sym.Header.Name, unsigned(COFF::NameSize), 0);
205       if (Name.size() <= COFF::NameSize) {
206         std::copy(Name.begin(), Name.end(), Sym.Header.Name);
207       } else {
208         // Add string to the string table and format the index for output.
209         unsigned Index = getStringIndex(Name);
210         *reinterpret_cast<support::aligned_ulittle32_t*>(
211             Sym.Header.Name + 4) = Index;
212       }
213
214       Sym.Header.Value = YamlSymbol.Value;
215       Sym.Header.Type |= YamlSymbol.SimpleType;
216       Sym.Header.Type |= YamlSymbol.ComplexType << COFF::SCT_COMPLEX_TYPE_SHIFT;
217       Sym.Header.StorageClass = YamlSymbol.StorageClass;
218       Sym.Header.SectionNumber = YamlSymbol.SectionNumber;
219
220       StringRef Data = YamlSymbol.AuxillaryData;
221       if (!hexStringToByteArray(Data, Sym.AuxSymbols)) {
222         errs() << "AuxillaryData must be a collection of pairs of hex bytes";
223         return false;
224       }
225       Symbols.push_back(Sym);
226     }
227     return true;
228   }
229
230   bool parse() {
231     parseHeader();
232     if (!parseSections())
233       return false;
234     if (!parseSymbols())
235       return false;
236     return true;
237   }
238
239   unsigned getStringIndex(StringRef Str) {
240     StringMap<unsigned>::iterator i = StringTableMap.find(Str);
241     if (i == StringTableMap.end()) {
242       unsigned Index = StringTable.size();
243       StringTable.append(Str.begin(), Str.end());
244       StringTable.push_back(0);
245       StringTableMap[Str] = Index;
246       return Index;
247     }
248     return i->second;
249   }
250
251   COFFYAML::Object &Obj;
252   COFF::header Header;
253
254   struct Section {
255     COFF::section Header;
256     std::vector<uint8_t> Data;
257     std::vector<COFF::relocation> Relocations;
258   };
259
260   struct Symbol {
261     COFF::symbol Header;
262     std::vector<uint8_t> AuxSymbols;
263   };
264
265   std::vector<Section> Sections;
266   std::vector<Symbol> Symbols;
267   StringMap<unsigned> StringTableMap;
268   std::string StringTable;
269 };
270
271 // Take a CP and assign addresses and sizes to everything. Returns false if the
272 // layout is not valid to do.
273 static bool layoutCOFF(COFFParser &CP) {
274   uint32_t SectionTableStart = 0;
275   uint32_t SectionTableSize  = 0;
276
277   // The section table starts immediately after the header, including the
278   // optional header.
279   SectionTableStart = sizeof(COFF::header) + CP.Header.SizeOfOptionalHeader;
280   SectionTableSize = sizeof(COFF::section) * CP.Sections.size();
281
282   uint32_t CurrentSectionDataOffset = SectionTableStart + SectionTableSize;
283
284   // Assign each section data address consecutively.
285   for (std::vector<COFFParser::Section>::iterator i = CP.Sections.begin(),
286                                                   e = CP.Sections.end();
287                                                   i != e; ++i) {
288     if (!i->Data.empty()) {
289       i->Header.SizeOfRawData = i->Data.size();
290       i->Header.PointerToRawData = CurrentSectionDataOffset;
291       CurrentSectionDataOffset += i->Header.SizeOfRawData;
292       // TODO: Handle alignment.
293     } else {
294       i->Header.SizeOfRawData = 0;
295       i->Header.PointerToRawData = 0;
296     }
297   }
298
299   uint32_t SymbolTableStart = CurrentSectionDataOffset;
300
301   // Calculate number of symbols.
302   uint32_t NumberOfSymbols = 0;
303   for (std::vector<COFFParser::Symbol>::iterator i = CP.Symbols.begin(),
304                                                  e = CP.Symbols.end();
305                                                  i != e; ++i) {
306     if (i->AuxSymbols.size() % COFF::SymbolSize != 0) {
307       errs() << "AuxillaryData size not a multiple of symbol size!\n";
308       return false;
309     }
310     i->Header.NumberOfAuxSymbols = i->AuxSymbols.size() / COFF::SymbolSize;
311     NumberOfSymbols += 1 + i->Header.NumberOfAuxSymbols;
312   }
313
314   // Store all the allocated start addresses in the header.
315   CP.Header.NumberOfSections = CP.Sections.size();
316   CP.Header.NumberOfSymbols = NumberOfSymbols;
317   CP.Header.PointerToSymbolTable = SymbolTableStart;
318
319   *reinterpret_cast<support::ulittle32_t *>(&CP.StringTable[0])
320     = CP.StringTable.size();
321
322   return true;
323 }
324
325 template <typename value_type>
326 struct binary_le_impl {
327   value_type Value;
328   binary_le_impl(value_type V) : Value(V) {}
329 };
330
331 template <typename value_type>
332 raw_ostream &operator <<( raw_ostream &OS
333                         , const binary_le_impl<value_type> &BLE) {
334   char Buffer[sizeof(BLE.Value)];
335   support::endian::write<value_type, support::little, support::unaligned>(
336     Buffer, BLE.Value);
337   OS.write(Buffer, sizeof(BLE.Value));
338   return OS;
339 }
340
341 template <typename value_type>
342 binary_le_impl<value_type> binary_le(value_type V) {
343   return binary_le_impl<value_type>(V);
344 }
345
346 void writeCOFF(COFFParser &CP, raw_ostream &OS) {
347   OS << binary_le(CP.Header.Machine)
348      << binary_le(CP.Header.NumberOfSections)
349      << binary_le(CP.Header.TimeDateStamp)
350      << binary_le(CP.Header.PointerToSymbolTable)
351      << binary_le(CP.Header.NumberOfSymbols)
352      << binary_le(CP.Header.SizeOfOptionalHeader)
353      << binary_le(CP.Header.Characteristics);
354
355   // Output section table.
356   for (std::vector<COFFParser::Section>::const_iterator i = CP.Sections.begin(),
357                                                         e = CP.Sections.end();
358                                                         i != e; ++i) {
359     OS.write(i->Header.Name, COFF::NameSize);
360     OS << binary_le(i->Header.VirtualSize)
361        << binary_le(i->Header.VirtualAddress)
362        << binary_le(i->Header.SizeOfRawData)
363        << binary_le(i->Header.PointerToRawData)
364        << binary_le(i->Header.PointerToRelocations)
365        << binary_le(i->Header.PointerToLineNumbers)
366        << binary_le(i->Header.NumberOfRelocations)
367        << binary_le(i->Header.NumberOfLineNumbers)
368        << binary_le(i->Header.Characteristics);
369   }
370
371   // Output section data.
372   for (std::vector<COFFParser::Section>::const_iterator i = CP.Sections.begin(),
373                                                         e = CP.Sections.end();
374                                                         i != e; ++i) {
375     if (!i->Data.empty())
376       OS.write(reinterpret_cast<const char*>(&i->Data[0]), i->Data.size());
377   }
378
379   // Output symbol table.
380
381   for (std::vector<COFFParser::Symbol>::const_iterator i = CP.Symbols.begin(),
382                                                        e = CP.Symbols.end();
383                                                        i != e; ++i) {
384     OS.write(i->Header.Name, COFF::NameSize);
385     OS << binary_le(i->Header.Value)
386        << binary_le(i->Header.SectionNumber)
387        << binary_le(i->Header.Type)
388        << binary_le(i->Header.StorageClass)
389        << binary_le(i->Header.NumberOfAuxSymbols);
390     if (!i->AuxSymbols.empty())
391       OS.write( reinterpret_cast<const char*>(&i->AuxSymbols[0])
392               , i->AuxSymbols.size());
393   }
394
395   // Output string table.
396   OS.write(&CP.StringTable[0], CP.StringTable.size());
397 }
398
399 LLVM_YAML_IS_SEQUENCE_VECTOR(COFF::relocation)
400 LLVM_YAML_IS_SEQUENCE_VECTOR(COFFYAML::Section)
401 LLVM_YAML_IS_SEQUENCE_VECTOR(COFFYAML::Symbol)
402
403 namespace llvm {
404
405 namespace COFF {
406   Characteristics operator|(Characteristics a, Characteristics b) {
407     uint32_t Ret = static_cast<uint32_t>(a) | static_cast<uint32_t>(b);
408     return static_cast<Characteristics>(Ret);
409   }
410
411   SectionCharacteristics
412   operator|(SectionCharacteristics a, SectionCharacteristics b) {
413     uint32_t Ret = static_cast<uint32_t>(a) | static_cast<uint32_t>(b);
414     return static_cast<SectionCharacteristics>(Ret);
415   }
416 }
417
418 namespace yaml {
419
420 #define BCase(X) IO.bitSetCase(Value, #X, COFF::X);
421
422 template <>
423 struct ScalarBitSetTraits<COFF::SectionCharacteristics> {
424   static void bitset(IO &IO, COFF::SectionCharacteristics &Value) {
425     BCase(IMAGE_SCN_TYPE_NO_PAD);
426     BCase(IMAGE_SCN_CNT_CODE);
427     BCase(IMAGE_SCN_CNT_INITIALIZED_DATA);
428     BCase(IMAGE_SCN_CNT_UNINITIALIZED_DATA);
429     BCase(IMAGE_SCN_LNK_OTHER);
430     BCase(IMAGE_SCN_LNK_INFO);
431     BCase(IMAGE_SCN_LNK_REMOVE);
432     BCase(IMAGE_SCN_LNK_COMDAT);
433     BCase(IMAGE_SCN_GPREL);
434     BCase(IMAGE_SCN_MEM_PURGEABLE);
435     BCase(IMAGE_SCN_MEM_16BIT);
436     BCase(IMAGE_SCN_MEM_LOCKED);
437     BCase(IMAGE_SCN_MEM_PRELOAD);
438     BCase(IMAGE_SCN_ALIGN_1BYTES);
439     BCase(IMAGE_SCN_ALIGN_2BYTES);
440     BCase(IMAGE_SCN_ALIGN_4BYTES);
441     BCase(IMAGE_SCN_ALIGN_8BYTES);
442     BCase(IMAGE_SCN_ALIGN_16BYTES);
443     BCase(IMAGE_SCN_ALIGN_32BYTES);
444     BCase(IMAGE_SCN_ALIGN_64BYTES);
445     BCase(IMAGE_SCN_ALIGN_128BYTES);
446     BCase(IMAGE_SCN_ALIGN_256BYTES);
447     BCase(IMAGE_SCN_ALIGN_512BYTES);
448     BCase(IMAGE_SCN_ALIGN_1024BYTES);
449     BCase(IMAGE_SCN_ALIGN_2048BYTES);
450     BCase(IMAGE_SCN_ALIGN_4096BYTES);
451     BCase(IMAGE_SCN_ALIGN_8192BYTES);
452     BCase(IMAGE_SCN_LNK_NRELOC_OVFL);
453     BCase(IMAGE_SCN_MEM_DISCARDABLE);
454     BCase(IMAGE_SCN_MEM_NOT_CACHED);
455     BCase(IMAGE_SCN_MEM_NOT_PAGED);
456     BCase(IMAGE_SCN_MEM_SHARED);
457     BCase(IMAGE_SCN_MEM_EXECUTE);
458     BCase(IMAGE_SCN_MEM_READ);
459     BCase(IMAGE_SCN_MEM_WRITE);
460   }
461 };
462
463 template <>
464 struct ScalarBitSetTraits<COFF::Characteristics> {
465   static void bitset(IO &IO, COFF::Characteristics &Value) {
466     BCase(IMAGE_FILE_RELOCS_STRIPPED);
467     BCase(IMAGE_FILE_EXECUTABLE_IMAGE);
468     BCase(IMAGE_FILE_LINE_NUMS_STRIPPED);
469     BCase(IMAGE_FILE_LOCAL_SYMS_STRIPPED);
470     BCase(IMAGE_FILE_AGGRESSIVE_WS_TRIM);
471     BCase(IMAGE_FILE_LARGE_ADDRESS_AWARE);
472     BCase(IMAGE_FILE_BYTES_REVERSED_LO);
473     BCase(IMAGE_FILE_32BIT_MACHINE);
474     BCase(IMAGE_FILE_DEBUG_STRIPPED);
475     BCase(IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP);
476     BCase(IMAGE_FILE_NET_RUN_FROM_SWAP);
477     BCase(IMAGE_FILE_SYSTEM);
478     BCase(IMAGE_FILE_DLL);
479     BCase(IMAGE_FILE_UP_SYSTEM_ONLY);
480     BCase(IMAGE_FILE_BYTES_REVERSED_HI);
481   }
482 };
483 #undef BCase
484
485 #define ECase(X) IO.enumCase(Value, #X, COFF::X);
486
487 template <>
488 struct ScalarEnumerationTraits<COFF::SymbolComplexType> {
489   static void enumeration(IO &IO, COFF::SymbolComplexType &Value) {
490     ECase(IMAGE_SYM_DTYPE_NULL);
491     ECase(IMAGE_SYM_DTYPE_POINTER);
492     ECase(IMAGE_SYM_DTYPE_FUNCTION);
493     ECase(IMAGE_SYM_DTYPE_ARRAY);
494   }
495 };
496
497 template <>
498 struct ScalarEnumerationTraits<COFF::SymbolStorageClass> {
499   static void enumeration(IO &IO, COFF::SymbolStorageClass &Value) {
500     ECase(IMAGE_SYM_CLASS_END_OF_FUNCTION);
501     ECase(IMAGE_SYM_CLASS_NULL);
502     ECase(IMAGE_SYM_CLASS_AUTOMATIC);
503     ECase(IMAGE_SYM_CLASS_EXTERNAL);
504     ECase(IMAGE_SYM_CLASS_STATIC);
505     ECase(IMAGE_SYM_CLASS_REGISTER);
506     ECase(IMAGE_SYM_CLASS_EXTERNAL_DEF);
507     ECase(IMAGE_SYM_CLASS_LABEL);
508     ECase(IMAGE_SYM_CLASS_UNDEFINED_LABEL);
509     ECase(IMAGE_SYM_CLASS_MEMBER_OF_STRUCT);
510     ECase(IMAGE_SYM_CLASS_ARGUMENT);
511     ECase(IMAGE_SYM_CLASS_STRUCT_TAG);
512     ECase(IMAGE_SYM_CLASS_MEMBER_OF_UNION);
513     ECase(IMAGE_SYM_CLASS_UNION_TAG);
514     ECase(IMAGE_SYM_CLASS_TYPE_DEFINITION);
515     ECase(IMAGE_SYM_CLASS_UNDEFINED_STATIC);
516     ECase(IMAGE_SYM_CLASS_ENUM_TAG);
517     ECase(IMAGE_SYM_CLASS_MEMBER_OF_ENUM);
518     ECase(IMAGE_SYM_CLASS_REGISTER_PARAM);
519     ECase(IMAGE_SYM_CLASS_BIT_FIELD);
520     ECase(IMAGE_SYM_CLASS_BLOCK);
521     ECase(IMAGE_SYM_CLASS_FUNCTION);
522     ECase(IMAGE_SYM_CLASS_END_OF_STRUCT);
523     ECase(IMAGE_SYM_CLASS_FILE);
524     ECase(IMAGE_SYM_CLASS_SECTION);
525     ECase(IMAGE_SYM_CLASS_WEAK_EXTERNAL);
526     ECase(IMAGE_SYM_CLASS_CLR_TOKEN);
527   }
528 };
529
530 template <>
531 struct ScalarEnumerationTraits<COFF::SymbolBaseType> {
532   static void enumeration(IO &IO, COFF::SymbolBaseType &Value) {
533     ECase(IMAGE_SYM_TYPE_NULL);
534     ECase(IMAGE_SYM_TYPE_VOID);
535     ECase(IMAGE_SYM_TYPE_CHAR);
536     ECase(IMAGE_SYM_TYPE_SHORT);
537     ECase(IMAGE_SYM_TYPE_INT);
538     ECase(IMAGE_SYM_TYPE_LONG);
539     ECase(IMAGE_SYM_TYPE_FLOAT);
540     ECase(IMAGE_SYM_TYPE_DOUBLE);
541     ECase(IMAGE_SYM_TYPE_STRUCT);
542     ECase(IMAGE_SYM_TYPE_UNION);
543     ECase(IMAGE_SYM_TYPE_ENUM);
544     ECase(IMAGE_SYM_TYPE_MOE);
545     ECase(IMAGE_SYM_TYPE_BYTE);
546     ECase(IMAGE_SYM_TYPE_WORD);
547     ECase(IMAGE_SYM_TYPE_UINT);
548     ECase(IMAGE_SYM_TYPE_DWORD);
549   }
550 };
551
552 template <>
553 struct ScalarEnumerationTraits<COFF::MachineTypes> {
554   static void enumeration(IO &IO, COFF::MachineTypes &Value) {
555     ECase(IMAGE_FILE_MACHINE_UNKNOWN);
556     ECase(IMAGE_FILE_MACHINE_AM33);
557     ECase(IMAGE_FILE_MACHINE_AMD64);
558     ECase(IMAGE_FILE_MACHINE_ARM);
559     ECase(IMAGE_FILE_MACHINE_ARMV7);
560     ECase(IMAGE_FILE_MACHINE_EBC);
561     ECase(IMAGE_FILE_MACHINE_I386);
562     ECase(IMAGE_FILE_MACHINE_IA64);
563     ECase(IMAGE_FILE_MACHINE_M32R);
564     ECase(IMAGE_FILE_MACHINE_MIPS16);
565     ECase(IMAGE_FILE_MACHINE_MIPSFPU);
566     ECase(IMAGE_FILE_MACHINE_MIPSFPU16);
567     ECase(IMAGE_FILE_MACHINE_POWERPC);
568     ECase(IMAGE_FILE_MACHINE_POWERPCFP);
569     ECase(IMAGE_FILE_MACHINE_R4000);
570     ECase(IMAGE_FILE_MACHINE_SH3);
571     ECase(IMAGE_FILE_MACHINE_SH3DSP);
572     ECase(IMAGE_FILE_MACHINE_SH4);
573     ECase(IMAGE_FILE_MACHINE_SH5);
574     ECase(IMAGE_FILE_MACHINE_THUMB);
575     ECase(IMAGE_FILE_MACHINE_WCEMIPSV2);
576   }
577 };
578
579 template <>
580 struct ScalarEnumerationTraits<COFF::RelocationTypeX86> {
581   static void enumeration(IO &IO, COFF::RelocationTypeX86 &Value) {
582     ECase(IMAGE_REL_I386_ABSOLUTE);
583     ECase(IMAGE_REL_I386_DIR16);
584     ECase(IMAGE_REL_I386_REL16);
585     ECase(IMAGE_REL_I386_DIR32);
586     ECase(IMAGE_REL_I386_DIR32NB);
587     ECase(IMAGE_REL_I386_SEG12);
588     ECase(IMAGE_REL_I386_SECTION);
589     ECase(IMAGE_REL_I386_SECREL);
590     ECase(IMAGE_REL_I386_TOKEN);
591     ECase(IMAGE_REL_I386_SECREL7);
592     ECase(IMAGE_REL_I386_REL32);
593     ECase(IMAGE_REL_AMD64_ABSOLUTE);
594     ECase(IMAGE_REL_AMD64_ADDR64);
595     ECase(IMAGE_REL_AMD64_ADDR32);
596     ECase(IMAGE_REL_AMD64_ADDR32NB);
597     ECase(IMAGE_REL_AMD64_REL32);
598     ECase(IMAGE_REL_AMD64_REL32_1);
599     ECase(IMAGE_REL_AMD64_REL32_2);
600     ECase(IMAGE_REL_AMD64_REL32_3);
601     ECase(IMAGE_REL_AMD64_REL32_4);
602     ECase(IMAGE_REL_AMD64_REL32_5);
603     ECase(IMAGE_REL_AMD64_SECTION);
604     ECase(IMAGE_REL_AMD64_SECREL);
605     ECase(IMAGE_REL_AMD64_SECREL7);
606     ECase(IMAGE_REL_AMD64_TOKEN);
607     ECase(IMAGE_REL_AMD64_SREL32);
608     ECase(IMAGE_REL_AMD64_PAIR);
609     ECase(IMAGE_REL_AMD64_SSPAN32);
610   }
611 };
612
613 #undef ECase
614
615 template <>
616 struct MappingTraits<COFFYAML::Symbol> {
617   static void mapping(IO &IO, COFFYAML::Symbol &S) {
618     IO.mapRequired("SimpleType", S.SimpleType);
619     IO.mapOptional("NumberOfAuxSymbols", S.NumberOfAuxSymbols);
620     IO.mapRequired("Name", S.Name);
621     IO.mapRequired("StorageClass", S.StorageClass);
622     IO.mapOptional("AuxillaryData", S.AuxillaryData); // FIXME: typo
623     IO.mapRequired("ComplexType", S.ComplexType);
624     IO.mapRequired("Value", S.Value);
625     IO.mapRequired("SectionNumber", S.SectionNumber);
626   }
627 };
628
629 template <>
630 struct MappingTraits<COFF::header> {
631   struct NMachine {
632     NMachine(IO&) : Machine(COFF::MachineTypes(0)) {
633     }
634     NMachine(IO&, uint16_t M) : Machine(COFF::MachineTypes(M)) {
635     }
636     uint16_t denormalize(IO &) {
637       return Machine;
638     }
639     COFF::MachineTypes Machine;
640   };
641
642   struct NCharacteristics {
643     NCharacteristics(IO&) : Characteristics(COFF::Characteristics(0)) {
644     }
645     NCharacteristics(IO&, uint16_t C) :
646       Characteristics(COFF::Characteristics(C)) {
647     }
648     uint16_t denormalize(IO &) {
649       return Characteristics;
650     }
651
652     COFF::Characteristics Characteristics;
653   };
654
655   static void mapping(IO &IO, COFF::header &H) {
656     MappingNormalization<NMachine, uint16_t> NM(IO, H.Machine);
657     MappingNormalization<NCharacteristics, uint16_t> NC(IO, H.Characteristics);
658
659     IO.mapRequired("Machine", NM->Machine);
660     IO.mapOptional("Characteristics", NC->Characteristics);
661   }
662 };
663
664 template <>
665 struct MappingTraits<COFF::relocation> {
666   struct NType {
667     NType(IO &) : Type(COFF::RelocationTypeX86(0)) {
668     }
669     NType(IO &, uint16_t T) : Type(COFF::RelocationTypeX86(T)) {
670     }
671     uint16_t denormalize(IO &) {
672       return Type;
673     }
674     COFF::RelocationTypeX86 Type;
675   };
676
677   static void mapping(IO &IO, COFF::relocation &Rel) {
678     MappingNormalization<NType, uint16_t> NT(IO, Rel.Type);
679
680     IO.mapRequired("Type", NT->Type);
681     IO.mapRequired("VirtualAddress", Rel.VirtualAddress);
682     IO.mapRequired("SymbolTableIndex", Rel.SymbolTableIndex);
683   }
684 };
685
686 template <>
687 struct MappingTraits<COFFYAML::Section> {
688   static void mapping(IO &IO, COFFYAML::Section &Sec) {
689     IO.mapOptional("Relocations", Sec.Relocations);
690     IO.mapRequired("SectionData", Sec.SectionData);
691     IO.mapRequired("Characteristics", Sec.Characteristics);
692     IO.mapRequired("Name", Sec.Name);
693   }
694 };
695
696 template <>
697 struct MappingTraits<COFFYAML::Object> {
698   static void mapping(IO &IO, COFFYAML::Object &Obj) {
699     IO.mapRequired("sections", Obj.Sections);
700     IO.mapRequired("header", Obj.HeaderData);
701     IO.mapRequired("symbols", Obj.Symbols);
702   }
703 };
704 } // end namespace yaml
705 } // end namespace llvm
706
707 int main(int argc, char **argv) {
708   cl::ParseCommandLineOptions(argc, argv);
709   sys::PrintStackTraceOnErrorSignal();
710   PrettyStackTraceProgram X(argc, argv);
711   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
712
713   OwningPtr<MemoryBuffer> Buf;
714   if (MemoryBuffer::getFileOrSTDIN(Input, Buf))
715     return 1;
716
717   yaml::Input YIn(Buf->getBuffer());
718   COFFYAML::Object Doc;
719   YIn >> Doc;
720   if (YIn.error()) {
721     errs() << "yaml2obj: Failed to parse YAML file!\n";
722     return 1;
723   }
724
725   COFFParser CP(Doc);
726   if (!CP.parse()) {
727     errs() << "yaml2obj: Failed to parse YAML file!\n";
728     return 1;
729   }
730
731   if (!layoutCOFF(CP)) {
732     errs() << "yaml2obj: Failed to layout COFF file!\n";
733     return 1;
734   }
735   writeCOFF(CP, outs());
736 }