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