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