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