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 *reinterpret_cast<support::ulittle32_t *>(CP.StringTable.data()) =
268 CP.StringTable.size();
269
270 return true;
271}
272
273template <typename T>
274static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic,
275 T Header) {
276 memset(Header, 0, sizeof(*Header));
277 Header->Magic = Magic;
278 Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment;
279 Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment;
280 uint32_t SizeOfCode = 0, SizeOfInitializedData = 0,
281 SizeOfUninitializedData = 0;
282 uint32_t SizeOfHeaders = alignTo(CP.SectionTableStart + CP.SectionTableSize,
283 Header->FileAlignment);
284 uint32_t SizeOfImage = alignTo(SizeOfHeaders, Header->SectionAlignment);
285 uint32_t BaseOfData = 0;
286 for (const COFFYAML::Section &S : CP.Obj.Sections) {
287 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_CODE)
288 SizeOfCode += S.Header.SizeOfRawData;
289 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
290 SizeOfInitializedData += S.Header.SizeOfRawData;
291 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
292 SizeOfUninitializedData += S.Header.SizeOfRawData;
293 if (S.Name == ".text")
294 Header->BaseOfCode = S.Header.VirtualAddress; // RVA
295 else if (S.Name == ".data")
296 BaseOfData = S.Header.VirtualAddress; // RVA
297 if (S.Header.VirtualAddress)
298 SizeOfImage += alignTo(S.Header.VirtualSize, Header->SectionAlignment);
299 }
300 Header->SizeOfCode = SizeOfCode;
301 Header->SizeOfInitializedData = SizeOfInitializedData;
302 Header->SizeOfUninitializedData = SizeOfUninitializedData;
303 Header->AddressOfEntryPoint =
304 CP.Obj.OptionalHeader->Header.AddressOfEntryPoint; // RVA
305 Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase;
306 Header->MajorOperatingSystemVersion =
307 CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion;
308 Header->MinorOperatingSystemVersion =
309 CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion;
310 Header->MajorImageVersion = CP.Obj.OptionalHeader->Header.MajorImageVersion;
311 Header->MinorImageVersion = CP.Obj.OptionalHeader->Header.MinorImageVersion;
312 Header->MajorSubsystemVersion =
313 CP.Obj.OptionalHeader->Header.MajorSubsystemVersion;
314 Header->MinorSubsystemVersion =
315 CP.Obj.OptionalHeader->Header.MinorSubsystemVersion;
316 Header->SizeOfImage = SizeOfImage;
317 Header->SizeOfHeaders = SizeOfHeaders;
318 Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem;
319 Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics;
320 Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve;
321 Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit;
322 Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve;
323 Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit;
324 Header->NumberOfRvaAndSize = CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
325 return BaseOfData;
326}
327
328static bool writeCOFF(COFFParser &CP, ContiguousBlobAccumulator &CBA) {
329 // Calculate number of symbols.
330 CP.Obj.Header.NumberOfSymbols = 0;
331 for (COFFYAML::Symbol &Sym : CP.Obj.Symbols) {
332 uint32_t NumberOfAuxSymbols = 0;
333 if (Sym.FunctionDefinition)
334 NumberOfAuxSymbols += 1;
335 if (Sym.bfAndefSymbol)
336 NumberOfAuxSymbols += 1;
337 if (Sym.WeakExternal)
338 NumberOfAuxSymbols += 1;
339 if (!Sym.File.empty())
340 NumberOfAuxSymbols +=
341 (Sym.File.size() + CP.getSymbolSize() - 1) / CP.getSymbolSize();
342 if (Sym.SectionDefinition)
343 NumberOfAuxSymbols += 1;
344 if (Sym.CLRToken)
345 NumberOfAuxSymbols += 1;
346 Sym.Header.NumberOfAuxSymbols = NumberOfAuxSymbols;
347 CP.Obj.Header.NumberOfSymbols += 1 + NumberOfAuxSymbols;
348 }
349
350 CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size();
351
352 // Save field offsets for writing back their final values.
353 uint64_t PointerToSymbolTableOffset;
354
355 if (CP.isPE()) {
356 // PE files start with a DOS stub.
357 object::dos_header DH;
358 memset(s: &DH, c: 0, n: sizeof(DH));
359
360 // DOS EXEs start with "MZ" magic.
361 DH.Magic[0] = 'M';
362 DH.Magic[1] = 'Z';
363 // Initializing the AddressOfRelocationTable is strictly optional but
364 // mollifies certain tools which expect it to have a value greater than
365 // 0x40.
366 DH.AddressOfRelocationTable = sizeof(DH);
367 // This is the address of the PE signature.
368 DH.AddressOfNewExeHeader = DOSStubSize;
369
370 // Write out our DOS stub.
371 CBA.write(Ptr: reinterpret_cast<const char *>(&DH), Size: sizeof(DH));
372 // Write padding until we reach the position of where our PE signature
373 // should live.
374 CBA.writeZeros(Num: DOSStubSize - sizeof(DH));
375 // Write out the PE signature.
376 CBA.write(Ptr: COFF::PEMagic, Size: sizeof(COFF::PEMagic));
377 }
378 if (CP.useBigObj()) {
379 CBA.write(Val: static_cast<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN),
380 E: LittleEndian);
381 CBA.write(Val: static_cast<uint16_t>(0xffff), E: LittleEndian);
382 CBA.write(Val: static_cast<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion),
383 E: LittleEndian);
384 CBA.write(Val: CP.Obj.Header.Machine, E: LittleEndian);
385 CBA.write(Val: CP.Obj.Header.TimeDateStamp, E: LittleEndian);
386 CBA.write(Ptr: COFF::BigObjMagic, Size: sizeof(COFF::BigObjMagic));
387 CBA.writeZeros(Num: 4 * sizeof(uint32_t));
388 CBA.write(Val: CP.Obj.Header.NumberOfSections, E: LittleEndian);
389 PointerToSymbolTableOffset = CBA.getOffset();
390 // The final symbol table offset is written after the section data.
391 CBA.writeZeros(Num: sizeof(CP.Obj.Header.PointerToSymbolTable));
392 CBA.write(Val: CP.Obj.Header.NumberOfSymbols, E: LittleEndian);
393 } else {
394 CBA.write(Val: CP.Obj.Header.Machine, E: LittleEndian);
395 CBA.write(Val: static_cast<int16_t>(CP.Obj.Header.NumberOfSections),
396 E: LittleEndian);
397 CBA.write(Val: CP.Obj.Header.TimeDateStamp, E: LittleEndian);
398 PointerToSymbolTableOffset = CBA.getOffset();
399 // The final symbol table offset is written after the section data.
400 CBA.writeZeros(Num: sizeof(CP.Obj.Header.PointerToSymbolTable));
401 CBA.write(Val: CP.Obj.Header.NumberOfSymbols, E: LittleEndian);
402 CBA.write(Val: CP.Obj.Header.SizeOfOptionalHeader, E: LittleEndian);
403 CBA.write(Val: CP.Obj.Header.Characteristics, E: LittleEndian);
404 }
405 if (CP.isPE()) {
406 if (CP.is64Bit()) {
407 object::pe32plus_header PEH;
408 initializeOptionalHeader(CP, Magic: COFF::PE32Header::PE32_PLUS, Header: &PEH);
409 CBA.write(Ptr: reinterpret_cast<const char *>(&PEH), Size: sizeof(PEH));
410 } else {
411 object::pe32_header PEH;
412 uint32_t BaseOfData =
413 initializeOptionalHeader(CP, Magic: COFF::PE32Header::PE32, Header: &PEH);
414 PEH.BaseOfData = BaseOfData;
415 CBA.write(Ptr: reinterpret_cast<const char *>(&PEH), Size: sizeof(PEH));
416 }
417 for (uint32_t I = 0; I < CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
418 ++I) {
419 const std::optional<COFF::DataDirectory> *DataDirectories =
420 CP.Obj.OptionalHeader->DataDirectories;
421 uint32_t NumDataDir = std::size(CP.Obj.OptionalHeader->DataDirectories);
422 if (I >= NumDataDir || !DataDirectories[I]) {
423 CBA.writeZeros(Num: 2 * sizeof(uint32_t));
424 } else {
425 CBA.write(Val: DataDirectories[I]->RelativeVirtualAddress, E: LittleEndian);
426 CBA.write(Val: DataDirectories[I]->Size, E: LittleEndian);
427 }
428 }
429 }
430
431 assert(CBA.getOffset() == CP.SectionTableStart);
432 // Output section table.
433 for (const COFFYAML::Section &S : CP.Obj.Sections) {
434 CBA.write(Ptr: S.Header.Name, Size: COFF::NameSize);
435 CBA.write(Val: S.Header.VirtualSize, E: LittleEndian);
436 CBA.write(Val: S.Header.VirtualAddress, E: LittleEndian);
437 CBA.write(Val: S.Header.SizeOfRawData, E: LittleEndian);
438 CBA.write(Val: S.Header.PointerToRawData, E: LittleEndian);
439 CBA.write(Val: S.Header.PointerToRelocations, E: LittleEndian);
440 CBA.write(Val: S.Header.PointerToLineNumbers, E: LittleEndian);
441 CBA.write(Val: S.Header.NumberOfRelocations, E: LittleEndian);
442 CBA.write(Val: S.Header.NumberOfLineNumbers, E: LittleEndian);
443 CBA.write(Val: S.Header.Characteristics, E: LittleEndian);
444 }
445 assert(CBA.getOffset() == CP.SectionTableStart + CP.SectionTableSize);
446
447 unsigned CurSymbol = 0;
448 StringMap<unsigned> SymbolTableIndexMap;
449 for (const COFFYAML::Symbol &Sym : CP.Obj.Symbols) {
450 SymbolTableIndexMap[Sym.Name] = CurSymbol;
451 CurSymbol += 1 + Sym.Header.NumberOfAuxSymbols;
452 }
453
454 // Output section data.
455 for (const COFFYAML::Section &S : CP.Obj.Sections) {
456 if (S.Header.SizeOfRawData == 0 || S.Header.PointerToRawData == 0)
457 continue;
458 assert(S.Header.PointerToRawData >= CBA.getOffset());
459 CBA.writeZeros(Num: S.Header.PointerToRawData - CBA.getOffset());
460 for (auto E : S.StructuredData)
461 E.writeAsBinary(CBA);
462 CBA.writeAsBinary(Bin: S.SectionData);
463 assert(S.Header.PointerToRawData + S.Header.SizeOfRawData >=
464 CBA.getOffset());
465 CBA.writeZeros(Num: S.Header.PointerToRawData + S.Header.SizeOfRawData -
466 CBA.getOffset());
467 if (S.Header.Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) {
468 CBA.write<uint32_t>(/*VirtualAddress=*/Val: S.Relocations.size() + 1,
469 E: LittleEndian);
470 CBA.write<uint32_t>(/*SymbolTableIndex=*/Val: 0, E: LittleEndian);
471 CBA.write<uint16_t>(/*Type=*/Val: 0, E: LittleEndian);
472 }
473 for (const COFFYAML::Relocation &R : S.Relocations) {
474 uint32_t SymbolTableIndex;
475 if (R.SymbolTableIndex) {
476 if (!R.SymbolName.empty())
477 WithColor::error()
478 << "Both SymbolName and SymbolTableIndex specified\n";
479 SymbolTableIndex = *R.SymbolTableIndex;
480 } else {
481 SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];
482 }
483 CBA.write(Val: R.VirtualAddress, E: LittleEndian);
484 CBA.write(Val: SymbolTableIndex, E: LittleEndian);
485 CBA.write(Val: R.Type, E: LittleEndian);
486 }
487 }
488
489 // Output symbol table.
490 if (CP.Obj.Header.NumberOfSymbols || CP.StringTable.size() > 4)
491 CP.Obj.Header.PointerToSymbolTable = CBA.getOffset();
492 else
493 CP.Obj.Header.PointerToSymbolTable = 0;
494
495 CBA.updateDataAt(Pos: PointerToSymbolTableOffset,
496 Val: CP.Obj.Header.PointerToSymbolTable, E: LittleEndian);
497
498 for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(),
499 e = CP.Obj.Symbols.end();
500 i != e; ++i) {
501 CBA.write(Ptr: i->Header.Name, Size: COFF::NameSize);
502 CBA.write(Val: i->Header.Value, E: LittleEndian);
503 if (CP.useBigObj())
504 CBA.write(Val: i->Header.SectionNumber, E: LittleEndian);
505 else
506 CBA.write(Val: static_cast<int16_t>(i->Header.SectionNumber), E: LittleEndian);
507 CBA.write(Val: i->Header.Type, E: LittleEndian);
508 CBA.write(Val: i->Header.StorageClass, E: LittleEndian);
509 CBA.write(Val: i->Header.NumberOfAuxSymbols, E: LittleEndian);
510
511 if (i->FunctionDefinition) {
512 CBA.write(Val: i->FunctionDefinition->TagIndex, E: LittleEndian);
513 CBA.write(Val: i->FunctionDefinition->TotalSize, E: LittleEndian);
514 CBA.write(Val: i->FunctionDefinition->PointerToLinenumber, E: LittleEndian);
515 CBA.write(Val: i->FunctionDefinition->PointerToNextFunction, E: LittleEndian);
516 CBA.writeZeros(Num: sizeof(i->FunctionDefinition->unused));
517 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
518 }
519 if (i->bfAndefSymbol) {
520 CBA.writeZeros(Num: sizeof(i->bfAndefSymbol->unused1));
521 CBA.write(Val: i->bfAndefSymbol->Linenumber, E: LittleEndian);
522 CBA.writeZeros(Num: sizeof(i->bfAndefSymbol->unused2));
523 CBA.write(Val: i->bfAndefSymbol->PointerToNextFunction, E: LittleEndian);
524 CBA.writeZeros(Num: sizeof(i->bfAndefSymbol->unused3));
525 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
526 }
527 if (i->WeakExternal) {
528 CBA.write(Val: i->WeakExternal->TagIndex, E: LittleEndian);
529 CBA.write(Val: i->WeakExternal->Characteristics, E: LittleEndian);
530 CBA.writeZeros(Num: sizeof(i->WeakExternal->unused));
531 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
532 }
533 if (!i->File.empty()) {
534 unsigned SymbolSize = CP.getSymbolSize();
535 uint32_t NumberOfAuxRecords =
536 (i->File.size() + SymbolSize - 1) / SymbolSize;
537 uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize;
538 uint32_t NumZeros = NumberOfAuxBytes - i->File.size();
539 CBA.write(Ptr: i->File.data(), Size: i->File.size());
540 CBA.writeZeros(Num: NumZeros);
541 }
542 if (i->SectionDefinition) {
543 CBA.write(Val: i->SectionDefinition->Length, E: LittleEndian);
544 CBA.write(Val: i->SectionDefinition->NumberOfRelocations, E: LittleEndian);
545 CBA.write(Val: i->SectionDefinition->NumberOfLinenumbers, E: LittleEndian);
546 CBA.write(Val: i->SectionDefinition->CheckSum, E: LittleEndian);
547 CBA.write(Val: static_cast<int16_t>(i->SectionDefinition->Number),
548 E: LittleEndian);
549 CBA.write(Val: i->SectionDefinition->Selection, E: LittleEndian);
550 CBA.writeZeros(Num: sizeof(i->SectionDefinition->unused));
551 CBA.write(Val: static_cast<int16_t>(i->SectionDefinition->Number >> 16),
552 E: LittleEndian);
553 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
554 }
555 if (i->CLRToken) {
556 CBA.write(Val: i->CLRToken->AuxType, E: LittleEndian);
557 CBA.writeZeros(Num: sizeof(i->CLRToken->unused1));
558 CBA.write(Val: i->CLRToken->SymbolTableIndex, E: LittleEndian);
559 CBA.writeZeros(Num: sizeof(i->CLRToken->unused2));
560 CBA.writeZeros(Num: CP.getSymbolSize() - COFF::Symbol16Size);
561 }
562 }
563
564 // Output string table.
565 if (CP.Obj.Header.PointerToSymbolTable)
566 CBA.write(Ptr: CP.StringTable.data(), Size: CP.StringTable.size());
567 return true;
568}
569
570size_t COFFYAML::SectionDataEntry::size() const {
571 size_t Size = Binary.binary_size();
572 if (UInt32)
573 Size += sizeof(*UInt32);
574 if (LoadConfig32)
575 Size += LoadConfig32->Size;
576 if (LoadConfig64)
577 Size += LoadConfig64->Size;
578 return Size;
579}
580
581template <typename T>
582static void writeLoadConfig(T &S, ContiguousBlobAccumulator &CBA) {
583 CBA.write(Ptr: reinterpret_cast<const char *>(&S),
584 Size: std::min(a: sizeof(S), b: static_cast<size_t>(S.Size)));
585 if (sizeof(S) < S.Size)
586 CBA.writeZeros(Num: S.Size - sizeof(S));
587}
588
589void COFFYAML::SectionDataEntry::writeAsBinary(
590 ContiguousBlobAccumulator &CBA) const {
591 if (UInt32)
592 CBA.write(Val: *UInt32, E: LittleEndian);
593 CBA.writeAsBinary(Bin: Binary);
594 if (LoadConfig32)
595 writeLoadConfig(S: *LoadConfig32, CBA);
596 if (LoadConfig64)
597 writeLoadConfig(S: *LoadConfig64, CBA);
598}
599
600namespace llvm {
601namespace yaml {
602
603bool yaml2coff(llvm::COFFYAML::Object &Doc, raw_ostream &Out,
604 ErrorHandler ErrHandler, uint64_t MaxSize) {
605 COFFParser CP(Doc, ErrHandler);
606 if (!CP.parse()) {
607 ErrHandler("failed to parse YAML file");
608 return false;
609 }
610
611 if (!layoutOptionalHeader(CP)) {
612 ErrHandler("failed to layout optional header for COFF file");
613 return false;
614 }
615
616 if (!layoutCOFF(CP)) {
617 ErrHandler("failed to layout COFF file");
618 return false;
619 }
620
621 // Limit the output size to guard against a runaway YAML description.
622 ContiguousBlobAccumulator CBA(/*BaseOffset=*/0, MaxSize);
623 if (!writeCOFF(CP, CBA)) {
624 ErrHandler("failed to write COFF file");
625 return false;
626 }
627 if (Error E = CBA.takeLimitError()) {
628 // Match ELF by reporting a custom error message instead below.
629 consumeError(Err: std::move(E));
630 ErrHandler("the desired output size is greater than permitted. Use the "
631 "--max-size option to change the limit");
632 return false;
633 }
634
635 CBA.writeBlobToStream(Out);
636 return true;
637}
638
639} // namespace yaml
640} // namespace llvm
641