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