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