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