[llvm-exegesis] Implements a cache of Instruction objects.
[llvm-core.git] / tools / yaml2obj / yaml2coff.cpp
blobbefa01b369c0427ea035a08532df07b91ae867ba
1 //===- yaml2coff - Convert YAML to a COFF object file ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// The COFF component of yaml2obj.
12 ///
13 //===----------------------------------------------------------------------===//
15 #include "yaml2obj.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
21 #include "llvm/DebugInfo/CodeView/StringsAndChecksums.h"
22 #include "llvm/Object/COFF.h"
23 #include "llvm/ObjectYAML/ObjectYAML.h"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/SourceMgr.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;
52 uint32_t getFileAlignment() const {
53 return Obj.OptionalHeader->Header.FileAlignment;
56 unsigned getHeaderSize() const {
57 return useBigObj() ? COFF::Header32Size : COFF::Header16Size;
60 unsigned getSymbolSize() const {
61 return useBigObj() ? COFF::Symbol32Size : COFF::Symbol16Size;
64 bool parseSections() {
65 for (std::vector<COFFYAML::Section>::iterator i = Obj.Sections.begin(),
66 e = Obj.Sections.end(); i != e; ++i) {
67 COFFYAML::Section &Sec = *i;
69 // If the name is less than 8 bytes, store it in place, otherwise
70 // store it in the string table.
71 StringRef Name = Sec.Name;
73 if (Name.size() <= COFF::NameSize) {
74 std::copy(Name.begin(), Name.end(), Sec.Header.Name);
75 } else {
76 // Add string to the string table and format the index for output.
77 unsigned Index = getStringIndex(Name);
78 std::string str = utostr(Index);
79 if (str.size() > 7) {
80 errs() << "String table got too large\n";
81 return false;
83 Sec.Header.Name[0] = '/';
84 std::copy(str.begin(), str.end(), Sec.Header.Name + 1);
87 if (Sec.Alignment) {
88 if (Sec.Alignment > 8192) {
89 errs() << "Section alignment is too large\n";
90 return false;
92 if (!isPowerOf2_32(Sec.Alignment)) {
93 errs() << "Section alignment is not a power of 2\n";
94 return false;
96 Sec.Header.Characteristics |= (Log2_32(Sec.Alignment) + 1) << 20;
99 return true;
102 bool parseSymbols() {
103 for (std::vector<COFFYAML::Symbol>::iterator i = Obj.Symbols.begin(),
104 e = Obj.Symbols.end(); i != e; ++i) {
105 COFFYAML::Symbol &Sym = *i;
107 // If the name is less than 8 bytes, store it in place, otherwise
108 // store it in the string table.
109 StringRef Name = Sym.Name;
110 if (Name.size() <= COFF::NameSize) {
111 std::copy(Name.begin(), Name.end(), Sym.Header.Name);
112 } else {
113 // Add string to the string table and format the index for output.
114 unsigned Index = getStringIndex(Name);
115 *reinterpret_cast<support::aligned_ulittle32_t*>(
116 Sym.Header.Name + 4) = Index;
119 Sym.Header.Type = Sym.SimpleType;
120 Sym.Header.Type |= Sym.ComplexType << COFF::SCT_COMPLEX_TYPE_SHIFT;
122 return true;
125 bool parse() {
126 if (!parseSections())
127 return false;
128 if (!parseSymbols())
129 return false;
130 return true;
133 unsigned getStringIndex(StringRef Str) {
134 StringMap<unsigned>::iterator i = StringTableMap.find(Str);
135 if (i == StringTableMap.end()) {
136 unsigned Index = StringTable.size();
137 StringTable.append(Str.begin(), Str.end());
138 StringTable.push_back(0);
139 StringTableMap[Str] = Index;
140 return Index;
142 return i->second;
145 COFFYAML::Object &Obj;
147 codeview::StringsAndChecksums StringsAndChecksums;
148 BumpPtrAllocator Allocator;
149 StringMap<unsigned> StringTableMap;
150 std::string StringTable;
151 uint32_t SectionTableStart;
152 uint32_t SectionTableSize;
155 // Take a CP and assign addresses and sizes to everything. Returns false if the
156 // layout is not valid to do.
157 static 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 +
164 sizeof(object::data_directory) * (COFF::NUM_DATA_DIRECTORIES + 1);
165 return true;
168 namespace {
169 enum { DOSStubSize = 128 };
172 static yaml::BinaryRef
173 toDebugS(ArrayRef<CodeViewYAML::YAMLDebugSubsection> Subsections,
174 const codeview::StringsAndChecksums &SC, BumpPtrAllocator &Allocator) {
175 using namespace codeview;
176 ExitOnError Err("Error occurred writing .debug$S section");
177 auto CVSS =
178 Err(CodeViewYAML::toCodeViewSubsectionList(Allocator, Subsections, SC));
180 std::vector<DebugSubsectionRecordBuilder> Builders;
181 uint32_t Size = sizeof(uint32_t);
182 for (auto &SS : CVSS) {
183 DebugSubsectionRecordBuilder B(SS, CodeViewContainer::ObjectFile);
184 Size += B.calculateSerializedLength();
185 Builders.push_back(std::move(B));
187 uint8_t *Buffer = Allocator.Allocate<uint8_t>(Size);
188 MutableArrayRef<uint8_t> Output(Buffer, Size);
189 BinaryStreamWriter Writer(Output, support::little);
191 Err(Writer.writeInteger<uint32_t>(COFF::DEBUG_SECTION_MAGIC));
192 for (const auto &B : Builders) {
193 Err(B.commit(Writer));
195 return {Output};
198 // Take a CP and assign addresses and sizes to everything. Returns false if the
199 // layout is not valid to do.
200 static bool layoutCOFF(COFFParser &CP) {
201 // The section table starts immediately after the header, including the
202 // optional header.
203 CP.SectionTableStart =
204 CP.getHeaderSize() + CP.Obj.Header.SizeOfOptionalHeader;
205 if (CP.isPE())
206 CP.SectionTableStart += DOSStubSize + sizeof(COFF::PEMagic);
207 CP.SectionTableSize = COFF::SectionSize * CP.Obj.Sections.size();
209 uint32_t CurrentSectionDataOffset =
210 CP.SectionTableStart + CP.SectionTableSize;
212 for (COFFYAML::Section &S : CP.Obj.Sections) {
213 // We support specifying exactly one of SectionData or Subsections. So if
214 // there is already some SectionData, then we don't need to do any of this.
215 if (S.Name == ".debug$S" && S.SectionData.binary_size() == 0) {
216 CodeViewYAML::initializeStringsAndChecksums(S.DebugS,
217 CP.StringsAndChecksums);
218 if (CP.StringsAndChecksums.hasChecksums() &&
219 CP.StringsAndChecksums.hasStrings())
220 break;
224 // Assign each section data address consecutively.
225 for (COFFYAML::Section &S : CP.Obj.Sections) {
226 if (S.Name == ".debug$S") {
227 if (S.SectionData.binary_size() == 0) {
228 assert(CP.StringsAndChecksums.hasStrings() &&
229 "Object file does not have debug string table!");
231 S.SectionData =
232 toDebugS(S.DebugS, CP.StringsAndChecksums, CP.Allocator);
234 } else if (S.Name == ".debug$T") {
235 if (S.SectionData.binary_size() == 0)
236 S.SectionData = CodeViewYAML::toDebugT(S.DebugT, CP.Allocator, S.Name);
237 } else if (S.Name == ".debug$P") {
238 if (S.SectionData.binary_size() == 0)
239 S.SectionData = CodeViewYAML::toDebugT(S.DebugP, CP.Allocator, S.Name);
240 } else if (S.Name == ".debug$H") {
241 if (S.DebugH.hasValue() && S.SectionData.binary_size() == 0)
242 S.SectionData = CodeViewYAML::toDebugH(*S.DebugH, CP.Allocator);
245 if (S.SectionData.binary_size() > 0) {
246 CurrentSectionDataOffset = alignTo(CurrentSectionDataOffset,
247 CP.isPE() ? CP.getFileAlignment() : 4);
248 S.Header.SizeOfRawData = S.SectionData.binary_size();
249 if (CP.isPE())
250 S.Header.SizeOfRawData =
251 alignTo(S.Header.SizeOfRawData, CP.getFileAlignment());
252 S.Header.PointerToRawData = CurrentSectionDataOffset;
253 CurrentSectionDataOffset += S.Header.SizeOfRawData;
254 if (!S.Relocations.empty()) {
255 S.Header.PointerToRelocations = CurrentSectionDataOffset;
256 S.Header.NumberOfRelocations = S.Relocations.size();
257 CurrentSectionDataOffset +=
258 S.Header.NumberOfRelocations * COFF::RelocationSize;
260 } else {
261 S.Header.SizeOfRawData = 0;
262 S.Header.PointerToRawData = 0;
266 uint32_t SymbolTableStart = CurrentSectionDataOffset;
268 // Calculate number of symbols.
269 uint32_t NumberOfSymbols = 0;
270 for (std::vector<COFFYAML::Symbol>::iterator i = CP.Obj.Symbols.begin(),
271 e = CP.Obj.Symbols.end();
272 i != e; ++i) {
273 uint32_t NumberOfAuxSymbols = 0;
274 if (i->FunctionDefinition)
275 NumberOfAuxSymbols += 1;
276 if (i->bfAndefSymbol)
277 NumberOfAuxSymbols += 1;
278 if (i->WeakExternal)
279 NumberOfAuxSymbols += 1;
280 if (!i->File.empty())
281 NumberOfAuxSymbols +=
282 (i->File.size() + CP.getSymbolSize() - 1) / CP.getSymbolSize();
283 if (i->SectionDefinition)
284 NumberOfAuxSymbols += 1;
285 if (i->CLRToken)
286 NumberOfAuxSymbols += 1;
287 i->Header.NumberOfAuxSymbols = NumberOfAuxSymbols;
288 NumberOfSymbols += 1 + NumberOfAuxSymbols;
291 // Store all the allocated start addresses in the header.
292 CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size();
293 CP.Obj.Header.NumberOfSymbols = NumberOfSymbols;
294 if (NumberOfSymbols > 0 || CP.StringTable.size() > 4)
295 CP.Obj.Header.PointerToSymbolTable = SymbolTableStart;
296 else
297 CP.Obj.Header.PointerToSymbolTable = 0;
299 *reinterpret_cast<support::ulittle32_t *>(&CP.StringTable[0])
300 = CP.StringTable.size();
302 return true;
305 template <typename value_type>
306 struct binary_le_impl {
307 value_type Value;
308 binary_le_impl(value_type V) : Value(V) {}
311 template <typename value_type>
312 raw_ostream &operator <<( raw_ostream &OS
313 , const binary_le_impl<value_type> &BLE) {
314 char Buffer[sizeof(BLE.Value)];
315 support::endian::write<value_type, support::little, support::unaligned>(
316 Buffer, BLE.Value);
317 OS.write(Buffer, sizeof(BLE.Value));
318 return OS;
321 template <typename value_type>
322 binary_le_impl<value_type> binary_le(value_type V) {
323 return binary_le_impl<value_type>(V);
326 template <size_t NumBytes> struct zeros_impl {};
328 template <size_t NumBytes>
329 raw_ostream &operator<<(raw_ostream &OS, const zeros_impl<NumBytes> &) {
330 char Buffer[NumBytes];
331 memset(Buffer, 0, sizeof(Buffer));
332 OS.write(Buffer, sizeof(Buffer));
333 return OS;
336 template <typename T>
337 zeros_impl<sizeof(T)> zeros(const T &) {
338 return zeros_impl<sizeof(T)>();
341 struct num_zeros_impl {
342 size_t N;
343 num_zeros_impl(size_t N) : N(N) {}
346 raw_ostream &operator<<(raw_ostream &OS, const num_zeros_impl &NZI) {
347 for (size_t I = 0; I != NZI.N; ++I)
348 OS.write(0);
349 return OS;
352 static num_zeros_impl num_zeros(size_t N) {
353 num_zeros_impl NZI(N);
354 return NZI;
357 template <typename T>
358 static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic, T Header) {
359 memset(Header, 0, sizeof(*Header));
360 Header->Magic = Magic;
361 Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment;
362 Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment;
363 uint32_t SizeOfCode = 0, SizeOfInitializedData = 0,
364 SizeOfUninitializedData = 0;
365 uint32_t SizeOfHeaders = alignTo(CP.SectionTableStart + CP.SectionTableSize,
366 Header->FileAlignment);
367 uint32_t SizeOfImage = alignTo(SizeOfHeaders, Header->SectionAlignment);
368 uint32_t BaseOfData = 0;
369 for (const COFFYAML::Section &S : CP.Obj.Sections) {
370 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_CODE)
371 SizeOfCode += S.Header.SizeOfRawData;
372 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
373 SizeOfInitializedData += S.Header.SizeOfRawData;
374 if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
375 SizeOfUninitializedData += S.Header.SizeOfRawData;
376 if (S.Name.equals(".text"))
377 Header->BaseOfCode = S.Header.VirtualAddress; // RVA
378 else if (S.Name.equals(".data"))
379 BaseOfData = S.Header.VirtualAddress; // RVA
380 if (S.Header.VirtualAddress)
381 SizeOfImage += alignTo(S.Header.VirtualSize, Header->SectionAlignment);
383 Header->SizeOfCode = SizeOfCode;
384 Header->SizeOfInitializedData = SizeOfInitializedData;
385 Header->SizeOfUninitializedData = SizeOfUninitializedData;
386 Header->AddressOfEntryPoint =
387 CP.Obj.OptionalHeader->Header.AddressOfEntryPoint; // RVA
388 Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase;
389 Header->MajorOperatingSystemVersion =
390 CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion;
391 Header->MinorOperatingSystemVersion =
392 CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion;
393 Header->MajorImageVersion =
394 CP.Obj.OptionalHeader->Header.MajorImageVersion;
395 Header->MinorImageVersion =
396 CP.Obj.OptionalHeader->Header.MinorImageVersion;
397 Header->MajorSubsystemVersion =
398 CP.Obj.OptionalHeader->Header.MajorSubsystemVersion;
399 Header->MinorSubsystemVersion =
400 CP.Obj.OptionalHeader->Header.MinorSubsystemVersion;
401 Header->SizeOfImage = SizeOfImage;
402 Header->SizeOfHeaders = SizeOfHeaders;
403 Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem;
404 Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics;
405 Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve;
406 Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit;
407 Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve;
408 Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit;
409 Header->NumberOfRvaAndSize = COFF::NUM_DATA_DIRECTORIES + 1;
410 return BaseOfData;
413 static bool writeCOFF(COFFParser &CP, raw_ostream &OS) {
414 if (CP.isPE()) {
415 // PE files start with a DOS stub.
416 object::dos_header DH;
417 memset(&DH, 0, sizeof(DH));
419 // DOS EXEs start with "MZ" magic.
420 DH.Magic[0] = 'M';
421 DH.Magic[1] = 'Z';
422 // Initializing the AddressOfRelocationTable is strictly optional but
423 // mollifies certain tools which expect it to have a value greater than
424 // 0x40.
425 DH.AddressOfRelocationTable = sizeof(DH);
426 // This is the address of the PE signature.
427 DH.AddressOfNewExeHeader = DOSStubSize;
429 // Write out our DOS stub.
430 OS.write(reinterpret_cast<char *>(&DH), sizeof(DH));
431 // Write padding until we reach the position of where our PE signature
432 // should live.
433 OS << num_zeros(DOSStubSize - sizeof(DH));
434 // Write out the PE signature.
435 OS.write(COFF::PEMagic, sizeof(COFF::PEMagic));
437 if (CP.useBigObj()) {
438 OS << binary_le(static_cast<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN))
439 << binary_le(static_cast<uint16_t>(0xffff))
440 << binary_le(static_cast<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion))
441 << binary_le(CP.Obj.Header.Machine)
442 << binary_le(CP.Obj.Header.TimeDateStamp);
443 OS.write(COFF::BigObjMagic, sizeof(COFF::BigObjMagic));
444 OS << zeros(uint32_t(0))
445 << zeros(uint32_t(0))
446 << zeros(uint32_t(0))
447 << zeros(uint32_t(0))
448 << binary_le(CP.Obj.Header.NumberOfSections)
449 << binary_le(CP.Obj.Header.PointerToSymbolTable)
450 << binary_le(CP.Obj.Header.NumberOfSymbols);
451 } else {
452 OS << binary_le(CP.Obj.Header.Machine)
453 << binary_le(static_cast<int16_t>(CP.Obj.Header.NumberOfSections))
454 << binary_le(CP.Obj.Header.TimeDateStamp)
455 << binary_le(CP.Obj.Header.PointerToSymbolTable)
456 << binary_le(CP.Obj.Header.NumberOfSymbols)
457 << binary_le(CP.Obj.Header.SizeOfOptionalHeader)
458 << binary_le(CP.Obj.Header.Characteristics);
460 if (CP.isPE()) {
461 if (CP.is64Bit()) {
462 object::pe32plus_header PEH;
463 initializeOptionalHeader(CP, COFF::PE32Header::PE32_PLUS, &PEH);
464 OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));
465 } else {
466 object::pe32_header PEH;
467 uint32_t BaseOfData = initializeOptionalHeader(CP, COFF::PE32Header::PE32, &PEH);
468 PEH.BaseOfData = BaseOfData;
469 OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));
471 for (const Optional<COFF::DataDirectory> &DD :
472 CP.Obj.OptionalHeader->DataDirectories) {
473 if (!DD.hasValue()) {
474 OS << zeros(uint32_t(0));
475 OS << zeros(uint32_t(0));
476 } else {
477 OS << binary_le(DD->RelativeVirtualAddress);
478 OS << binary_le(DD->Size);
481 OS << zeros(uint32_t(0));
482 OS << zeros(uint32_t(0));
485 assert(OS.tell() == CP.SectionTableStart);
486 // Output section table.
487 for (std::vector<COFFYAML::Section>::iterator i = CP.Obj.Sections.begin(),
488 e = CP.Obj.Sections.end();
489 i != e; ++i) {
490 OS.write(i->Header.Name, COFF::NameSize);
491 OS << binary_le(i->Header.VirtualSize)
492 << binary_le(i->Header.VirtualAddress)
493 << binary_le(i->Header.SizeOfRawData)
494 << binary_le(i->Header.PointerToRawData)
495 << binary_le(i->Header.PointerToRelocations)
496 << binary_le(i->Header.PointerToLineNumbers)
497 << binary_le(i->Header.NumberOfRelocations)
498 << binary_le(i->Header.NumberOfLineNumbers)
499 << binary_le(i->Header.Characteristics);
501 assert(OS.tell() == CP.SectionTableStart + CP.SectionTableSize);
503 unsigned CurSymbol = 0;
504 StringMap<unsigned> SymbolTableIndexMap;
505 for (std::vector<COFFYAML::Symbol>::iterator I = CP.Obj.Symbols.begin(),
506 E = CP.Obj.Symbols.end();
507 I != E; ++I) {
508 SymbolTableIndexMap[I->Name] = CurSymbol;
509 CurSymbol += 1 + I->Header.NumberOfAuxSymbols;
512 // Output section data.
513 for (const COFFYAML::Section &S : CP.Obj.Sections) {
514 if (!S.Header.SizeOfRawData)
515 continue;
516 assert(S.Header.PointerToRawData >= OS.tell());
517 OS << num_zeros(S.Header.PointerToRawData - OS.tell());
518 S.SectionData.writeAsBinary(OS);
519 assert(S.Header.SizeOfRawData >= S.SectionData.binary_size());
520 OS << num_zeros(S.Header.SizeOfRawData - S.SectionData.binary_size());
521 for (const COFFYAML::Relocation &R : S.Relocations) {
522 uint32_t SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];
523 OS << binary_le(R.VirtualAddress)
524 << binary_le(SymbolTableIndex)
525 << binary_le(R.Type);
529 // Output symbol table.
531 for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(),
532 e = CP.Obj.Symbols.end();
533 i != e; ++i) {
534 OS.write(i->Header.Name, COFF::NameSize);
535 OS << binary_le(i->Header.Value);
536 if (CP.useBigObj())
537 OS << binary_le(i->Header.SectionNumber);
538 else
539 OS << binary_le(static_cast<int16_t>(i->Header.SectionNumber));
540 OS << binary_le(i->Header.Type)
541 << binary_le(i->Header.StorageClass)
542 << binary_le(i->Header.NumberOfAuxSymbols);
544 if (i->FunctionDefinition)
545 OS << binary_le(i->FunctionDefinition->TagIndex)
546 << binary_le(i->FunctionDefinition->TotalSize)
547 << binary_le(i->FunctionDefinition->PointerToLinenumber)
548 << binary_le(i->FunctionDefinition->PointerToNextFunction)
549 << zeros(i->FunctionDefinition->unused)
550 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
551 if (i->bfAndefSymbol)
552 OS << zeros(i->bfAndefSymbol->unused1)
553 << binary_le(i->bfAndefSymbol->Linenumber)
554 << zeros(i->bfAndefSymbol->unused2)
555 << binary_le(i->bfAndefSymbol->PointerToNextFunction)
556 << zeros(i->bfAndefSymbol->unused3)
557 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
558 if (i->WeakExternal)
559 OS << binary_le(i->WeakExternal->TagIndex)
560 << binary_le(i->WeakExternal->Characteristics)
561 << zeros(i->WeakExternal->unused)
562 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
563 if (!i->File.empty()) {
564 unsigned SymbolSize = CP.getSymbolSize();
565 uint32_t NumberOfAuxRecords =
566 (i->File.size() + SymbolSize - 1) / SymbolSize;
567 uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize;
568 uint32_t NumZeros = NumberOfAuxBytes - i->File.size();
569 OS.write(i->File.data(), i->File.size());
570 OS << num_zeros(NumZeros);
572 if (i->SectionDefinition)
573 OS << binary_le(i->SectionDefinition->Length)
574 << binary_le(i->SectionDefinition->NumberOfRelocations)
575 << binary_le(i->SectionDefinition->NumberOfLinenumbers)
576 << binary_le(i->SectionDefinition->CheckSum)
577 << binary_le(static_cast<int16_t>(i->SectionDefinition->Number))
578 << binary_le(i->SectionDefinition->Selection)
579 << zeros(i->SectionDefinition->unused)
580 << binary_le(static_cast<int16_t>(i->SectionDefinition->Number >> 16))
581 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
582 if (i->CLRToken)
583 OS << binary_le(i->CLRToken->AuxType)
584 << zeros(i->CLRToken->unused1)
585 << binary_le(i->CLRToken->SymbolTableIndex)
586 << zeros(i->CLRToken->unused2)
587 << num_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
590 // Output string table.
591 if (CP.Obj.Header.PointerToSymbolTable)
592 OS.write(&CP.StringTable[0], CP.StringTable.size());
593 return true;
596 int yaml2coff(llvm::COFFYAML::Object &Doc, raw_ostream &Out) {
597 COFFParser CP(Doc);
598 if (!CP.parse()) {
599 errs() << "yaml2obj: Failed to parse YAML file!\n";
600 return 1;
603 if (!layoutOptionalHeader(CP)) {
604 errs() << "yaml2obj: Failed to layout optional header for COFF file!\n";
605 return 1;
608 if (!layoutCOFF(CP)) {
609 errs() << "yaml2obj: Failed to layout COFF file!\n";
610 return 1;
612 if (!writeCOFF(CP, Out)) {
613 errs() << "yaml2obj: Failed to write COFF file!\n";
614 return 1;
616 return 0;