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 || 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 && S.SectionData->binary_size() != 0;
194 for (const auto &E : S.StructuredData)
195 HasContent |= E.size() != 0;
196 // Every BB address map entry encodes at least a version and a feature field.
197 if (S.BBAddrMapEntries && !S.BBAddrMapEntries->empty())
198 HasContent = true;
199
200 // Warn as ELF BBAddrMap does.
201 const std::vector<BBAddrMapYAML::PGOAnalysisMapEntry> *PGOAnalyses = nullptr;
202 if (S.PGOAnalyses) {
203 if (!S.BBAddrMapEntries)
204 WithColor::warning() << "PGOAnalyses should not exist in "
205 ".llvm_bb_addr_map when Entries does not exist";
206 else if (S.BBAddrMapEntries->size() != S.PGOAnalyses->size())
207 WithColor::warning() << "PGOAnalyses must be the same length as Entries "
208 "in .llvm_bb_addr_map";
209 else
210 PGOAnalyses = &S.PGOAnalyses.value();
211 }
212
213 if (!HasContent) {
214 // Leave SizeOfRawData unaltered. For .bss sections in object files, it
215 // carries the section size.
216 S.Header.PointerToRawData = 0;
217 return false;
218 }
219
220 CBA.padToAlignment(Align: CP.isPE() ? CP.getFileAlignment() : 4);
221 S.Header.PointerToRawData = CBA.getOffset();
222 for (const auto &E : S.StructuredData)
223 E.writeAsBinary(CBA);
224 if (S.SectionData)
225 CBA.writeAsBinary(Bin: *S.SectionData);
226 if (S.BBAddrMapEntries)
227 BBAddrMapYAML::encodePayload(Entries: *S.BBAddrMapEntries, PGOAnalyses, CBA,
228 Endian: LittleEndian, AddressSize: CP.is64Bit() ? 8 : 4);
229 if (CP.isPE())
230 CBA.padToAlignment(Align: CP.getFileAlignment());
231 S.Header.SizeOfRawData = CBA.getOffset() - S.Header.PointerToRawData;
232 return true;
233}
234
235template <typename T>
236static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic,
237 T Header) {
238 memset(Header, 0, sizeof(*Header));
239 Header->Magic = Magic;
240 Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment;
241 Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment;
242 uint32_t SizeOfCode = 0, SizeOfInitializedData = 0,
243 SizeOfUninitializedData = 0;
244 uint32_t SizeOfHeaders = alignTo(CP.SectionTableStart + CP.SectionTableSize,
245 Header->FileAlignment);
246 uint32_t SizeOfImage = alignTo(SizeOfHeaders, Header->SectionAlignment);
247 uint32_t BaseOfData = 0;
248 for (const COFFYAML::Section &S : CP.Obj.Sections) {
249 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_CODE)
250 SizeOfCode += S.Header.SizeOfRawData;
251 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
252 SizeOfInitializedData += S.Header.SizeOfRawData;
253 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
254 SizeOfUninitializedData += S.Header.SizeOfRawData;
255 if (S.Name == ".text")
256 Header->BaseOfCode = S.Header.VirtualAddress; // RVA
257 else if (S.Name == ".data")
258 BaseOfData = S.Header.VirtualAddress; // RVA
259 if (S.Header.VirtualAddress)
260 SizeOfImage += alignTo(S.Header.VirtualSize, Header->SectionAlignment);
261 }
262 Header->SizeOfCode = SizeOfCode;
263 Header->SizeOfInitializedData = SizeOfInitializedData;
264 Header->SizeOfUninitializedData = SizeOfUninitializedData;
265 Header->AddressOfEntryPoint =
266 CP.Obj.OptionalHeader->Header.AddressOfEntryPoint; // RVA
267 Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase;
268 Header->MajorOperatingSystemVersion =
269 CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion;
270 Header->MinorOperatingSystemVersion =
271 CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion;
272 Header->MajorImageVersion = CP.Obj.OptionalHeader->Header.MajorImageVersion;
273 Header->MinorImageVersion = CP.Obj.OptionalHeader->Header.MinorImageVersion;
274 Header->MajorSubsystemVersion =
275 CP.Obj.OptionalHeader->Header.MajorSubsystemVersion;
276 Header->MinorSubsystemVersion =
277 CP.Obj.OptionalHeader->Header.MinorSubsystemVersion;
278 Header->SizeOfImage = SizeOfImage;
279 Header->SizeOfHeaders = SizeOfHeaders;
280 Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem;
281 Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics;
282 Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve;
283 Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit;
284 Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve;
285 Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit;
286 Header->NumberOfRvaAndSize = CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
287 return BaseOfData;
288}
289
290static bool writeCOFF(COFFParser &CP, ContiguousBlobAccumulator &CBA) {
291 // Calculate number of symbols.
292 CP.Obj.Header.NumberOfSymbols = 0;
293 for (COFFYAML::Symbol &Sym : CP.Obj.Symbols) {
294 uint32_t NumberOfAuxSymbols = 0;
295 if (Sym.FunctionDefinition)
296 NumberOfAuxSymbols += 1;
297 if (Sym.bfAndefSymbol)
298 NumberOfAuxSymbols += 1;
299 if (Sym.WeakExternal)
300 NumberOfAuxSymbols += 1;
301 if (!Sym.File.empty())
302 NumberOfAuxSymbols +=
303 (Sym.File.size() + CP.getSymbolSize() - 1) / CP.getSymbolSize();
304 if (Sym.SectionDefinition)
305 NumberOfAuxSymbols += 1;
306 if (Sym.CLRToken)
307 NumberOfAuxSymbols += 1;
308 Sym.Header.NumberOfAuxSymbols = NumberOfAuxSymbols;
309 CP.Obj.Header.NumberOfSymbols += 1 + NumberOfAuxSymbols;
310 }
311
312 CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size();
313
314 unsigned PEHeaderSize = CP.is64Bit() ? sizeof(object::pe32plus_header)
315 : sizeof(object::pe32_header);
316 if (CP.isPE())
317 CP.Obj.Header.SizeOfOptionalHeader =
318 PEHeaderSize + sizeof(object::data_directory) *
319 CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
320
321 // Save field offsets for writing back their final values.
322 uint64_t PointerToSymbolTableOffset;
323
324 if (CP.isPE()) {
325 // PE files start with a DOS stub.
326 object::dos_header DH;
327 memset(s: &DH, c: 0, n: sizeof(DH));
328
329 // DOS EXEs start with "MZ" magic.
330 DH.Magic[0] = 'M';
331 DH.Magic[1] = 'Z';
332 // Initializing the AddressOfRelocationTable is strictly optional but
333 // mollifies certain tools which expect it to have a value greater than
334 // 0x40.
335 DH.AddressOfRelocationTable = sizeof(DH);
336 // This is the address of the PE signature.
337 DH.AddressOfNewExeHeader = DOSStubSize;
338
339 // Write out our DOS stub.
340 CBA.write(Ptr: reinterpret_cast<const char *>(&DH), Size: sizeof(DH));
341 // Write padding until we reach the position of where our PE signature
342 // should live.
343 CBA.writeZeros(Num: DOSStubSize - sizeof(DH));
344 // Write out the PE signature.
345 CBA.write(Ptr: COFF::PEMagic, Size: sizeof(COFF::PEMagic));
346 }
347 if (CP.useBigObj()) {
348 CBA.write(Val: static_cast<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN),
349 E: LittleEndian);
350 CBA.write(Val: static_cast<uint16_t>(0xffff), E: LittleEndian);
351 CBA.write(Val: static_cast<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion),
352 E: LittleEndian);
353 CBA.write(Val: CP.Obj.Header.Machine, E: LittleEndian);
354 CBA.write(Val: CP.Obj.Header.TimeDateStamp, E: LittleEndian);
355 CBA.write(Ptr: COFF::BigObjMagic, Size: sizeof(COFF::BigObjMagic));
356 CBA.writeZeros(Num: 4 * sizeof(uint32_t));
357 CBA.write(Val: CP.Obj.Header.NumberOfSections, E: LittleEndian);
358 PointerToSymbolTableOffset = CBA.getOffset();
359 // The final symbol table offset is written after the section data.
360 CBA.writeZeros(Num: sizeof(CP.Obj.Header.PointerToSymbolTable));
361 CBA.write(Val: CP.Obj.Header.NumberOfSymbols, E: LittleEndian);
362 } else {
363 CBA.write(Val: CP.Obj.Header.Machine, E: LittleEndian);
364 CBA.write(Val: static_cast<int16_t>(CP.Obj.Header.NumberOfSections),
365 E: LittleEndian);
366 CBA.write(Val: CP.Obj.Header.TimeDateStamp, E: LittleEndian);
367 PointerToSymbolTableOffset = CBA.getOffset();
368 // The final symbol table offset is written after the section data.
369 CBA.writeZeros(Num: sizeof(CP.Obj.Header.PointerToSymbolTable));
370 CBA.write(Val: CP.Obj.Header.NumberOfSymbols, E: LittleEndian);
371 CBA.write(Val: CP.Obj.Header.SizeOfOptionalHeader, E: LittleEndian);
372 CBA.write(Val: CP.Obj.Header.Characteristics, E: LittleEndian);
373 }
374
375 // The optional header, if present, immediately follows the COFF file header.
376 uint64_t OptionalHeaderOffset = CBA.getOffset();
377 if (CP.isPE()) {
378 // Reserve space for the PE header, whose fields depend on the final section
379 // layout. The data directories that follow it are already final.
380 CBA.writeZeros(Num: PEHeaderSize);
381 for (uint32_t I = 0; I < CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
382 ++I) {
383 const std::optional<COFF::DataDirectory> *DataDirectories =
384 CP.Obj.OptionalHeader->DataDirectories;
385 uint32_t NumDataDir = std::size(CP.Obj.OptionalHeader->DataDirectories);
386 if (I >= NumDataDir || !DataDirectories[I]) {
387 CBA.writeZeros(Num: 2 * sizeof(uint32_t));
388 } else {
389 CBA.write(Val: DataDirectories[I]->RelativeVirtualAddress, E: LittleEndian);
390 CBA.write(Val: DataDirectories[I]->Size, E: LittleEndian);
391 }
392 }
393 }
394
395 CP.SectionTableStart = CBA.getOffset();
396 CP.SectionTableSize = COFF::SectionSize * CP.Obj.Sections.size();
397 // Reserve space for the section table. Section offsets and sizes are filled
398 // in later.
399 CBA.writeZeros(Num: CP.SectionTableSize);
400
401 unsigned CurSymbol = 0;
402 StringMap<unsigned> SymbolTableIndexMap;
403 for (const COFFYAML::Symbol &Sym : CP.Obj.Symbols) {
404 SymbolTableIndexMap[Sym.Name] = CurSymbol;
405 CurSymbol += 1 + Sym.Header.NumberOfAuxSymbols;
406 }
407
408 // Collect the CodeView strings and checksums shared by all .debug$S sections.
409 for (COFFYAML::Section &S : CP.Obj.Sections) {
410 // We support specifying exactly one of SectionData or Subsections. So if
411 // there is already some SectionData, then we don't need to do any of this.
412 if (S.Name == ".debug$S" &&
413 (!S.SectionData || S.SectionData->binary_size() == 0)) {
414 CodeViewYAML::initializeStringsAndChecksums(Sections: S.DebugS,
415 SC&: CP.StringsAndChecksums);
416 if (CP.StringsAndChecksums.hasChecksums() &&
417 CP.StringsAndChecksums.hasStrings())
418 break;
419 }
420 }
421
422 // Output section data.
423 for (COFFYAML::Section &S : CP.Obj.Sections) {
424 bool HasContent = writeSectionContent(CP, S, CBA);
425 if (!HasContent || S.Relocations.empty())
426 continue;
427
428 S.Header.PointerToRelocations = CBA.getOffset();
429 if (S.Header.Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) {
430 S.Header.NumberOfRelocations = 0xffff;
431 CBA.write<uint32_t>(/*VirtualAddress=*/Val: S.Relocations.size() + 1,
432 E: LittleEndian);
433 CBA.write<uint32_t>(/*SymbolTableIndex=*/Val: 0, E: LittleEndian);
434 CBA.write<uint16_t>(/*Type=*/Val: 0, E: LittleEndian);
435 } else {
436 S.Header.NumberOfRelocations = S.Relocations.size();
437 }
438
439 for (const COFFYAML::Relocation &R : S.Relocations) {
440 uint32_t SymbolTableIndex;
441 if (R.SymbolTableIndex) {
442 if (!R.SymbolName.empty())
443 WithColor::error()
444 << "Both SymbolName and SymbolTableIndex specified\n";
445 SymbolTableIndex = *R.SymbolTableIndex;
446 } else {
447 SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];
448 }
449 CBA.write(Val: R.VirtualAddress, E: LittleEndian);
450 CBA.write(Val: SymbolTableIndex, E: LittleEndian);
451 CBA.write(Val: R.Type, E: LittleEndian);
452 }
453 }
454
455 // Fill in the optional header now that the section layout is final.
456 if (CP.isPE()) {
457 if (CP.is64Bit()) {
458 object::pe32plus_header PEH;
459 initializeOptionalHeader(CP, Magic: COFF::PE32Header::PE32_PLUS, Header: &PEH);
460 CBA.updateDataAt(Pos: OptionalHeaderOffset, Data: &PEH, Size: sizeof(PEH));
461 } else {
462 object::pe32_header PEH;
463 uint32_t BaseOfData =
464 initializeOptionalHeader(CP, Magic: COFF::PE32Header::PE32, Header: &PEH);
465 PEH.BaseOfData = BaseOfData;
466 CBA.updateDataAt(Pos: OptionalHeaderOffset, Data: &PEH, Size: sizeof(PEH));
467 }
468 }
469
470 // Fill in the section table.
471 static_assert(sizeof(object::coff_section) == COFF::SectionSize,
472 "unexpected COFF section header size");
473 uint64_t SectionHeaderOffset = CP.SectionTableStart;
474 for (const COFFYAML::Section &S : CP.Obj.Sections) {
475 object::coff_section Header{};
476 memcpy(dest: Header.Name, src: S.Header.Name, n: COFF::NameSize);
477 Header.VirtualSize = S.Header.VirtualSize;
478 Header.VirtualAddress = S.Header.VirtualAddress;
479 Header.SizeOfRawData = S.Header.SizeOfRawData;
480 Header.PointerToRawData = S.Header.PointerToRawData;
481 Header.PointerToRelocations = S.Header.PointerToRelocations;
482 Header.PointerToLinenumbers = S.Header.PointerToLineNumbers;
483 Header.NumberOfRelocations = S.Header.NumberOfRelocations;
484 Header.NumberOfLinenumbers = S.Header.NumberOfLineNumbers;
485 Header.Characteristics = S.Header.Characteristics;
486 CBA.updateDataAt(Pos: SectionHeaderOffset, Data: &Header, Size: sizeof(Header));
487 SectionHeaderOffset += sizeof(Header);
488 }
489
490 // Output symbol table.
491 if (CP.Obj.Header.NumberOfSymbols || CP.StringTable.size() > 4)
492 CP.Obj.Header.PointerToSymbolTable = CBA.getOffset();
493 else
494 CP.Obj.Header.PointerToSymbolTable = 0;
495
496 CBA.updateDataAt(Pos: PointerToSymbolTableOffset,
497 Val: CP.Obj.Header.PointerToSymbolTable, E: LittleEndian);
498
499 for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(),
500 e = CP.Obj.Symbols.end();
501 i != e; ++i) {
502 CBA.write(Ptr: i->Header.Name, Size: COFF::NameSize);
503 CBA.write(Val: i->Header.Value, E: LittleEndian);
504 if (CP.useBigObj())
505 CBA.write(Val: i->Header.SectionNumber, E: LittleEndian);
506 else
507 CBA.write(Val: static_cast<int16_t>(i->Header.SectionNumber), E: LittleEndian);
508 CBA.write(Val: i->Header.Type, E: LittleEndian);
509 CBA.write(Val: i->Header.StorageClass, E: LittleEndian);
510 CBA.write(Val: i->Header.NumberOfAuxSymbols, E: LittleEndian);
511
512 if (i->FunctionDefinition) {
513 CBA.write(Val: i->FunctionDefinition->TagIndex, E: LittleEndian);
514 CBA.write(Val: i->FunctionDefinition->TotalSize, E: LittleEndian);
515 CBA.write(Val: i->FunctionDefinition->PointerToLinenumber, E: LittleEndian);
516 CBA.write(Val: i->FunctionDefinition->PointerToNextFunction, E: LittleEndian);
517 CBA.writeZeros(Num: sizeof(i->FunctionDefinition->unused));
518 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
519 }
520 if (i->bfAndefSymbol) {
521 CBA.writeZeros(Num: sizeof(i->bfAndefSymbol->unused1));
522 CBA.write(Val: i->bfAndefSymbol->Linenumber, E: LittleEndian);
523 CBA.writeZeros(Num: sizeof(i->bfAndefSymbol->unused2));
524 CBA.write(Val: i->bfAndefSymbol->PointerToNextFunction, E: LittleEndian);
525 CBA.writeZeros(Num: sizeof(i->bfAndefSymbol->unused3));
526 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
527 }
528 if (i->WeakExternal) {
529 CBA.write(Val: i->WeakExternal->TagIndex, E: LittleEndian);
530 CBA.write(Val: i->WeakExternal->Characteristics, E: LittleEndian);
531 CBA.writeZeros(Num: sizeof(i->WeakExternal->unused));
532 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
533 }
534 if (!i->File.empty()) {
535 unsigned SymbolSize = CP.getSymbolSize();
536 uint32_t NumberOfAuxRecords =
537 (i->File.size() + SymbolSize - 1) / SymbolSize;
538 uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize;
539 uint32_t NumZeros = NumberOfAuxBytes - i->File.size();
540 CBA.write(Ptr: i->File.data(), Size: i->File.size());
541 CBA.writeZeros(Num: NumZeros);
542 }
543 if (i->SectionDefinition) {
544 CBA.write(Val: i->SectionDefinition->Length, E: LittleEndian);
545 CBA.write(Val: i->SectionDefinition->NumberOfRelocations, E: LittleEndian);
546 CBA.write(Val: i->SectionDefinition->NumberOfLinenumbers, E: LittleEndian);
547 CBA.write(Val: i->SectionDefinition->CheckSum, E: LittleEndian);
548 CBA.write(Val: static_cast<int16_t>(i->SectionDefinition->Number),
549 E: LittleEndian);
550 CBA.write(Val: i->SectionDefinition->Selection, E: LittleEndian);
551 CBA.writeZeros(Num: sizeof(i->SectionDefinition->unused));
552 CBA.write(Val: static_cast<int16_t>(i->SectionDefinition->Number >> 16),
553 E: LittleEndian);
554 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
555 }
556 if (i->CLRToken) {
557 CBA.write(Val: i->CLRToken->AuxType, E: LittleEndian);
558 CBA.writeZeros(Num: sizeof(i->CLRToken->unused1));
559 CBA.write(Val: i->CLRToken->SymbolTableIndex, E: LittleEndian);
560 CBA.writeZeros(Num: sizeof(i->CLRToken->unused2));
561 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
562 }
563 }
564
565 // Output string table.
566 if (CP.Obj.Header.PointerToSymbolTable) {
567 *reinterpret_cast<support::ulittle32_t *>(CP.StringTable.data()) =
568 CP.StringTable.size();
569 CBA.write(Ptr: CP.StringTable.data(), Size: CP.StringTable.size());
570 }
571 return true;
572}
573
574size_t COFFYAML::SectionDataEntry::size() const {
575 size_t Size = Binary.binary_size();
576 if (UInt32)
577 Size += sizeof(*UInt32);
578 if (LoadConfig32)
579 Size += LoadConfig32->Size;
580 if (LoadConfig64)
581 Size += LoadConfig64->Size;
582 return Size;
583}
584
585template <typename T>
586static void writeLoadConfig(T &S, ContiguousBlobAccumulator &CBA) {
587 CBA.write(Ptr: reinterpret_cast<const char *>(&S),
588 Size: std::min(a: sizeof(S), b: static_cast<size_t>(S.Size)));
589 if (sizeof(S) < S.Size)
590 CBA.writeZeros(Num: S.Size - sizeof(S));
591}
592
593void COFFYAML::SectionDataEntry::writeAsBinary(
594 ContiguousBlobAccumulator &CBA) const {
595 if (UInt32)
596 CBA.write(Val: *UInt32, E: LittleEndian);
597 CBA.writeAsBinary(Bin: Binary);
598 if (LoadConfig32)
599 writeLoadConfig(S: *LoadConfig32, CBA);
600 if (LoadConfig64)
601 writeLoadConfig(S: *LoadConfig64, CBA);
602}
603
604namespace llvm {
605namespace yaml {
606
607bool yaml2coff(llvm::COFFYAML::Object &Doc, raw_ostream &Out,
608 ErrorHandler ErrHandler, uint64_t MaxSize) {
609 COFFParser CP(Doc, ErrHandler);
610 if (!CP.parse()) {
611 ErrHandler("failed to parse YAML file");
612 return false;
613 }
614
615 // Limit the output size to guard against a runaway YAML description.
616 ContiguousBlobAccumulator CBA(/*BaseOffset=*/0, MaxSize);
617 if (!writeCOFF(CP, CBA)) {
618 ErrHandler("failed to write COFF file");
619 return false;
620 }
621 if (Error E = CBA.takeLimitError()) {
622 // Match ELF by reporting a custom error message instead below.
623 consumeError(Err: std::move(E));
624 ErrHandler("the desired output size is greater than permitted. Use the "
625 "--max-size option to change the limit");
626 return false;
627 }
628
629 CBA.writeBlobToStream(Out);
630 return true;
631}
632
633} // namespace yaml
634} // namespace llvm
635