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