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/ContiguousBlobAccumulator.h"
18#include "llvm/ObjectYAML/ObjectYAML.h"
19#include "llvm/ObjectYAML/yaml2obj.h"
20#include "llvm/Support/BinaryStreamWriter.h"
21#include "llvm/Support/Endian.h"
22#include "llvm/Support/SourceMgr.h"
23#include "llvm/Support/WithColor.h"
24#include "llvm/Support/raw_ostream.h"
25#include <optional>
26#include <vector>
27
28using namespace llvm;
29using llvm::yaml::ContiguousBlobAccumulator;
30
31namespace {
32
33constexpr auto LittleEndian = llvm::endianness::little;
34
35/// This parses a yaml stream that represents a COFF object file.
36/// See docs/yaml2obj for the yaml scheema.
37struct COFFParser {
38 COFFParser(COFFYAML::Object &Obj, yaml::ErrorHandler EH)
39 : Obj(Obj), ErrHandler(EH) {
40 // A COFF string table always starts with a 4 byte size field. Offsets into
41 // it include this size, so allocate it now.
42 StringTable.append(n: 4, c: char(0));
43 }
44
45 bool useBigObj() const {
46 return static_cast<int32_t>(Obj.Sections.size()) >
47 COFF::MaxNumberOfSections16;
48 }
49
50 bool isPE() const { return Obj.OptionalHeader.has_value(); }
51 bool is64Bit() const { return COFF::is64Bit(Machine: Obj.Header.Machine); }
52
53 uint32_t getFileAlignment() const {
54 return Obj.OptionalHeader->Header.FileAlignment;
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 llvm::copy(Range&: Name, Out: Sec.Header.Name);
69 } else {
70 // Add string to the string table and format the index for output.
71 unsigned Index = getStringIndex(Str: Name);
72 std::string str = utostr(X: Index);
73 if (str.size() > 7) {
74 ErrHandler("string table got too large");
75 return false;
76 }
77 Sec.Header.Name[0] = '/';
78 llvm::copy(Range&: str, Out: 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(Value: Sec.Alignment)) {
87 ErrHandler("section alignment is not a power of 2");
88 return false;
89 }
90 Sec.Header.Characteristics |= (Log2_32(Value: 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 llvm::copy(Range&: Name, Out: Sym.Header.Name);
103 } else {
104 // Add string to the string table and format the index for output.
105 unsigned Index = getStringIndex(Str: 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(Key: Str, Args: StringTable.size());
126 if (Inserted) {
127 StringTable.append(first: Str.begin(), last: Str.end());
128 StringTable.push_back(c: 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
145enum { DOSStubSize = 128 };
146
147} // end anonymous namespace
148
149static yaml::BinaryRef
150toDebugS(ArrayRef<CodeViewYAML::YAMLDebugSubsection> Subsections,
151 const codeview::StringsAndChecksums &SC, BumpPtrAllocator &Allocator) {
152 using namespace codeview;
153 ExitOnError Err("Error occurred writing .debug$S section");
154 auto CVSS =
155 Err(CodeViewYAML::toCodeViewSubsectionList(Allocator, Subsections, SC));
156
157 std::vector<DebugSubsectionRecordBuilder> Builders;
158 uint32_t Size = sizeof(uint32_t);
159 for (auto &SS : CVSS) {
160 DebugSubsectionRecordBuilder B(SS);
161 Size += B.calculateSerializedLength();
162 Builders.push_back(x: std::move(B));
163 }
164 uint8_t *Buffer = Allocator.Allocate<uint8_t>(Num: Size);
165 MutableArrayRef<uint8_t> Output(Buffer, Size);
166 BinaryStreamWriter Writer(Output, llvm::endianness::little);
167
168 Err(Writer.writeInteger<uint32_t>(Value: COFF::DEBUG_SECTION_MAGIC));
169 for (const auto &B : Builders) {
170 Err(B.commit(Writer, Container: CodeViewContainer::ObjectFile));
171 }
172 return {Output};
173}
174
175// Write the content of a section and fill in the header fields locating it.
176// Returns whether the section has any content.
177static bool writeSectionContent(COFFParser &CP, COFFYAML::Section &S,
178 ContiguousBlobAccumulator &CBA) {
179 if (S.SectionData.binary_size() == 0) {
180 if (S.Name == ".debug$S") {
181 assert(CP.StringsAndChecksums.hasStrings() &&
182 "Object file does not have debug string table!");
183 S.SectionData = toDebugS(Subsections: S.DebugS, SC: CP.StringsAndChecksums, Allocator&: CP.Allocator);
184 } else if (S.Name == ".debug$T") {
185 S.SectionData = CodeViewYAML::toDebugT(S.DebugT, Alloc&: CP.Allocator, SectionName: S.Name);
186 } else if (S.Name == ".debug$P") {
187 S.SectionData = CodeViewYAML::toDebugT(S.DebugP, Alloc&: CP.Allocator, SectionName: S.Name);
188 } else if (S.Name == ".debug$H" && S.DebugH) {
189 S.SectionData = CodeViewYAML::toDebugH(DebugH: *S.DebugH, Alloc&: CP.Allocator);
190 }
191 }
192
193 bool HasContent = S.SectionData.binary_size() != 0;
194 for (const auto &E : S.StructuredData)
195 HasContent |= E.size() != 0;
196
197 if (!HasContent) {
198 // Leave SizeOfRawData unaltered. For .bss sections in object files, it
199 // carries the section size.
200 S.Header.PointerToRawData = 0;
201 return false;
202 }
203
204 CBA.padToAlignment(Align: CP.isPE() ? CP.getFileAlignment() : 4);
205 S.Header.PointerToRawData = CBA.getOffset();
206 for (const auto &E : S.StructuredData)
207 E.writeAsBinary(CBA);
208 CBA.writeAsBinary(Bin: S.SectionData);
209 if (CP.isPE())
210 CBA.padToAlignment(Align: CP.getFileAlignment());
211 S.Header.SizeOfRawData = CBA.getOffset() - S.Header.PointerToRawData;
212 return true;
213}
214
215template <typename T>
216static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic,
217 T Header) {
218 memset(Header, 0, sizeof(*Header));
219 Header->Magic = Magic;
220 Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment;
221 Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment;
222 uint32_t SizeOfCode = 0, SizeOfInitializedData = 0,
223 SizeOfUninitializedData = 0;
224 uint32_t SizeOfHeaders = alignTo(CP.SectionTableStart + CP.SectionTableSize,
225 Header->FileAlignment);
226 uint32_t SizeOfImage = alignTo(SizeOfHeaders, Header->SectionAlignment);
227 uint32_t BaseOfData = 0;
228 for (const COFFYAML::Section &S : CP.Obj.Sections) {
229 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_CODE)
230 SizeOfCode += S.Header.SizeOfRawData;
231 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
232 SizeOfInitializedData += S.Header.SizeOfRawData;
233 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
234 SizeOfUninitializedData += S.Header.SizeOfRawData;
235 if (S.Name == ".text")
236 Header->BaseOfCode = S.Header.VirtualAddress; // RVA
237 else if (S.Name == ".data")
238 BaseOfData = S.Header.VirtualAddress; // RVA
239 if (S.Header.VirtualAddress)
240 SizeOfImage += alignTo(S.Header.VirtualSize, Header->SectionAlignment);
241 }
242 Header->SizeOfCode = SizeOfCode;
243 Header->SizeOfInitializedData = SizeOfInitializedData;
244 Header->SizeOfUninitializedData = SizeOfUninitializedData;
245 Header->AddressOfEntryPoint =
246 CP.Obj.OptionalHeader->Header.AddressOfEntryPoint; // RVA
247 Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase;
248 Header->MajorOperatingSystemVersion =
249 CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion;
250 Header->MinorOperatingSystemVersion =
251 CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion;
252 Header->MajorImageVersion = CP.Obj.OptionalHeader->Header.MajorImageVersion;
253 Header->MinorImageVersion = CP.Obj.OptionalHeader->Header.MinorImageVersion;
254 Header->MajorSubsystemVersion =
255 CP.Obj.OptionalHeader->Header.MajorSubsystemVersion;
256 Header->MinorSubsystemVersion =
257 CP.Obj.OptionalHeader->Header.MinorSubsystemVersion;
258 Header->SizeOfImage = SizeOfImage;
259 Header->SizeOfHeaders = SizeOfHeaders;
260 Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem;
261 Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics;
262 Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve;
263 Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit;
264 Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve;
265 Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit;
266 Header->NumberOfRvaAndSize = CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
267 return BaseOfData;
268}
269
270static bool writeCOFF(COFFParser &CP, ContiguousBlobAccumulator &CBA) {
271 // Calculate number of symbols.
272 CP.Obj.Header.NumberOfSymbols = 0;
273 for (COFFYAML::Symbol &Sym : CP.Obj.Symbols) {
274 uint32_t NumberOfAuxSymbols = 0;
275 if (Sym.FunctionDefinition)
276 NumberOfAuxSymbols += 1;
277 if (Sym.bfAndefSymbol)
278 NumberOfAuxSymbols += 1;
279 if (Sym.WeakExternal)
280 NumberOfAuxSymbols += 1;
281 if (!Sym.File.empty())
282 NumberOfAuxSymbols +=
283 (Sym.File.size() + CP.getSymbolSize() - 1) / CP.getSymbolSize();
284 if (Sym.SectionDefinition)
285 NumberOfAuxSymbols += 1;
286 if (Sym.CLRToken)
287 NumberOfAuxSymbols += 1;
288 Sym.Header.NumberOfAuxSymbols = NumberOfAuxSymbols;
289 CP.Obj.Header.NumberOfSymbols += 1 + NumberOfAuxSymbols;
290 }
291
292 CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size();
293
294 unsigned PEHeaderSize = CP.is64Bit() ? sizeof(object::pe32plus_header)
295 : sizeof(object::pe32_header);
296 if (CP.isPE())
297 CP.Obj.Header.SizeOfOptionalHeader =
298 PEHeaderSize + sizeof(object::data_directory) *
299 CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
300
301 // Save field offsets for writing back their final values.
302 uint64_t PointerToSymbolTableOffset;
303
304 if (CP.isPE()) {
305 // PE files start with a DOS stub.
306 object::dos_header DH;
307 memset(s: &DH, c: 0, n: sizeof(DH));
308
309 // DOS EXEs start with "MZ" magic.
310 DH.Magic[0] = 'M';
311 DH.Magic[1] = 'Z';
312 // Initializing the AddressOfRelocationTable is strictly optional but
313 // mollifies certain tools which expect it to have a value greater than
314 // 0x40.
315 DH.AddressOfRelocationTable = sizeof(DH);
316 // This is the address of the PE signature.
317 DH.AddressOfNewExeHeader = DOSStubSize;
318
319 // Write out our DOS stub.
320 CBA.write(Ptr: reinterpret_cast<const char *>(&DH), Size: sizeof(DH));
321 // Write padding until we reach the position of where our PE signature
322 // should live.
323 CBA.writeZeros(Num: DOSStubSize - sizeof(DH));
324 // Write out the PE signature.
325 CBA.write(Ptr: COFF::PEMagic, Size: sizeof(COFF::PEMagic));
326 }
327 if (CP.useBigObj()) {
328 CBA.write(Val: static_cast<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN),
329 E: LittleEndian);
330 CBA.write(Val: static_cast<uint16_t>(0xffff), E: LittleEndian);
331 CBA.write(Val: static_cast<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion),
332 E: LittleEndian);
333 CBA.write(Val: CP.Obj.Header.Machine, E: LittleEndian);
334 CBA.write(Val: CP.Obj.Header.TimeDateStamp, E: LittleEndian);
335 CBA.write(Ptr: COFF::BigObjMagic, Size: sizeof(COFF::BigObjMagic));
336 CBA.writeZeros(Num: 4 * sizeof(uint32_t));
337 CBA.write(Val: CP.Obj.Header.NumberOfSections, E: LittleEndian);
338 PointerToSymbolTableOffset = CBA.getOffset();
339 // The final symbol table offset is written after the section data.
340 CBA.writeZeros(Num: sizeof(CP.Obj.Header.PointerToSymbolTable));
341 CBA.write(Val: CP.Obj.Header.NumberOfSymbols, E: LittleEndian);
342 } else {
343 CBA.write(Val: CP.Obj.Header.Machine, E: LittleEndian);
344 CBA.write(Val: static_cast<int16_t>(CP.Obj.Header.NumberOfSections),
345 E: LittleEndian);
346 CBA.write(Val: CP.Obj.Header.TimeDateStamp, E: LittleEndian);
347 PointerToSymbolTableOffset = CBA.getOffset();
348 // The final symbol table offset is written after the section data.
349 CBA.writeZeros(Num: sizeof(CP.Obj.Header.PointerToSymbolTable));
350 CBA.write(Val: CP.Obj.Header.NumberOfSymbols, E: LittleEndian);
351 CBA.write(Val: CP.Obj.Header.SizeOfOptionalHeader, E: LittleEndian);
352 CBA.write(Val: CP.Obj.Header.Characteristics, E: LittleEndian);
353 }
354
355 // The optional header, if present, immediately follows the COFF file header.
356 uint64_t OptionalHeaderOffset = CBA.getOffset();
357 if (CP.isPE()) {
358 // Reserve space for the PE header, whose fields depend on the final section
359 // layout. The data directories that follow it are already final.
360 CBA.writeZeros(Num: PEHeaderSize);
361 for (uint32_t I = 0; I < CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
362 ++I) {
363 const std::optional<COFF::DataDirectory> *DataDirectories =
364 CP.Obj.OptionalHeader->DataDirectories;
365 uint32_t NumDataDir = std::size(CP.Obj.OptionalHeader->DataDirectories);
366 if (I >= NumDataDir || !DataDirectories[I]) {
367 CBA.writeZeros(Num: 2 * sizeof(uint32_t));
368 } else {
369 CBA.write(Val: DataDirectories[I]->RelativeVirtualAddress, E: LittleEndian);
370 CBA.write(Val: DataDirectories[I]->Size, E: LittleEndian);
371 }
372 }
373 }
374
375 CP.SectionTableStart = CBA.getOffset();
376 CP.SectionTableSize = COFF::SectionSize * CP.Obj.Sections.size();
377 // Reserve space for the section table. Section offsets and sizes are filled
378 // in later.
379 CBA.writeZeros(Num: CP.SectionTableSize);
380
381 unsigned CurSymbol = 0;
382 StringMap<unsigned> SymbolTableIndexMap;
383 for (const COFFYAML::Symbol &Sym : CP.Obj.Symbols) {
384 SymbolTableIndexMap[Sym.Name] = CurSymbol;
385 CurSymbol += 1 + Sym.Header.NumberOfAuxSymbols;
386 }
387
388 // Collect the CodeView strings and checksums shared by all .debug$S sections.
389 for (COFFYAML::Section &S : CP.Obj.Sections) {
390 // We support specifying exactly one of SectionData or Subsections. So if
391 // there is already some SectionData, then we don't need to do any of this.
392 if (S.Name == ".debug$S" && S.SectionData.binary_size() == 0) {
393 CodeViewYAML::initializeStringsAndChecksums(Sections: S.DebugS,
394 SC&: CP.StringsAndChecksums);
395 if (CP.StringsAndChecksums.hasChecksums() &&
396 CP.StringsAndChecksums.hasStrings())
397 break;
398 }
399 }
400
401 // Output section data.
402 for (COFFYAML::Section &S : CP.Obj.Sections) {
403 bool HasContent = writeSectionContent(CP, S, CBA);
404 if (!HasContent || S.Relocations.empty())
405 continue;
406
407 S.Header.PointerToRelocations = CBA.getOffset();
408 if (S.Header.Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) {
409 S.Header.NumberOfRelocations = 0xffff;
410 CBA.write<uint32_t>(/*VirtualAddress=*/Val: S.Relocations.size() + 1,
411 E: LittleEndian);
412 CBA.write<uint32_t>(/*SymbolTableIndex=*/Val: 0, E: LittleEndian);
413 CBA.write<uint16_t>(/*Type=*/Val: 0, E: LittleEndian);
414 } else {
415 S.Header.NumberOfRelocations = S.Relocations.size();
416 }
417
418 for (const COFFYAML::Relocation &R : S.Relocations) {
419 uint32_t SymbolTableIndex;
420 if (R.SymbolTableIndex) {
421 if (!R.SymbolName.empty())
422 WithColor::error()
423 << "Both SymbolName and SymbolTableIndex specified\n";
424 SymbolTableIndex = *R.SymbolTableIndex;
425 } else {
426 SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];
427 }
428 CBA.write(Val: R.VirtualAddress, E: LittleEndian);
429 CBA.write(Val: SymbolTableIndex, E: LittleEndian);
430 CBA.write(Val: R.Type, E: LittleEndian);
431 }
432 }
433
434 // Fill in the optional header now that the section layout is final.
435 if (CP.isPE()) {
436 if (CP.is64Bit()) {
437 object::pe32plus_header PEH;
438 initializeOptionalHeader(CP, Magic: COFF::PE32Header::PE32_PLUS, Header: &PEH);
439 CBA.updateDataAt(Pos: OptionalHeaderOffset, Data: &PEH, Size: sizeof(PEH));
440 } else {
441 object::pe32_header PEH;
442 uint32_t BaseOfData =
443 initializeOptionalHeader(CP, Magic: COFF::PE32Header::PE32, Header: &PEH);
444 PEH.BaseOfData = BaseOfData;
445 CBA.updateDataAt(Pos: OptionalHeaderOffset, Data: &PEH, Size: sizeof(PEH));
446 }
447 }
448
449 // Fill in the section table.
450 static_assert(sizeof(object::coff_section) == COFF::SectionSize,
451 "unexpected COFF section header size");
452 uint64_t SectionHeaderOffset = CP.SectionTableStart;
453 for (const COFFYAML::Section &S : CP.Obj.Sections) {
454 object::coff_section Header{};
455 memcpy(dest: Header.Name, src: S.Header.Name, n: COFF::NameSize);
456 Header.VirtualSize = S.Header.VirtualSize;
457 Header.VirtualAddress = S.Header.VirtualAddress;
458 Header.SizeOfRawData = S.Header.SizeOfRawData;
459 Header.PointerToRawData = S.Header.PointerToRawData;
460 Header.PointerToRelocations = S.Header.PointerToRelocations;
461 Header.PointerToLinenumbers = S.Header.PointerToLineNumbers;
462 Header.NumberOfRelocations = S.Header.NumberOfRelocations;
463 Header.NumberOfLinenumbers = S.Header.NumberOfLineNumbers;
464 Header.Characteristics = S.Header.Characteristics;
465 CBA.updateDataAt(Pos: SectionHeaderOffset, Data: &Header, Size: sizeof(Header));
466 SectionHeaderOffset += sizeof(Header);
467 }
468
469 // Output symbol table.
470 if (CP.Obj.Header.NumberOfSymbols || CP.StringTable.size() > 4)
471 CP.Obj.Header.PointerToSymbolTable = CBA.getOffset();
472 else
473 CP.Obj.Header.PointerToSymbolTable = 0;
474
475 CBA.updateDataAt(Pos: PointerToSymbolTableOffset,
476 Val: CP.Obj.Header.PointerToSymbolTable, E: LittleEndian);
477
478 for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(),
479 e = CP.Obj.Symbols.end();
480 i != e; ++i) {
481 CBA.write(Ptr: i->Header.Name, Size: COFF::NameSize);
482 CBA.write(Val: i->Header.Value, E: LittleEndian);
483 if (CP.useBigObj())
484 CBA.write(Val: i->Header.SectionNumber, E: LittleEndian);
485 else
486 CBA.write(Val: static_cast<int16_t>(i->Header.SectionNumber), E: LittleEndian);
487 CBA.write(Val: i->Header.Type, E: LittleEndian);
488 CBA.write(Val: i->Header.StorageClass, E: LittleEndian);
489 CBA.write(Val: i->Header.NumberOfAuxSymbols, E: LittleEndian);
490
491 if (i->FunctionDefinition) {
492 CBA.write(Val: i->FunctionDefinition->TagIndex, E: LittleEndian);
493 CBA.write(Val: i->FunctionDefinition->TotalSize, E: LittleEndian);
494 CBA.write(Val: i->FunctionDefinition->PointerToLinenumber, E: LittleEndian);
495 CBA.write(Val: i->FunctionDefinition->PointerToNextFunction, E: LittleEndian);
496 CBA.writeZeros(Num: sizeof(i->FunctionDefinition->unused));
497 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
498 }
499 if (i->bfAndefSymbol) {
500 CBA.writeZeros(Num: sizeof(i->bfAndefSymbol->unused1));
501 CBA.write(Val: i->bfAndefSymbol->Linenumber, E: LittleEndian);
502 CBA.writeZeros(Num: sizeof(i->bfAndefSymbol->unused2));
503 CBA.write(Val: i->bfAndefSymbol->PointerToNextFunction, E: LittleEndian);
504 CBA.writeZeros(Num: sizeof(i->bfAndefSymbol->unused3));
505 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
506 }
507 if (i->WeakExternal) {
508 CBA.write(Val: i->WeakExternal->TagIndex, E: LittleEndian);
509 CBA.write(Val: i->WeakExternal->Characteristics, E: LittleEndian);
510 CBA.writeZeros(Num: sizeof(i->WeakExternal->unused));
511 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
512 }
513 if (!i->File.empty()) {
514 unsigned SymbolSize = CP.getSymbolSize();
515 uint32_t NumberOfAuxRecords =
516 (i->File.size() + SymbolSize - 1) / SymbolSize;
517 uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize;
518 uint32_t NumZeros = NumberOfAuxBytes - i->File.size();
519 CBA.write(Ptr: i->File.data(), Size: i->File.size());
520 CBA.writeZeros(Num: NumZeros);
521 }
522 if (i->SectionDefinition) {
523 CBA.write(Val: i->SectionDefinition->Length, E: LittleEndian);
524 CBA.write(Val: i->SectionDefinition->NumberOfRelocations, E: LittleEndian);
525 CBA.write(Val: i->SectionDefinition->NumberOfLinenumbers, E: LittleEndian);
526 CBA.write(Val: i->SectionDefinition->CheckSum, E: LittleEndian);
527 CBA.write(Val: static_cast<int16_t>(i->SectionDefinition->Number),
528 E: LittleEndian);
529 CBA.write(Val: i->SectionDefinition->Selection, E: LittleEndian);
530 CBA.writeZeros(Num: sizeof(i->SectionDefinition->unused));
531 CBA.write(Val: static_cast<int16_t>(i->SectionDefinition->Number >> 16),
532 E: LittleEndian);
533 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
534 }
535 if (i->CLRToken) {
536 CBA.write(Val: i->CLRToken->AuxType, E: LittleEndian);
537 CBA.writeZeros(Num: sizeof(i->CLRToken->unused1));
538 CBA.write(Val: i->CLRToken->SymbolTableIndex, E: LittleEndian);
539 CBA.writeZeros(Num: sizeof(i->CLRToken->unused2));
540 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
541 }
542 }
543
544 // Output string table.
545 if (CP.Obj.Header.PointerToSymbolTable) {
546 *reinterpret_cast<support::ulittle32_t *>(CP.StringTable.data()) =
547 CP.StringTable.size();
548 CBA.write(Ptr: CP.StringTable.data(), Size: CP.StringTable.size());
549 }
550 return true;
551}
552
553size_t COFFYAML::SectionDataEntry::size() const {
554 size_t Size = Binary.binary_size();
555 if (UInt32)
556 Size += sizeof(*UInt32);
557 if (LoadConfig32)
558 Size += LoadConfig32->Size;
559 if (LoadConfig64)
560 Size += LoadConfig64->Size;
561 return Size;
562}
563
564template <typename T>
565static void writeLoadConfig(T &S, ContiguousBlobAccumulator &CBA) {
566 CBA.write(Ptr: reinterpret_cast<const char *>(&S),
567 Size: std::min(a: sizeof(S), b: static_cast<size_t>(S.Size)));
568 if (sizeof(S) < S.Size)
569 CBA.writeZeros(Num: S.Size - sizeof(S));
570}
571
572void COFFYAML::SectionDataEntry::writeAsBinary(
573 ContiguousBlobAccumulator &CBA) const {
574 if (UInt32)
575 CBA.write(Val: *UInt32, E: LittleEndian);
576 CBA.writeAsBinary(Bin: Binary);
577 if (LoadConfig32)
578 writeLoadConfig(S: *LoadConfig32, CBA);
579 if (LoadConfig64)
580 writeLoadConfig(S: *LoadConfig64, CBA);
581}
582
583namespace llvm {
584namespace yaml {
585
586bool yaml2coff(llvm::COFFYAML::Object &Doc, raw_ostream &Out,
587 ErrorHandler ErrHandler, uint64_t MaxSize) {
588 COFFParser CP(Doc, ErrHandler);
589 if (!CP.parse()) {
590 ErrHandler("failed to parse YAML file");
591 return false;
592 }
593
594 // Limit the output size to guard against a runaway YAML description.
595 ContiguousBlobAccumulator CBA(/*BaseOffset=*/0, MaxSize);
596 if (!writeCOFF(CP, CBA)) {
597 ErrHandler("failed to write COFF file");
598 return false;
599 }
600 if (Error E = CBA.takeLimitError()) {
601 // Match ELF by reporting a custom error message instead below.
602 consumeError(Err: std::move(E));
603 ErrHandler("the desired output size is greater than permitted. Use the "
604 "--max-size option to change the limit");
605 return false;
606 }
607
608 CBA.writeBlobToStream(Out);
609 return true;
610}
611
612} // namespace yaml
613} // namespace llvm
614