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