LLVM 20.0.0git
COFFEmitter.cpp
Go to the documentation of this file.
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"
16#include "llvm/ADT/StringMap.h"
22#include "llvm/Support/Endian.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(4, char(0));
42 }
43
44 bool useBigObj() const {
45 return static_cast<int32_t>(Obj.Sections.size()) >
47 }
48
49 bool isPE() const { return Obj.OptionalHeader.has_value(); }
50 bool is64Bit() const { return COFF::is64Bit(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(Name);
75 std::string str = utostr(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(Sec.Alignment)) {
90 ErrHandler("section alignment is not a power of 2");
91 return false;
92 }
93 Sec.Header.Characteristics |= (Log2_32(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(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(Str);
129 if (i == StringTableMap.end()) {
130 unsigned Index = StringTable.size();
131 StringTable.append(Str.begin(), Str.end());
132 StringTable.push_back(0);
133 StringTableMap[Str] = Index;
134 return Index;
135 }
136 return i->second;
137 }
138
139 COFFYAML::Object &Obj;
140
141 codeview::StringsAndChecksums StringsAndChecksums;
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
170 const codeview::StringsAndChecksums &SC, BumpPtrAllocator &Allocator) {
171 using namespace codeview;
172 ExitOnError Err("Error occurred writing .debug$S section");
173 auto CVSS =
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(std::move(B));
182 }
183 uint8_t *Buffer = Allocator.Allocate<uint8_t>(Size);
184 MutableArrayRef<uint8_t> Output(Buffer, Size);
186
188 for (const auto &B : Builders) {
189 Err(B.commit(Writer, 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) {
213 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(S.DebugS, CP.StringsAndChecksums, CP.Allocator);
229 }
230 } else if (S.Name == ".debug$T") {
231 if (S.SectionData.binary_size() == 0)
232 S.SectionData = CodeViewYAML::toDebugT(S.DebugT, CP.Allocator, S.Name);
233 } else if (S.Name == ".debug$P") {
234 if (S.SectionData.binary_size() == 0)
235 S.SectionData = CodeViewYAML::toDebugT(S.DebugP, CP.Allocator, S.Name);
236 } else if (S.Name == ".debug$H") {
237 if (S.DebugH && S.SectionData.binary_size() == 0)
238 S.SectionData = CodeViewYAML::toDebugH(*S.DebugH, 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(CurrentSectionDataOffset,
246 CP.isPE() ? CP.getFileAlignment() : 4);
247 S.Header.SizeOfRawData = DataSize;
248 if (CP.isPE())
250 alignTo(S.Header.SizeOfRawData, CP.getFileAlignment());
251 S.Header.PointerToRawData = CurrentSectionDataOffset;
252 CurrentSectionDataOffset += S.Header.SizeOfRawData;
253 if (!S.Relocations.empty()) {
254 S.Header.PointerToRelocations = CurrentSectionDataOffset;
256 S.Header.NumberOfRelocations = 0xffff;
257 CurrentSectionDataOffset += COFF::RelocationSize;
258 } else
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.
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>
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>
326}
327
328template <size_t NumBytes> struct zeros_impl {};
329
330template <size_t 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) {
357 SizeOfCode += S.Header.SizeOfRawData;
359 SizeOfInitializedData += S.Header.SizeOfRawData;
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
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.
401 memset(&DH, 0, 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(reinterpret_cast<char *>(&DH), sizeof(DH));
415 // Write padding until we reach the position of where our PE signature
416 // should live.
417 OS.write_zeros(DOSStubSize - sizeof(DH));
418 // Write out the PE signature.
420 }
421 if (CP.useBigObj()) {
422 OS << binary_le(static_cast<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN))
423 << binary_le(static_cast<uint16_t>(0xffff))
424 << binary_le(
426 << binary_le(CP.Obj.Header.Machine)
427 << binary_le(CP.Obj.Header.TimeDateStamp);
429 OS << zeros(uint32_t(0)) << zeros(uint32_t(0)) << zeros(uint32_t(0))
430 << zeros(uint32_t(0)) << binary_le(CP.Obj.Header.NumberOfSections)
431 << binary_le(CP.Obj.Header.PointerToSymbolTable)
432 << binary_le(CP.Obj.Header.NumberOfSymbols);
433 } else {
434 OS << binary_le(CP.Obj.Header.Machine)
435 << binary_le(static_cast<int16_t>(CP.Obj.Header.NumberOfSections))
436 << binary_le(CP.Obj.Header.TimeDateStamp)
437 << binary_le(CP.Obj.Header.PointerToSymbolTable)
438 << binary_le(CP.Obj.Header.NumberOfSymbols)
439 << binary_le(CP.Obj.Header.SizeOfOptionalHeader)
440 << binary_le(CP.Obj.Header.Characteristics);
441 }
442 if (CP.isPE()) {
443 if (CP.is64Bit()) {
446 OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));
447 } else {
449 uint32_t BaseOfData =
451 PEH.BaseOfData = BaseOfData;
452 OS.write(reinterpret_cast<char *>(&PEH), 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(DataDirectories[I]->RelativeVirtualAddress);
464 OS << binary_le(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) {
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;
498 for (auto E : S.StructuredData)
499 E.writeAsBinary(OS);
503 OS.tell());
505 OS << binary_le<uint32_t>(/*VirtualAddress=*/ S.Relocations.size() + 1)
506 << binary_le<uint32_t>(/*SymbolTableIndex=*/ 0)
507 << binary_le<uint16_t>(/*Type=*/ 0);
508 for (const COFFYAML::Relocation &R : S.Relocations) {
509 uint32_t SymbolTableIndex;
510 if (R.SymbolTableIndex) {
511 if (!R.SymbolName.empty())
513 << "Both SymbolName and SymbolTableIndex specified\n";
514 SymbolTableIndex = *R.SymbolTableIndex;
515 } else {
516 SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];
517 }
518 OS << binary_le(R.VirtualAddress) << binary_le(SymbolTableIndex)
519 << binary_le(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(i->Header.Name, COFF::NameSize);
529 OS << binary_le(i->Header.Value);
530 if (CP.useBigObj())
531 OS << binary_le(i->Header.SectionNumber);
532 else
533 OS << binary_le(static_cast<int16_t>(i->Header.SectionNumber));
534 OS << binary_le(i->Header.Type) << binary_le(i->Header.StorageClass)
535 << binary_le(i->Header.NumberOfAuxSymbols);
536
537 if (i->FunctionDefinition) {
538 OS << binary_le(i->FunctionDefinition->TagIndex)
539 << binary_le(i->FunctionDefinition->TotalSize)
540 << binary_le(i->FunctionDefinition->PointerToLinenumber)
541 << binary_le(i->FunctionDefinition->PointerToNextFunction)
542 << zeros(i->FunctionDefinition->unused);
543 OS.write_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
544 }
545 if (i->bfAndefSymbol) {
546 OS << zeros(i->bfAndefSymbol->unused1)
547 << binary_le(i->bfAndefSymbol->Linenumber)
548 << zeros(i->bfAndefSymbol->unused2)
549 << binary_le(i->bfAndefSymbol->PointerToNextFunction)
550 << zeros(i->bfAndefSymbol->unused3);
551 OS.write_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
552 }
553 if (i->WeakExternal) {
554 OS << binary_le(i->WeakExternal->TagIndex)
555 << binary_le(i->WeakExternal->Characteristics)
556 << zeros(i->WeakExternal->unused);
557 OS.write_zeros(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(i->File.data(), i->File.size());
566 OS.write_zeros(NumZeros);
567 }
568 if (i->SectionDefinition) {
569 OS << binary_le(i->SectionDefinition->Length)
570 << binary_le(i->SectionDefinition->NumberOfRelocations)
571 << binary_le(i->SectionDefinition->NumberOfLinenumbers)
572 << binary_le(i->SectionDefinition->CheckSum)
573 << binary_le(static_cast<int16_t>(i->SectionDefinition->Number))
574 << binary_le(i->SectionDefinition->Selection)
575 << zeros(i->SectionDefinition->unused)
576 << binary_le(static_cast<int16_t>(i->SectionDefinition->Number >> 16));
577 OS.write_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
578 }
579 if (i->CLRToken) {
580 OS << binary_le(i->CLRToken->AuxType) << zeros(i->CLRToken->unused1)
581 << binary_le(i->CLRToken->SymbolTableIndex)
582 << zeros(i->CLRToken->unused2);
583 OS.write_zeros(CP.getSymbolSize() - COFF::Symbol16Size);
584 }
585 }
586
587 // Output string table.
588 if (CP.Obj.Header.PointerToSymbolTable)
589 OS.write(&CP.StringTable[0], CP.StringTable.size());
590 return true;
591}
592
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(reinterpret_cast<const char *>(&S),
606 std::min(sizeof(S), static_cast<size_t>(S.Size)));
607 if (sizeof(S) < S.Size)
608 OS.write_zeros(S.Size - sizeof(S));
609}
610
612 if (UInt32)
613 OS << binary_le(*UInt32);
614 Binary.writeAsBinary(OS);
615 if (LoadConfig32)
616 writeLoadConfig(*LoadConfig32, OS);
617 if (LoadConfig64)
618 writeLoadConfig(*LoadConfig64, OS);
619}
620
621namespace llvm {
622namespace yaml {
623
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, Out)) {
642 ErrHandler("failed to write COFF file");
643 return false;
644 }
645 return true;
646}
647
648} // namespace yaml
649} // namespace llvm
This file defines the StringMap class.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool layoutCOFF(COFFParser &CP)
binary_le_impl< value_type > binary_le(value_type V)
static void writeLoadConfig(T &S, raw_ostream &OS)
static yaml::BinaryRef toDebugS(ArrayRef< CodeViewYAML::YAMLDebugSubsection > Subsections, const codeview::StringsAndChecksums &SC, BumpPtrAllocator &Allocator)
zeros_impl< sizeof(T)> zeros(const T &)
static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic, T Header)
raw_ostream & operator<<(raw_ostream &OS, const binary_le_impl< value_type > &BLE)
static bool writeCOFF(COFFParser &CP, raw_ostream &OS)
static bool layoutOptionalHeader(COFFParser &CP)
std::string Name
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:479
static size_t getStringIndex(StringRef Name)
Definition: LVElement.cpp:78
#define I(x, y, z)
Definition: MD5.cpp:58
Basic Register Allocator
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file contains some functions that are useful when dealing with strings.
static bool is64Bit(const char *name)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
Provides write only access to a subclass of WritableBinaryStream.
Error writeInteger(T Value)
Write the integer Value to the underlying stream in the specified endianness.
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
Helper for check-and-exit error handling.
Definition: Error.h:1408
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:307
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
LLVM Value Representation.
Definition: Value.h:74
static raw_ostream & error()
Convenience method for printing "error: " to stderr.
Definition: WithColor.cpp:83
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:147
raw_ostream & write(unsigned char C)
Specialized YAMLIO scalar type for representing a binary blob.
Definition: YAML.h:63
ArrayRef< uint8_t >::size_type binary_size() const
The number of bytes that are represented by this BinaryRef.
Definition: YAML.h:80
void writeAsBinary(raw_ostream &OS, uint64_t N=UINT64_MAX) const
Write the contents (regardless of whether it is binary or a hex string) as binary to the given raw_os...
Definition: YAML.cpp:39
@ IMAGE_FILE_MACHINE_UNKNOWN
Definition: COFF.h:95
@ IMAGE_SCN_CNT_CODE
Definition: COFF.h:302
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition: COFF.h:304
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition: COFF.h:303
@ IMAGE_SCN_LNK_NRELOC_OVFL
Definition: COFF.h:329
@ NameSize
Definition: COFF.h:57
@ Header16Size
Definition: COFF.h:55
@ Symbol16Size
Definition: COFF.h:58
@ Header32Size
Definition: COFF.h:56
@ SectionSize
Definition: COFF.h:60
@ Symbol32Size
Definition: COFF.h:59
@ RelocationSize
Definition: COFF.h:61
@ DEBUG_SECTION_MAGIC
Definition: COFF.h:803
bool is64Bit(T Machine)
Definition: COFF.h:133
const int32_t MaxNumberOfSections16
Definition: COFF.h:32
static const char BigObjMagic[]
Definition: COFF.h:37
static const char PEMagic[]
Definition: COFF.h:35
@ SCT_COMPLEX_TYPE_SHIFT
Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
Definition: COFF.h:279
void initializeStringsAndChecksums(ArrayRef< YAMLDebugSubsection > Sections, codeview::StringsAndChecksums &SC)
Expected< std::vector< std::shared_ptr< codeview::DebugSubsection > > > toCodeViewSubsectionList(BumpPtrAllocator &Allocator, ArrayRef< YAMLDebugSubsection > Subsections, const codeview::StringsAndChecksums &SC)
ArrayRef< uint8_t > toDebugH(const DebugHSection &DebugH, BumpPtrAllocator &Alloc)
ArrayRef< uint8_t > toDebugT(ArrayRef< LeafRecord >, BumpPtrAllocator &Alloc, StringRef SectionName)
bool yaml2coff(COFFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH)
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:340
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:291
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
binary_le_impl(value_type V)
value_type Value
std::optional< PEHeader > OptionalHeader
Definition: COFFYAML.h:117
std::vector< Section > Sections
Definition: COFFYAML.h:119
std::vector< Symbol > Symbols
Definition: COFFYAML.h:120
COFF::header Header
Definition: COFFYAML.h:118
std::optional< object::coff_load_configuration64 > LoadConfig64
Definition: COFFYAML.h:74
std::optional< object::coff_load_configuration32 > LoadConfig32
Definition: COFFYAML.h:73
void writeAsBinary(raw_ostream &OS) const
std::optional< uint32_t > UInt32
Definition: COFFYAML.h:71
std::vector< CodeViewYAML::YAMLDebugSubsection > DebugS
Definition: COFFYAML.h:84
std::vector< SectionDataEntry > StructuredData
Definition: COFFYAML.h:88
std::vector< CodeViewYAML::LeafRecord > DebugT
Definition: COFFYAML.h:85
yaml::BinaryRef SectionData
Definition: COFFYAML.h:83
std::optional< CodeViewYAML::DebugHSection > DebugH
Definition: COFFYAML.h:87
std::vector< CodeViewYAML::LeafRecord > DebugP
Definition: COFFYAML.h:86
COFF::section Header
Definition: COFFYAML.h:81
std::vector< Relocation > Relocations
Definition: COFFYAML.h:89
uint16_t Machine
Definition: COFF.h:65
uint32_t VirtualSize
Definition: COFF.h:286
uint32_t PointerToRelocations
Definition: COFF.h:290
uint16_t NumberOfLineNumbers
Definition: COFF.h:293
uint32_t PointerToRawData
Definition: COFF.h:289
uint32_t SizeOfRawData
Definition: COFF.h:288
uint32_t Characteristics
Definition: COFF.h:294
uint16_t NumberOfRelocations
Definition: COFF.h:292
char Name[NameSize]
Definition: COFF.h:285
uint32_t VirtualAddress
Definition: COFF.h:287
uint32_t PointerToLineNumbers
Definition: COFF.h:291
The DOS compatible header at the front of all PE/COFF executables.
Definition: COFF.h:57
support::ulittle16_t AddressOfRelocationTable
Definition: COFF.h:70
support::ulittle32_t AddressOfNewExeHeader
Definition: COFF.h:76
The 32-bit PE header that follows the COFF header.
Definition: COFF.h:108
support::ulittle32_t BaseOfData
Definition: COFF.h:117
The 64-bit PE header that follows the COFF header.
Definition: COFF.h:144
Definition: regcomp.c:192
Common declarations for yaml2obj.