ReleaseNotes: new Win EH instructions; by David Majnemer
[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/STLExtras.h"
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/Object/COFF.h"
22 #include "llvm/Object/COFFYAML.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <vector>
28
29 using namespace llvm;
30
31 /// This parses a yaml stream that represents a COFF object file.
32 /// See docs/yaml2obj for the yaml scheema.
33 struct COFFParser {
34   COFFParser(COFFYAML::Object &Obj)
35       : Obj(Obj), SectionTableStart(0), SectionTableSize(0) {
36     // A COFF string table always starts with a 4 byte size field. Offsets into
37     // it include this size, so allocate it now.
38     StringTable.append(4, char(0));
39   }
40
41   bool useBigObj() const {
42     return static_cast<int32_t>(Obj.Sections.size()) >
43            COFF::MaxNumberOfSections16;
44   }
45
46   bool isPE() const { return Obj.OptionalHeader.hasValue(); }
47   bool is64Bit() const {
48     return Obj.Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64;
49   }
50
51   uint32_t getFileAlignment() const {
52     return Obj.OptionalHeader->Header.FileAlignment;
53   }
54
55   unsigned getHeaderSize() const {
56     return useBigObj() ? COFF::Header32Size : COFF::Header16Size;
57   }
58
59   unsigned getSymbolSize() const {
60     return useBigObj() ? COFF::Symbol32Size : COFF::Symbol16Size;
61   }
62
63   bool parseSections() {
64     for (std::vector<COFFYAML::Section>::iterator i = Obj.Sections.begin(),
65            e = Obj.Sections.end(); i != e; ++i) {
66       COFFYAML::Section &Sec = *i;
67
68       // If the name is less than 8 bytes, store it in place, otherwise
69       // store it in the string table.
70       StringRef Name = Sec.Name;
71
72       if (Name.size() <= COFF::NameSize) {
73         std::copy(Name.begin(), Name.end(), Sec.Header.Name);
74       } else {
75         // Add string to the string table and format the index for output.
76         unsigned Index = getStringIndex(Name);
77         std::string str = utostr(Index);
78         if (str.size() > 7) {
79           errs() << "String table got too large";
80           return false;
81         }
82         Sec.Header.Name[0] = '/';
83         std::copy(str.begin(), str.end(), Sec.Header.Name + 1);
84       }
85
86       Sec.Header.Characteristics |= (Log2_32(Sec.Alignment) + 1) << 20;
87     }
88     return true;
89   }
90
91   bool parseSymbols() {
92     for (std::vector<COFFYAML::Symbol>::iterator i = Obj.Symbols.begin(),
93            e = Obj.Symbols.end(); i != e; ++i) {
94       COFFYAML::Symbol &Sym = *i;
95
96       // If the name is less than 8 bytes, store it in place, otherwise
97       // store it in the string table.
98       StringRef Name = Sym.Name;
99       if (Name.size() <= COFF::NameSize) {
100         std::copy(Name.begin(), Name.end(), Sym.Header.Name);
101       } else {
102         // Add string to the string table and format the index for output.
103         unsigned Index = getStringIndex(Name);
104         *reinterpret_cast<support::aligned_ulittle32_t*>(
105             Sym.Header.Name + 4) = Index;
106       }
107
108       Sym.Header.Type = Sym.SimpleType;
109       Sym.Header.Type |= Sym.ComplexType << COFF::SCT_COMPLEX_TYPE_SHIFT;
110     }
111     return true;
112   }
113
114   bool parse() {
115     if (!parseSections())
116       return false;
117     if (!parseSymbols())
118       return false;
119     return true;
120   }
121
122   unsigned getStringIndex(StringRef Str) {
123     StringMap<unsigned>::iterator i = StringTableMap.find(Str);
124     if (i == StringTableMap.end()) {
125       unsigned Index = StringTable.size();
126       StringTable.append(Str.begin(), Str.end());
127       StringTable.push_back(0);
128       StringTableMap[Str] = Index;
129       return Index;
130     }
131     return i->second;
132   }
133
134   COFFYAML::Object &Obj;
135
136   StringMap<unsigned> StringTableMap;
137   std::string StringTable;
138   uint32_t SectionTableStart;
139   uint32_t SectionTableSize;
140 };
141
142 // Take a CP and assign addresses and sizes to everything. Returns false if the
143 // layout is not valid to do.
144 static bool layoutOptionalHeader(COFFParser &CP) {
145   if (!CP.isPE())
146     return true;
147   unsigned PEHeaderSize = CP.is64Bit() ? sizeof(object::pe32plus_header)
148                                        : sizeof(object::pe32_header);
149   CP.Obj.Header.SizeOfOptionalHeader =
150       PEHeaderSize +
151       sizeof(object::data_directory) * (COFF::NUM_DATA_DIRECTORIES + 1);
152   return true;
153 }
154
155 namespace {
156 enum { DOSStubSize = 128 };
157 }
158
159 // Take a CP and assign addresses and sizes to everything. Returns false if the
160 // layout is not valid to do.
161 static bool layoutCOFF(COFFParser &CP) {
162   // The section table starts immediately after the header, including the
163   // optional header.
164   CP.SectionTableStart =
165       CP.getHeaderSize() + CP.Obj.Header.SizeOfOptionalHeader;
166   if (CP.isPE())
167     CP.SectionTableStart += DOSStubSize + sizeof(COFF::PEMagic);
168   CP.SectionTableSize = COFF::SectionSize * CP.Obj.Sections.size();
169
170   uint32_t CurrentSectionDataOffset =
171       CP.SectionTableStart + CP.SectionTableSize;
172
173   // Assign each section data address consecutively.
174   for (COFFYAML::Section &S : CP.Obj.Sections) {
175     if (S.SectionData.binary_size() > 0) {
176       CurrentSectionDataOffset = RoundUpToAlignment(
177           CurrentSectionDataOffset, CP.isPE() ? CP.getFileAlignment() : 4);
178       S.Header.SizeOfRawData = S.SectionData.binary_size();
179       if (CP.isPE())
180         S.Header.SizeOfRawData =
181             RoundUpToAlignment(S.Header.SizeOfRawData, CP.getFileAlignment());
182       S.Header.PointerToRawData = CurrentSectionDataOffset;
183       CurrentSectionDataOffset += S.Header.SizeOfRawData;
184       if (!S.Relocations.empty()) {
185         S.Header.PointerToRelocations = CurrentSectionDataOffset;
186         S.Header.NumberOfRelocations = S.Relocations.size();
187         CurrentSectionDataOffset +=
188             S.Header.NumberOfRelocations * COFF::RelocationSize;
189       }
190     } else {
191       S.Header.SizeOfRawData = 0;
192       S.Header.PointerToRawData = 0;
193     }
194   }
195
196   uint32_t SymbolTableStart = CurrentSectionDataOffset;
197
198   // Calculate number of symbols.
199   uint32_t NumberOfSymbols = 0;
200   for (std::vector<COFFYAML::Symbol>::iterator i = CP.Obj.Symbols.begin(),
201                                                e = CP.Obj.Symbols.end();
202                                                i != e; ++i) {
203     uint32_t NumberOfAuxSymbols = 0;
204     if (i->FunctionDefinition)
205       NumberOfAuxSymbols += 1;
206     if (i->bfAndefSymbol)
207       NumberOfAuxSymbols += 1;
208     if (i->WeakExternal)
209       NumberOfAuxSymbols += 1;
210     if (!i->File.empty())
211       NumberOfAuxSymbols +=
212           (i->File.size() + CP.getSymbolSize() - 1) / CP.getSymbolSize();
213     if (i->SectionDefinition)
214       NumberOfAuxSymbols += 1;
215     if (i->CLRToken)
216       NumberOfAuxSymbols += 1;
217     i->Header.NumberOfAuxSymbols = NumberOfAuxSymbols;
218     NumberOfSymbols += 1 + NumberOfAuxSymbols;
219   }
220
221   // Store all the allocated start addresses in the header.
222   CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size();
223   CP.Obj.Header.NumberOfSymbols = NumberOfSymbols;
224   if (NumberOfSymbols > 0 || CP.StringTable.size() > 4)
225     CP.Obj.Header.PointerToSymbolTable = SymbolTableStart;
226   else
227     CP.Obj.Header.PointerToSymbolTable = 0;
228
229   *reinterpret_cast<support::ulittle32_t *>(&CP.StringTable[0])
230     = CP.StringTable.size();
231
232   return true;
233 }
234
235 template <typename value_type>
236 struct binary_le_impl {
237   value_type Value;
238   binary_le_impl(value_type V) : Value(V) {}
239 };
240
241 template <typename value_type>
242 raw_ostream &operator <<( raw_ostream &OS
243                         , const binary_le_impl<value_type> &BLE) {
244   char Buffer[sizeof(BLE.Value)];
245   support::endian::write<value_type, support::little, support::unaligned>(
246     Buffer, BLE.Value);
247   OS.write(Buffer, sizeof(BLE.Value));
248   return OS;
249 }
250
251 template <typename value_type>
252 binary_le_impl<value_type> binary_le(value_type V) {
253   return binary_le_impl<value_type>(V);
254 }
255
256 template <size_t NumBytes> struct zeros_impl {};
257
258 template <size_t NumBytes>
259 raw_ostream &operator<<(raw_ostream &OS, const zeros_impl<NumBytes> &) {
260   char Buffer[NumBytes];
261   memset(Buffer, 0, sizeof(Buffer));
262   OS.write(Buffer, sizeof(Buffer));
263   return OS;
264 }
265
266 template <typename T>
267 zeros_impl<sizeof(T)> zeros(const T &) {
268   return zeros_impl<sizeof(T)>();
269 }
270
271 struct num_zeros_impl {
272   size_t N;
273   num_zeros_impl(size_t N) : N(N) {}
274 };
275
276 raw_ostream &operator<<(raw_ostream &OS, const num_zeros_impl &NZI) {
277   for (size_t I = 0; I != NZI.N; ++I)
278     OS.write(0);
279   return OS;
280 }
281
282 static num_zeros_impl num_zeros(size_t N) {
283   num_zeros_impl NZI(N);
284   return NZI;
285 }
286
287 template <typename T>
288 static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic, T Header) {
289   memset(Header, 0, sizeof(*Header));
290   Header->Magic = Magic;
291   Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment;
292   Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment;
293   uint32_t SizeOfCode = 0, SizeOfInitializedData = 0,
294            SizeOfUninitializedData = 0;
295   uint32_t SizeOfHeaders = RoundUpToAlignment(
296       CP.SectionTableStart + CP.SectionTableSize, Header->FileAlignment);
297   uint32_t SizeOfImage =
298       RoundUpToAlignment(SizeOfHeaders, Header->SectionAlignment);
299   uint32_t BaseOfData = 0;
300   for (const COFFYAML::Section &S : CP.Obj.Sections) {
301     if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_CODE)
302       SizeOfCode += S.Header.SizeOfRawData;
303     if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
304       SizeOfInitializedData += S.Header.SizeOfRawData;
305     if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
306       SizeOfUninitializedData += S.Header.SizeOfRawData;
307     if (S.Name.equals(".text"))
308       Header->BaseOfCode = S.Header.VirtualAddress; // RVA
309     else if (S.Name.equals(".data"))
310       BaseOfData = S.Header.VirtualAddress; // RVA
311     if (S.Header.VirtualAddress)
312       SizeOfImage +=
313           RoundUpToAlignment(S.Header.VirtualSize, Header->SectionAlignment);
314   }
315   Header->SizeOfCode = SizeOfCode;
316   Header->SizeOfInitializedData = SizeOfInitializedData;
317   Header->SizeOfUninitializedData = SizeOfUninitializedData;
318   Header->AddressOfEntryPoint =
319       CP.Obj.OptionalHeader->Header.AddressOfEntryPoint; // RVA
320   Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase;
321   Header->MajorOperatingSystemVersion =
322       CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion;
323   Header->MinorOperatingSystemVersion =
324       CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion;
325   Header->MajorImageVersion =
326       CP.Obj.OptionalHeader->Header.MajorImageVersion;
327   Header->MinorImageVersion =
328       CP.Obj.OptionalHeader->Header.MinorImageVersion;
329   Header->MajorSubsystemVersion =
330       CP.Obj.OptionalHeader->Header.MajorSubsystemVersion;
331   Header->MinorSubsystemVersion =
332       CP.Obj.OptionalHeader->Header.MinorSubsystemVersion;
333   Header->SizeOfImage = SizeOfImage;
334   Header->SizeOfHeaders = SizeOfHeaders;
335   Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem;
336   Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics;
337   Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve;
338   Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit;
339   Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve;
340   Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit;
341   Header->NumberOfRvaAndSize = COFF::NUM_DATA_DIRECTORIES + 1;
342   return BaseOfData;
343 }
344
345 static bool writeCOFF(COFFParser &CP, raw_ostream &OS) {
346   if (CP.isPE()) {
347     // PE files start with a DOS stub.
348     object::dos_header DH;
349     memset(&DH, 0, sizeof(DH));
350
351     // DOS EXEs start with "MZ" magic.
352     DH.Magic[0] = 'M';
353     DH.Magic[1] = 'Z';
354     // Initializing the AddressOfRelocationTable is strictly optional but
355     // mollifies certain tools which expect it to have a value greater than
356     // 0x40.
357     DH.AddressOfRelocationTable = sizeof(DH);
358     // This is the address of the PE signature.
359     DH.AddressOfNewExeHeader = DOSStubSize;
360
361     // Write out our DOS stub.
362     OS.write(reinterpret_cast<char *>(&DH), sizeof(DH));
363     // Write padding until we reach the position of where our PE signature
364     // should live.
365     OS << num_zeros(DOSStubSize - sizeof(DH));
366     // Write out the PE signature.
367     OS.write(COFF::PEMagic, sizeof(COFF::PEMagic));
368   }
369   if (CP.useBigObj()) {
370     OS << binary_le(static_cast<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN))
371        << binary_le(static_cast<uint16_t>(0xffff))
372        << binary_le(static_cast<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion))
373        << binary_le(CP.Obj.Header.Machine)
374        << binary_le(CP.Obj.Header.TimeDateStamp);
375     OS.write(COFF::BigObjMagic, sizeof(COFF::BigObjMagic));
376     OS << zeros(uint32_t(0))
377        << zeros(uint32_t(0))
378        << zeros(uint32_t(0))
379        << zeros(uint32_t(0))
380        << binary_le(CP.Obj.Header.NumberOfSections)
381        << binary_le(CP.Obj.Header.PointerToSymbolTable)
382        << binary_le(CP.Obj.Header.NumberOfSymbols);
383   } else {
384     OS << binary_le(CP.Obj.Header.Machine)
385        << binary_le(static_cast<int16_t>(CP.Obj.Header.NumberOfSections))
386        << binary_le(CP.Obj.Header.TimeDateStamp)
387        << binary_le(CP.Obj.Header.PointerToSymbolTable)
388        << binary_le(CP.Obj.Header.NumberOfSymbols)
389        << binary_le(CP.Obj.Header.SizeOfOptionalHeader)
390        << binary_le(CP.Obj.Header.Characteristics);
391   }
392   if (CP.isPE()) {
393     if (CP.is64Bit()) {
394       object::pe32plus_header PEH;
395       initializeOptionalHeader(CP, COFF::PE32Header::PE32_PLUS, &PEH);
396       OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));
397     } else {
398       object::pe32_header PEH;
399       uint32_t BaseOfData = initializeOptionalHeader(CP, COFF::PE32Header::PE32, &PEH);
400       PEH.BaseOfData = BaseOfData;
401       OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));
402     }
403     for (const Optional<COFF::DataDirectory> &DD :
404          CP.Obj.OptionalHeader->DataDirectories) {
405       if (!DD.hasValue()) {
406         OS << zeros(uint32_t(0));
407         OS << zeros(uint32_t(0));
408       } else {
409         OS << binary_le(DD->RelativeVirtualAddress);
410         OS << binary_le(DD->Size);
411       }
412     }
413     OS << zeros(uint32_t(0));
414     OS << zeros(uint32_t(0));
415   }
416
417   assert(OS.tell() == CP.SectionTableStart);
418   // Output section table.
419   for (std::vector<COFFYAML::Section>::iterator i = CP.Obj.Sections.begin(),
420                                                 e = CP.Obj.Sections.end();
421                                                 i != e; ++i) {
422     OS.write(i->Header.Name, COFF::NameSize);
423     OS << binary_le(i->Header.VirtualSize)
424        << binary_le(i->Header.VirtualAddress)
425        << binary_le(i->Header.SizeOfRawData)
426        << binary_le(i->Header.PointerToRawData)
427        << binary_le(i->Header.PointerToRelocations)
428        << binary_le(i->Header.PointerToLineNumbers)
429        << binary_le(i->Header.NumberOfRelocations)
430        << binary_le(i->Header.NumberOfLineNumbers)
431        << binary_le(i->Header.Characteristics);
432   }
433   assert(OS.tell() == CP.SectionTableStart + CP.SectionTableSize);
434
435   unsigned CurSymbol = 0;
436   StringMap<unsigned> SymbolTableIndexMap;
437   for (std::vector<COFFYAML::Symbol>::iterator I = CP.Obj.Symbols.begin(),
438                                                E = CP.Obj.Symbols.end();
439        I != E; ++I) {
440     SymbolTableIndexMap[I->Name] = CurSymbol;
441     CurSymbol += 1 + I->Header.NumberOfAuxSymbols;
442   }
443
444   // Output section data.
445   for (const COFFYAML::Section &S : CP.Obj.Sections) {
446     if (!S.Header.SizeOfRawData)
447       continue;
448     assert(S.Header.PointerToRawData >= OS.tell());
449     OS << num_zeros(S.Header.PointerToRawData - OS.tell());
450     S.SectionData.writeAsBinary(OS);
451     assert(S.Header.SizeOfRawData >= S.SectionData.binary_size());
452     OS << num_zeros(S.Header.SizeOfRawData - S.SectionData.binary_size());
453     for (const COFFYAML::Relocation &R : S.Relocations) {
454       uint32_t SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];
455       OS << binary_le(R.VirtualAddress)
456          << binary_le(SymbolTableIndex)
457          << binary_le(R.Type);
458     }
459   }
460
461   // Output symbol table.
462
463   for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(),
464                                                      e = CP.Obj.Symbols.end();
465                                                      i != e; ++i) {
466     OS.write(i->Header.Name, COFF::NameSize);
467     OS << binary_le(i->Header.Value);
468     if (CP.useBigObj())
469        OS << binary_le(i->Header.SectionNumber);
470     else
471        OS << binary_le(static_cast<int16_t>(i->Header.SectionNumber));
472     OS << binary_le(i->Header.Type)
473        << binary_le(i->Header.StorageClass)
474        << binary_le(i->Header.NumberOfAuxSymbols);
475
476     if (i->FunctionDefinition)
477       OS << binary_le(i->FunctionDefinition->TagIndex)
478          << binary_le(i->FunctionDefinition->TotalSize)
479          << binary_le(i->FunctionDefinition->PointerToLinenumber)
480          << binary_le(i->FunctionDefinition->PointerToNextFunction)
481          << zeros(i->FunctionDefinition->unused)
482          << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
483     if (i->bfAndefSymbol)
484       OS << zeros(i->bfAndefSymbol->unused1)
485          << binary_le(i->bfAndefSymbol->Linenumber)
486          << zeros(i->bfAndefSymbol->unused2)
487          << binary_le(i->bfAndefSymbol->PointerToNextFunction)
488          << zeros(i->bfAndefSymbol->unused3)
489          << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
490     if (i->WeakExternal)
491       OS << binary_le(i->WeakExternal->TagIndex)
492          << binary_le(i->WeakExternal->Characteristics)
493          << zeros(i->WeakExternal->unused)
494          << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
495     if (!i->File.empty()) {
496       unsigned SymbolSize = CP.getSymbolSize();
497       uint32_t NumberOfAuxRecords =
498           (i->File.size() + SymbolSize - 1) / SymbolSize;
499       uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize;
500       uint32_t NumZeros = NumberOfAuxBytes - i->File.size();
501       OS.write(i->File.data(), i->File.size());
502       OS << num_zeros(NumZeros);
503     }
504     if (i->SectionDefinition)
505       OS << binary_le(i->SectionDefinition->Length)
506          << binary_le(i->SectionDefinition->NumberOfRelocations)
507          << binary_le(i->SectionDefinition->NumberOfLinenumbers)
508          << binary_le(i->SectionDefinition->CheckSum)
509          << binary_le(static_cast<int16_t>(i->SectionDefinition->Number))
510          << binary_le(i->SectionDefinition->Selection)
511          << zeros(i->SectionDefinition->unused)
512          << binary_le(static_cast<int16_t>(i->SectionDefinition->Number >> 16))
513          << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
514     if (i->CLRToken)
515       OS << binary_le(i->CLRToken->AuxType)
516          << zeros(i->CLRToken->unused1)
517          << binary_le(i->CLRToken->SymbolTableIndex)
518          << zeros(i->CLRToken->unused2)
519          << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
520   }
521
522   // Output string table.
523   if (CP.Obj.Header.PointerToSymbolTable)
524     OS.write(&CP.StringTable[0], CP.StringTable.size());
525   return true;
526 }
527
528 int yaml2coff(yaml::Input &YIn, raw_ostream &Out) {
529   COFFYAML::Object Doc;
530   YIn >> Doc;
531   if (YIn.error()) {
532     errs() << "yaml2obj: Failed to parse YAML file!\n";
533     return 1;
534   }
535
536   COFFParser CP(Doc);
537   if (!CP.parse()) {
538     errs() << "yaml2obj: Failed to parse YAML file!\n";
539     return 1;
540   }
541
542   if (!layoutOptionalHeader(CP)) {
543     errs() << "yaml2obj: Failed to layout optional header for COFF file!\n";
544     return 1;
545   }
546   if (!layoutCOFF(CP)) {
547     errs() << "yaml2obj: Failed to layout COFF file!\n";
548     return 1;
549   }
550   if (!writeCOFF(CP, Out)) {
551     errs() << "yaml2obj: Failed to write COFF file!\n";
552     return 1;
553   }
554   return 0;
555 }