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