Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / tools / yaml2obj / yaml2coff.cpp
blob223ade065e1c5fc5b9ce790c47b379996b6e46dd
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 //===----------------------------------------------------------------------===//
14 #include "yaml2obj.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
20 #include "llvm/DebugInfo/CodeView/StringsAndChecksums.h"
21 #include "llvm/Object/COFF.h"
22 #include "llvm/ObjectYAML/ObjectYAML.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/WithColor.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <vector>
30 using namespace llvm;
32 /// This parses a yaml stream that represents a COFF object file.
33 /// See docs/yaml2obj for the yaml scheema.
34 struct COFFParser {
35 COFFParser(COFFYAML::Object &Obj)
36 : Obj(Obj), SectionTableStart(0), SectionTableSize(0) {
37 // A COFF string table always starts with a 4 byte size field. Offsets into
38 // it include this size, so allocate it now.
39 StringTable.append(4, char(0));
42 bool useBigObj() const {
43 return static_cast<int32_t>(Obj.Sections.size()) >
44 COFF::MaxNumberOfSections16;
47 bool isPE() const { return Obj.OptionalHeader.hasValue(); }
48 bool is64Bit() const {
49 return Obj.Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 ||
50 Obj.Header.Machine == COFF::IMAGE_FILE_MACHINE_ARM64;
53 uint32_t getFileAlignment() const {
54 return Obj.OptionalHeader->Header.FileAlignment;
57 unsigned getHeaderSize() const {
58 return useBigObj() ? COFF::Header32Size : COFF::Header16Size;
61 unsigned getSymbolSize() const {
62 return useBigObj() ? COFF::Symbol32Size : COFF::Symbol16Size;
65 bool parseSections() {
66 for (std::vector<COFFYAML::Section>::iterator i = Obj.Sections.begin(),
67 e = Obj.Sections.end(); i != e; ++i) {
68 COFFYAML::Section &Sec = *i;
70 // If the name is less than 8 bytes, store it in place, otherwise
71 // store it in the string table.
72 StringRef Name = Sec.Name;
74 if (Name.size() <= COFF::NameSize) {
75 std::copy(Name.begin(), Name.end(), Sec.Header.Name);
76 } else {
77 // Add string to the string table and format the index for output.
78 unsigned Index = getStringIndex(Name);
79 std::string str = utostr(Index);
80 if (str.size() > 7) {
81 errs() << "String table got too large\n";
82 return false;
84 Sec.Header.Name[0] = '/';
85 std::copy(str.begin(), str.end(), Sec.Header.Name + 1);
88 if (Sec.Alignment) {
89 if (Sec.Alignment > 8192) {
90 errs() << "Section alignment is too large\n";
91 return false;
93 if (!isPowerOf2_32(Sec.Alignment)) {
94 errs() << "Section alignment is not a power of 2\n";
95 return false;
97 Sec.Header.Characteristics |= (Log2_32(Sec.Alignment) + 1) << 20;
100 return true;
103 bool parseSymbols() {
104 for (std::vector<COFFYAML::Symbol>::iterator i = Obj.Symbols.begin(),
105 e = Obj.Symbols.end(); i != e; ++i) {
106 COFFYAML::Symbol &Sym = *i;
108 // If the name is less than 8 bytes, store it in place, otherwise
109 // store it in the string table.
110 StringRef Name = Sym.Name;
111 if (Name.size() <= COFF::NameSize) {
112 std::copy(Name.begin(), Name.end(), Sym.Header.Name);
113 } else {
114 // Add string to the string table and format the index for output.
115 unsigned Index = getStringIndex(Name);
116 *reinterpret_cast<support::aligned_ulittle32_t*>(
117 Sym.Header.Name + 4) = Index;
120 Sym.Header.Type = Sym.SimpleType;
121 Sym.Header.Type |= Sym.ComplexType << COFF::SCT_COMPLEX_TYPE_SHIFT;
123 return true;
126 bool parse() {
127 if (!parseSections())
128 return false;
129 if (!parseSymbols())
130 return false;
131 return true;
134 unsigned getStringIndex(StringRef Str) {
135 StringMap<unsigned>::iterator i = StringTableMap.find(Str);
136 if (i == StringTableMap.end()) {
137 unsigned Index = StringTable.size();
138 StringTable.append(Str.begin(), Str.end());
139 StringTable.push_back(0);
140 StringTableMap[Str] = Index;
141 return Index;
143 return i->second;
146 COFFYAML::Object &Obj;
148 codeview::StringsAndChecksums StringsAndChecksums;
149 BumpPtrAllocator Allocator;
150 StringMap<unsigned> StringTableMap;
151 std::string StringTable;
152 uint32_t SectionTableStart;
153 uint32_t SectionTableSize;
156 // Take a CP and assign addresses and sizes to everything. Returns false if the
157 // layout is not valid to do.
158 static bool layoutOptionalHeader(COFFParser &CP) {
159 if (!CP.isPE())
160 return true;
161 unsigned PEHeaderSize = CP.is64Bit() ? sizeof(object::pe32plus_header)
162 : sizeof(object::pe32_header);
163 CP.Obj.Header.SizeOfOptionalHeader =
164 PEHeaderSize +
165 sizeof(object::data_directory) * (COFF::NUM_DATA_DIRECTORIES + 1);
166 return true;
169 namespace {
170 enum { DOSStubSize = 128 };
173 static yaml::BinaryRef
174 toDebugS(ArrayRef<CodeViewYAML::YAMLDebugSubsection> Subsections,
175 const codeview::StringsAndChecksums &SC, BumpPtrAllocator &Allocator) {
176 using namespace codeview;
177 ExitOnError Err("Error occurred writing .debug$S section");
178 auto CVSS =
179 Err(CodeViewYAML::toCodeViewSubsectionList(Allocator, Subsections, SC));
181 std::vector<DebugSubsectionRecordBuilder> Builders;
182 uint32_t Size = sizeof(uint32_t);
183 for (auto &SS : CVSS) {
184 DebugSubsectionRecordBuilder B(SS, CodeViewContainer::ObjectFile);
185 Size += B.calculateSerializedLength();
186 Builders.push_back(std::move(B));
188 uint8_t *Buffer = Allocator.Allocate<uint8_t>(Size);
189 MutableArrayRef<uint8_t> Output(Buffer, Size);
190 BinaryStreamWriter Writer(Output, support::little);
192 Err(Writer.writeInteger<uint32_t>(COFF::DEBUG_SECTION_MAGIC));
193 for (const auto &B : Builders) {
194 Err(B.commit(Writer));
196 return {Output};
199 // Take a CP and assign addresses and sizes to everything. Returns false if the
200 // layout is not valid to do.
201 static bool layoutCOFF(COFFParser &CP) {
202 // The section table starts immediately after the header, including the
203 // optional header.
204 CP.SectionTableStart =
205 CP.getHeaderSize() + CP.Obj.Header.SizeOfOptionalHeader;
206 if (CP.isPE())
207 CP.SectionTableStart += DOSStubSize + sizeof(COFF::PEMagic);
208 CP.SectionTableSize = COFF::SectionSize * CP.Obj.Sections.size();
210 uint32_t CurrentSectionDataOffset =
211 CP.SectionTableStart + CP.SectionTableSize;
213 for (COFFYAML::Section &S : CP.Obj.Sections) {
214 // We support specifying exactly one of SectionData or Subsections. So if
215 // there is already some SectionData, then we don't need to do any of this.
216 if (S.Name == ".debug$S" && S.SectionData.binary_size() == 0) {
217 CodeViewYAML::initializeStringsAndChecksums(S.DebugS,
218 CP.StringsAndChecksums);
219 if (CP.StringsAndChecksums.hasChecksums() &&
220 CP.StringsAndChecksums.hasStrings())
221 break;
225 // Assign each section data address consecutively.
226 for (COFFYAML::Section &S : CP.Obj.Sections) {
227 if (S.Name == ".debug$S") {
228 if (S.SectionData.binary_size() == 0) {
229 assert(CP.StringsAndChecksums.hasStrings() &&
230 "Object file does not have debug string table!");
232 S.SectionData =
233 toDebugS(S.DebugS, CP.StringsAndChecksums, CP.Allocator);
235 } else if (S.Name == ".debug$T") {
236 if (S.SectionData.binary_size() == 0)
237 S.SectionData = CodeViewYAML::toDebugT(S.DebugT, CP.Allocator, S.Name);
238 } else if (S.Name == ".debug$P") {
239 if (S.SectionData.binary_size() == 0)
240 S.SectionData = CodeViewYAML::toDebugT(S.DebugP, CP.Allocator, S.Name);
241 } else if (S.Name == ".debug$H") {
242 if (S.DebugH.hasValue() && S.SectionData.binary_size() == 0)
243 S.SectionData = CodeViewYAML::toDebugH(*S.DebugH, CP.Allocator);
246 if (S.SectionData.binary_size() > 0) {
247 CurrentSectionDataOffset = alignTo(CurrentSectionDataOffset,
248 CP.isPE() ? CP.getFileAlignment() : 4);
249 S.Header.SizeOfRawData = S.SectionData.binary_size();
250 if (CP.isPE())
251 S.Header.SizeOfRawData =
252 alignTo(S.Header.SizeOfRawData, CP.getFileAlignment());
253 S.Header.PointerToRawData = CurrentSectionDataOffset;
254 CurrentSectionDataOffset += S.Header.SizeOfRawData;
255 if (!S.Relocations.empty()) {
256 S.Header.PointerToRelocations = CurrentSectionDataOffset;
257 S.Header.NumberOfRelocations = S.Relocations.size();
258 CurrentSectionDataOffset +=
259 S.Header.NumberOfRelocations * COFF::RelocationSize;
261 } else {
262 S.Header.SizeOfRawData = 0;
263 S.Header.PointerToRawData = 0;
267 uint32_t SymbolTableStart = CurrentSectionDataOffset;
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;
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;
300 *reinterpret_cast<support::ulittle32_t *>(&CP.StringTable[0])
301 = CP.StringTable.size();
303 return true;
306 template <typename value_type>
307 struct binary_le_impl {
308 value_type Value;
309 binary_le_impl(value_type V) : Value(V) {}
312 template <typename value_type>
313 raw_ostream &operator <<( raw_ostream &OS
314 , const binary_le_impl<value_type> &BLE) {
315 char Buffer[sizeof(BLE.Value)];
316 support::endian::write<value_type, support::little, support::unaligned>(
317 Buffer, BLE.Value);
318 OS.write(Buffer, sizeof(BLE.Value));
319 return OS;
322 template <typename value_type>
323 binary_le_impl<value_type> binary_le(value_type V) {
324 return binary_le_impl<value_type>(V);
327 template <size_t NumBytes> struct zeros_impl {};
329 template <size_t NumBytes>
330 raw_ostream &operator<<(raw_ostream &OS, const zeros_impl<NumBytes> &) {
331 char Buffer[NumBytes];
332 memset(Buffer, 0, sizeof(Buffer));
333 OS.write(Buffer, sizeof(Buffer));
334 return OS;
337 template <typename T>
338 zeros_impl<sizeof(T)> zeros(const T &) {
339 return zeros_impl<sizeof(T)>();
342 struct num_zeros_impl {
343 size_t N;
344 num_zeros_impl(size_t N) : N(N) {}
347 raw_ostream &operator<<(raw_ostream &OS, const num_zeros_impl &NZI) {
348 for (size_t I = 0; I != NZI.N; ++I)
349 OS.write(0);
350 return OS;
353 static num_zeros_impl num_zeros(size_t N) {
354 num_zeros_impl NZI(N);
355 return NZI;
358 template <typename T>
359 static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic, T Header) {
360 memset(Header, 0, sizeof(*Header));
361 Header->Magic = Magic;
362 Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment;
363 Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment;
364 uint32_t SizeOfCode = 0, SizeOfInitializedData = 0,
365 SizeOfUninitializedData = 0;
366 uint32_t SizeOfHeaders = alignTo(CP.SectionTableStart + CP.SectionTableSize,
367 Header->FileAlignment);
368 uint32_t SizeOfImage = alignTo(SizeOfHeaders, Header->SectionAlignment);
369 uint32_t BaseOfData = 0;
370 for (const COFFYAML::Section &S : CP.Obj.Sections) {
371 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_CODE)
372 SizeOfCode += S.Header.SizeOfRawData;
373 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
374 SizeOfInitializedData += S.Header.SizeOfRawData;
375 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
376 SizeOfUninitializedData += S.Header.SizeOfRawData;
377 if (S.Name.equals(".text"))
378 Header->BaseOfCode = S.Header.VirtualAddress; // RVA
379 else if (S.Name.equals(".data"))
380 BaseOfData = S.Header.VirtualAddress; // RVA
381 if (S.Header.VirtualAddress)
382 SizeOfImage += alignTo(S.Header.VirtualSize, Header->SectionAlignment);
384 Header->SizeOfCode = SizeOfCode;
385 Header->SizeOfInitializedData = SizeOfInitializedData;
386 Header->SizeOfUninitializedData = SizeOfUninitializedData;
387 Header->AddressOfEntryPoint =
388 CP.Obj.OptionalHeader->Header.AddressOfEntryPoint; // RVA
389 Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase;
390 Header->MajorOperatingSystemVersion =
391 CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion;
392 Header->MinorOperatingSystemVersion =
393 CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion;
394 Header->MajorImageVersion =
395 CP.Obj.OptionalHeader->Header.MajorImageVersion;
396 Header->MinorImageVersion =
397 CP.Obj.OptionalHeader->Header.MinorImageVersion;
398 Header->MajorSubsystemVersion =
399 CP.Obj.OptionalHeader->Header.MajorSubsystemVersion;
400 Header->MinorSubsystemVersion =
401 CP.Obj.OptionalHeader->Header.MinorSubsystemVersion;
402 Header->SizeOfImage = SizeOfImage;
403 Header->SizeOfHeaders = SizeOfHeaders;
404 Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem;
405 Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics;
406 Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve;
407 Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit;
408 Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve;
409 Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit;
410 Header->NumberOfRvaAndSize = COFF::NUM_DATA_DIRECTORIES + 1;
411 return BaseOfData;
414 static bool writeCOFF(COFFParser &CP, raw_ostream &OS) {
415 if (CP.isPE()) {
416 // PE files start with a DOS stub.
417 object::dos_header DH;
418 memset(&DH, 0, sizeof(DH));
420 // DOS EXEs start with "MZ" magic.
421 DH.Magic[0] = 'M';
422 DH.Magic[1] = 'Z';
423 // Initializing the AddressOfRelocationTable is strictly optional but
424 // mollifies certain tools which expect it to have a value greater than
425 // 0x40.
426 DH.AddressOfRelocationTable = sizeof(DH);
427 // This is the address of the PE signature.
428 DH.AddressOfNewExeHeader = DOSStubSize;
430 // Write out our DOS stub.
431 OS.write(reinterpret_cast<char *>(&DH), sizeof(DH));
432 // Write padding until we reach the position of where our PE signature
433 // should live.
434 OS << num_zeros(DOSStubSize - sizeof(DH));
435 // Write out the PE signature.
436 OS.write(COFF::PEMagic, sizeof(COFF::PEMagic));
438 if (CP.useBigObj()) {
439 OS << binary_le(static_cast<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN))
440 << binary_le(static_cast<uint16_t>(0xffff))
441 << binary_le(static_cast<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion))
442 << binary_le(CP.Obj.Header.Machine)
443 << binary_le(CP.Obj.Header.TimeDateStamp);
444 OS.write(COFF::BigObjMagic, sizeof(COFF::BigObjMagic));
445 OS << zeros(uint32_t(0))
446 << zeros(uint32_t(0))
447 << zeros(uint32_t(0))
448 << zeros(uint32_t(0))
449 << binary_le(CP.Obj.Header.NumberOfSections)
450 << binary_le(CP.Obj.Header.PointerToSymbolTable)
451 << binary_le(CP.Obj.Header.NumberOfSymbols);
452 } else {
453 OS << binary_le(CP.Obj.Header.Machine)
454 << binary_le(static_cast<int16_t>(CP.Obj.Header.NumberOfSections))
455 << binary_le(CP.Obj.Header.TimeDateStamp)
456 << binary_le(CP.Obj.Header.PointerToSymbolTable)
457 << binary_le(CP.Obj.Header.NumberOfSymbols)
458 << binary_le(CP.Obj.Header.SizeOfOptionalHeader)
459 << binary_le(CP.Obj.Header.Characteristics);
461 if (CP.isPE()) {
462 if (CP.is64Bit()) {
463 object::pe32plus_header PEH;
464 initializeOptionalHeader(CP, COFF::PE32Header::PE32_PLUS, &PEH);
465 OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));
466 } else {
467 object::pe32_header PEH;
468 uint32_t BaseOfData = initializeOptionalHeader(CP, COFF::PE32Header::PE32, &PEH);
469 PEH.BaseOfData = BaseOfData;
470 OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));
472 for (const Optional<COFF::DataDirectory> &DD :
473 CP.Obj.OptionalHeader->DataDirectories) {
474 if (!DD.hasValue()) {
475 OS << zeros(uint32_t(0));
476 OS << zeros(uint32_t(0));
477 } else {
478 OS << binary_le(DD->RelativeVirtualAddress);
479 OS << binary_le(DD->Size);
482 OS << zeros(uint32_t(0));
483 OS << zeros(uint32_t(0));
486 assert(OS.tell() == CP.SectionTableStart);
487 // Output section table.
488 for (std::vector<COFFYAML::Section>::iterator i = CP.Obj.Sections.begin(),
489 e = CP.Obj.Sections.end();
490 i != e; ++i) {
491 OS.write(i->Header.Name, COFF::NameSize);
492 OS << binary_le(i->Header.VirtualSize)
493 << binary_le(i->Header.VirtualAddress)
494 << binary_le(i->Header.SizeOfRawData)
495 << binary_le(i->Header.PointerToRawData)
496 << binary_le(i->Header.PointerToRelocations)
497 << binary_le(i->Header.PointerToLineNumbers)
498 << binary_le(i->Header.NumberOfRelocations)
499 << binary_le(i->Header.NumberOfLineNumbers)
500 << binary_le(i->Header.Characteristics);
502 assert(OS.tell() == CP.SectionTableStart + CP.SectionTableSize);
504 unsigned CurSymbol = 0;
505 StringMap<unsigned> SymbolTableIndexMap;
506 for (std::vector<COFFYAML::Symbol>::iterator I = CP.Obj.Symbols.begin(),
507 E = CP.Obj.Symbols.end();
508 I != E; ++I) {
509 SymbolTableIndexMap[I->Name] = CurSymbol;
510 CurSymbol += 1 + I->Header.NumberOfAuxSymbols;
513 // Output section data.
514 for (const COFFYAML::Section &S : CP.Obj.Sections) {
515 if (!S.Header.SizeOfRawData)
516 continue;
517 assert(S.Header.PointerToRawData >= OS.tell());
518 OS << num_zeros(S.Header.PointerToRawData - OS.tell());
519 S.SectionData.writeAsBinary(OS);
520 assert(S.Header.SizeOfRawData >= S.SectionData.binary_size());
521 OS << num_zeros(S.Header.SizeOfRawData - S.SectionData.binary_size());
522 for (const COFFYAML::Relocation &R : S.Relocations) {
523 uint32_t SymbolTableIndex;
524 if (R.SymbolTableIndex) {
525 if (!R.SymbolName.empty())
526 WithColor::error()
527 << "Both SymbolName and SymbolTableIndex specified\n";
528 SymbolTableIndex = *R.SymbolTableIndex;
529 } else {
530 SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];
532 OS << binary_le(R.VirtualAddress)
533 << binary_le(SymbolTableIndex)
534 << binary_le(R.Type);
538 // Output symbol table.
540 for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(),
541 e = CP.Obj.Symbols.end();
542 i != e; ++i) {
543 OS.write(i->Header.Name, COFF::NameSize);
544 OS << binary_le(i->Header.Value);
545 if (CP.useBigObj())
546 OS << binary_le(i->Header.SectionNumber);
547 else
548 OS << binary_le(static_cast<int16_t>(i->Header.SectionNumber));
549 OS << binary_le(i->Header.Type)
550 << binary_le(i->Header.StorageClass)
551 << binary_le(i->Header.NumberOfAuxSymbols);
553 if (i->FunctionDefinition)
554 OS << binary_le(i->FunctionDefinition->TagIndex)
555 << binary_le(i->FunctionDefinition->TotalSize)
556 << binary_le(i->FunctionDefinition->PointerToLinenumber)
557 << binary_le(i->FunctionDefinition->PointerToNextFunction)
558 << zeros(i->FunctionDefinition->unused)
559 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
560 if (i->bfAndefSymbol)
561 OS << zeros(i->bfAndefSymbol->unused1)
562 << binary_le(i->bfAndefSymbol->Linenumber)
563 << zeros(i->bfAndefSymbol->unused2)
564 << binary_le(i->bfAndefSymbol->PointerToNextFunction)
565 << zeros(i->bfAndefSymbol->unused3)
566 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
567 if (i->WeakExternal)
568 OS << binary_le(i->WeakExternal->TagIndex)
569 << binary_le(i->WeakExternal->Characteristics)
570 << zeros(i->WeakExternal->unused)
571 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
572 if (!i->File.empty()) {
573 unsigned SymbolSize = CP.getSymbolSize();
574 uint32_t NumberOfAuxRecords =
575 (i->File.size() + SymbolSize - 1) / SymbolSize;
576 uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize;
577 uint32_t NumZeros = NumberOfAuxBytes - i->File.size();
578 OS.write(i->File.data(), i->File.size());
579 OS << num_zeros(NumZeros);
581 if (i->SectionDefinition)
582 OS << binary_le(i->SectionDefinition->Length)
583 << binary_le(i->SectionDefinition->NumberOfRelocations)
584 << binary_le(i->SectionDefinition->NumberOfLinenumbers)
585 << binary_le(i->SectionDefinition->CheckSum)
586 << binary_le(static_cast<int16_t>(i->SectionDefinition->Number))
587 << binary_le(i->SectionDefinition->Selection)
588 << zeros(i->SectionDefinition->unused)
589 << binary_le(static_cast<int16_t>(i->SectionDefinition->Number >> 16))
590 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
591 if (i->CLRToken)
592 OS << binary_le(i->CLRToken->AuxType)
593 << zeros(i->CLRToken->unused1)
594 << binary_le(i->CLRToken->SymbolTableIndex)
595 << zeros(i->CLRToken->unused2)
596 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
599 // Output string table.
600 if (CP.Obj.Header.PointerToSymbolTable)
601 OS.write(&CP.StringTable[0], CP.StringTable.size());
602 return true;
605 int yaml2coff(llvm::COFFYAML::Object &Doc, raw_ostream &Out) {
606 COFFParser CP(Doc);
607 if (!CP.parse()) {
608 errs() << "yaml2obj: Failed to parse YAML file!\n";
609 return 1;
612 if (!layoutOptionalHeader(CP)) {
613 errs() << "yaml2obj: Failed to layout optional header for COFF file!\n";
614 return 1;
617 if (!layoutCOFF(CP)) {
618 errs() << "yaml2obj: Failed to layout COFF file!\n";
619 return 1;
621 if (!writeCOFF(CP, Out)) {
622 errs() << "yaml2obj: Failed to write COFF file!\n";
623 return 1;
625 return 0;