LLVM 24.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"
21#include "llvm/Support/Endian.h"
25#include <optional>
26#include <vector>
27
28using namespace llvm;
30
31namespace {
32
33constexpr auto LittleEndian = llvm::endianness::little;
34
35/// This parses a yaml stream that represents a COFF object file.
36/// See docs/yaml2obj for the yaml scheema.
37struct COFFParser {
38 COFFParser(COFFYAML::Object &Obj, yaml::ErrorHandler EH)
39 : Obj(Obj), ErrHandler(EH) {
40 // A COFF string table always starts with a 4 byte size field. Offsets into
41 // it include this size, so allocate it now.
42 StringTable.append(4, char(0));
43 }
44
45 bool useBigObj() const {
46 return static_cast<int32_t>(Obj.Sections.size()) >
48 }
49
50 bool isPE() const { return Obj.OptionalHeader.has_value(); }
51 bool is64Bit() const { return COFF::is64Bit(Obj.Header.Machine); }
52
53 uint32_t getFileAlignment() const {
54 return Obj.OptionalHeader->Header.FileAlignment;
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 llvm::copy(Name, 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 llvm::copy(str, 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 llvm::copy(Name, 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;
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;
136 BumpPtrAllocator Allocator;
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
149static yaml::BinaryRef
152 using namespace codeview;
153 ExitOnError Err("Error occurred writing .debug$S section");
154 auto CVSS =
156
157 std::vector<DebugSubsectionRecordBuilder> Builders;
158 uint32_t Size = sizeof(uint32_t);
159 for (auto &SS : CVSS) {
160 DebugSubsectionRecordBuilder B(SS);
161 Size += B.calculateSerializedLength();
162 Builders.push_back(std::move(B));
163 }
164 uint8_t *Buffer = Allocator.Allocate<uint8_t>(Size);
165 MutableArrayRef<uint8_t> Output(Buffer, Size);
167
169 for (const auto &B : Builders) {
170 Err(B.commit(Writer, CodeViewContainer::ObjectFile));
171 }
172 return {Output};
173}
174
175// Write the content of a section and fill in the header fields locating it.
176// Returns whether the section has any content.
177static bool writeSectionContent(COFFParser &CP, COFFYAML::Section &S,
179 if (S.SectionData.binary_size() == 0) {
180 if (S.Name == ".debug$S") {
181 assert(CP.StringsAndChecksums.hasStrings() &&
182 "Object file does not have debug string table!");
183 S.SectionData = toDebugS(S.DebugS, CP.StringsAndChecksums, CP.Allocator);
184 } else if (S.Name == ".debug$T") {
185 S.SectionData = CodeViewYAML::toDebugT(S.DebugT, CP.Allocator, S.Name);
186 } else if (S.Name == ".debug$P") {
187 S.SectionData = CodeViewYAML::toDebugT(S.DebugP, CP.Allocator, S.Name);
188 } else if (S.Name == ".debug$H" && S.DebugH) {
189 S.SectionData = CodeViewYAML::toDebugH(*S.DebugH, CP.Allocator);
190 }
191 }
192
193 bool HasContent = S.SectionData.binary_size() != 0;
194 for (const auto &E : S.StructuredData)
195 HasContent |= E.size() != 0;
196
197 if (!HasContent) {
198 // Leave SizeOfRawData unaltered. For .bss sections in object files, it
199 // carries the section size.
201 return false;
202 }
203
204 CBA.padToAlignment(CP.isPE() ? CP.getFileAlignment() : 4);
206 for (const auto &E : S.StructuredData)
207 E.writeAsBinary(CBA);
209 if (CP.isPE())
210 CBA.padToAlignment(CP.getFileAlignment());
212 return true;
213}
214
215template <typename T>
216static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic,
217 T Header) {
218 memset(Header, 0, sizeof(*Header));
219 Header->Magic = Magic;
220 Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment;
221 Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment;
222 uint32_t SizeOfCode = 0, SizeOfInitializedData = 0,
223 SizeOfUninitializedData = 0;
224 uint32_t SizeOfHeaders = alignTo(CP.SectionTableStart + CP.SectionTableSize,
225 Header->FileAlignment);
226 uint32_t SizeOfImage = alignTo(SizeOfHeaders, Header->SectionAlignment);
227 uint32_t BaseOfData = 0;
228 for (const COFFYAML::Section &S : CP.Obj.Sections) {
230 SizeOfCode += S.Header.SizeOfRawData;
232 SizeOfInitializedData += S.Header.SizeOfRawData;
234 SizeOfUninitializedData += S.Header.SizeOfRawData;
235 if (S.Name == ".text")
236 Header->BaseOfCode = S.Header.VirtualAddress; // RVA
237 else if (S.Name == ".data")
238 BaseOfData = S.Header.VirtualAddress; // RVA
240 SizeOfImage += alignTo(S.Header.VirtualSize, Header->SectionAlignment);
241 }
242 Header->SizeOfCode = SizeOfCode;
243 Header->SizeOfInitializedData = SizeOfInitializedData;
244 Header->SizeOfUninitializedData = SizeOfUninitializedData;
245 Header->AddressOfEntryPoint =
246 CP.Obj.OptionalHeader->Header.AddressOfEntryPoint; // RVA
247 Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase;
248 Header->MajorOperatingSystemVersion =
249 CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion;
250 Header->MinorOperatingSystemVersion =
251 CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion;
252 Header->MajorImageVersion = CP.Obj.OptionalHeader->Header.MajorImageVersion;
253 Header->MinorImageVersion = CP.Obj.OptionalHeader->Header.MinorImageVersion;
254 Header->MajorSubsystemVersion =
255 CP.Obj.OptionalHeader->Header.MajorSubsystemVersion;
256 Header->MinorSubsystemVersion =
257 CP.Obj.OptionalHeader->Header.MinorSubsystemVersion;
258 Header->SizeOfImage = SizeOfImage;
259 Header->SizeOfHeaders = SizeOfHeaders;
260 Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem;
261 Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics;
262 Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve;
263 Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit;
264 Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve;
265 Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit;
266 Header->NumberOfRvaAndSize = CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
267 return BaseOfData;
268}
269
270static bool writeCOFF(COFFParser &CP, ContiguousBlobAccumulator &CBA) {
271 // Calculate number of symbols.
272 CP.Obj.Header.NumberOfSymbols = 0;
273 for (COFFYAML::Symbol &Sym : CP.Obj.Symbols) {
274 uint32_t NumberOfAuxSymbols = 0;
275 if (Sym.FunctionDefinition)
276 NumberOfAuxSymbols += 1;
277 if (Sym.bfAndefSymbol)
278 NumberOfAuxSymbols += 1;
279 if (Sym.WeakExternal)
280 NumberOfAuxSymbols += 1;
281 if (!Sym.File.empty())
282 NumberOfAuxSymbols +=
283 (Sym.File.size() + CP.getSymbolSize() - 1) / CP.getSymbolSize();
284 if (Sym.SectionDefinition)
285 NumberOfAuxSymbols += 1;
286 if (Sym.CLRToken)
287 NumberOfAuxSymbols += 1;
288 Sym.Header.NumberOfAuxSymbols = NumberOfAuxSymbols;
289 CP.Obj.Header.NumberOfSymbols += 1 + NumberOfAuxSymbols;
290 }
291
292 CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size();
293
294 unsigned PEHeaderSize = CP.is64Bit() ? sizeof(object::pe32plus_header)
295 : sizeof(object::pe32_header);
296 if (CP.isPE())
298 PEHeaderSize + sizeof(object::data_directory) *
299 CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
300
301 // Save field offsets for writing back their final values.
302 uint64_t PointerToSymbolTableOffset;
303
304 if (CP.isPE()) {
305 // PE files start with a DOS stub.
307 memset(&DH, 0, sizeof(DH));
308
309 // DOS EXEs start with "MZ" magic.
310 DH.Magic[0] = 'M';
311 DH.Magic[1] = 'Z';
312 // Initializing the AddressOfRelocationTable is strictly optional but
313 // mollifies certain tools which expect it to have a value greater than
314 // 0x40.
315 DH.AddressOfRelocationTable = sizeof(DH);
316 // This is the address of the PE signature.
317 DH.AddressOfNewExeHeader = DOSStubSize;
318
319 // Write out our DOS stub.
320 CBA.write(reinterpret_cast<const char *>(&DH), sizeof(DH));
321 // Write padding until we reach the position of where our PE signature
322 // should live.
323 CBA.writeZeros(DOSStubSize - sizeof(DH));
324 // Write out the PE signature.
325 CBA.write(COFF::PEMagic, sizeof(COFF::PEMagic));
326 }
327 if (CP.useBigObj()) {
329 LittleEndian);
330 CBA.write(static_cast<uint16_t>(0xffff), LittleEndian);
332 LittleEndian);
333 CBA.write(CP.Obj.Header.Machine, LittleEndian);
334 CBA.write(CP.Obj.Header.TimeDateStamp, LittleEndian);
336 CBA.writeZeros(4 * sizeof(uint32_t));
337 CBA.write(CP.Obj.Header.NumberOfSections, LittleEndian);
338 PointerToSymbolTableOffset = CBA.getOffset();
339 // The final symbol table offset is written after the section data.
340 CBA.writeZeros(sizeof(CP.Obj.Header.PointerToSymbolTable));
341 CBA.write(CP.Obj.Header.NumberOfSymbols, LittleEndian);
342 } else {
343 CBA.write(CP.Obj.Header.Machine, LittleEndian);
344 CBA.write(static_cast<int16_t>(CP.Obj.Header.NumberOfSections),
345 LittleEndian);
346 CBA.write(CP.Obj.Header.TimeDateStamp, LittleEndian);
347 PointerToSymbolTableOffset = CBA.getOffset();
348 // The final symbol table offset is written after the section data.
349 CBA.writeZeros(sizeof(CP.Obj.Header.PointerToSymbolTable));
350 CBA.write(CP.Obj.Header.NumberOfSymbols, LittleEndian);
351 CBA.write(CP.Obj.Header.SizeOfOptionalHeader, LittleEndian);
352 CBA.write(CP.Obj.Header.Characteristics, LittleEndian);
353 }
354
355 // The optional header, if present, immediately follows the COFF file header.
356 uint64_t OptionalHeaderOffset = CBA.getOffset();
357 if (CP.isPE()) {
358 // Reserve space for the PE header, whose fields depend on the final section
359 // layout. The data directories that follow it are already final.
360 CBA.writeZeros(PEHeaderSize);
361 for (uint32_t I = 0; I < CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
362 ++I) {
363 const std::optional<COFF::DataDirectory> *DataDirectories =
364 CP.Obj.OptionalHeader->DataDirectories;
365 uint32_t NumDataDir = std::size(CP.Obj.OptionalHeader->DataDirectories);
366 if (I >= NumDataDir || !DataDirectories[I]) {
367 CBA.writeZeros(2 * sizeof(uint32_t));
368 } else {
369 CBA.write(DataDirectories[I]->RelativeVirtualAddress, LittleEndian);
370 CBA.write(DataDirectories[I]->Size, LittleEndian);
371 }
372 }
373 }
374
375 CP.SectionTableStart = CBA.getOffset();
376 CP.SectionTableSize = COFF::SectionSize * CP.Obj.Sections.size();
377 // Reserve space for the section table. Section offsets and sizes are filled
378 // in later.
379 CBA.writeZeros(CP.SectionTableSize);
380
381 unsigned CurSymbol = 0;
382 StringMap<unsigned> SymbolTableIndexMap;
383 for (const COFFYAML::Symbol &Sym : CP.Obj.Symbols) {
384 SymbolTableIndexMap[Sym.Name] = CurSymbol;
385 CurSymbol += 1 + Sym.Header.NumberOfAuxSymbols;
386 }
387
388 // Collect the CodeView strings and checksums shared by all .debug$S sections.
389 for (COFFYAML::Section &S : CP.Obj.Sections) {
390 // We support specifying exactly one of SectionData or Subsections. So if
391 // there is already some SectionData, then we don't need to do any of this.
392 if (S.Name == ".debug$S" && S.SectionData.binary_size() == 0) {
394 CP.StringsAndChecksums);
395 if (CP.StringsAndChecksums.hasChecksums() &&
396 CP.StringsAndChecksums.hasStrings())
397 break;
398 }
399 }
400
401 // Output section data.
402 for (COFFYAML::Section &S : CP.Obj.Sections) {
403 bool HasContent = writeSectionContent(CP, S, CBA);
404 if (!HasContent || S.Relocations.empty())
405 continue;
406
409 S.Header.NumberOfRelocations = 0xffff;
410 CBA.write<uint32_t>(/*VirtualAddress=*/S.Relocations.size() + 1,
411 LittleEndian);
412 CBA.write<uint32_t>(/*SymbolTableIndex=*/0, LittleEndian);
413 CBA.write<uint16_t>(/*Type=*/0, LittleEndian);
414 } else {
416 }
417
418 for (const COFFYAML::Relocation &R : S.Relocations) {
419 uint32_t SymbolTableIndex;
420 if (R.SymbolTableIndex) {
421 if (!R.SymbolName.empty())
423 << "Both SymbolName and SymbolTableIndex specified\n";
424 SymbolTableIndex = *R.SymbolTableIndex;
425 } else {
426 SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];
427 }
428 CBA.write(R.VirtualAddress, LittleEndian);
429 CBA.write(SymbolTableIndex, LittleEndian);
430 CBA.write(R.Type, LittleEndian);
431 }
432 }
433
434 // Fill in the optional header now that the section layout is final.
435 if (CP.isPE()) {
436 if (CP.is64Bit()) {
439 CBA.updateDataAt(OptionalHeaderOffset, &PEH, sizeof(PEH));
440 } else {
442 uint32_t BaseOfData =
444 PEH.BaseOfData = BaseOfData;
445 CBA.updateDataAt(OptionalHeaderOffset, &PEH, sizeof(PEH));
446 }
447 }
448
449 // Fill in the section table.
450 static_assert(sizeof(object::coff_section) == COFF::SectionSize,
451 "unexpected COFF section header size");
452 uint64_t SectionHeaderOffset = CP.SectionTableStart;
453 for (const COFFYAML::Section &S : CP.Obj.Sections) {
454 object::coff_section Header{};
455 memcpy(Header.Name, S.Header.Name, COFF::NameSize);
456 Header.VirtualSize = S.Header.VirtualSize;
457 Header.VirtualAddress = S.Header.VirtualAddress;
458 Header.SizeOfRawData = S.Header.SizeOfRawData;
459 Header.PointerToRawData = S.Header.PointerToRawData;
460 Header.PointerToRelocations = S.Header.PointerToRelocations;
461 Header.PointerToLinenumbers = S.Header.PointerToLineNumbers;
462 Header.NumberOfRelocations = S.Header.NumberOfRelocations;
463 Header.NumberOfLinenumbers = S.Header.NumberOfLineNumbers;
464 Header.Characteristics = S.Header.Characteristics;
465 CBA.updateDataAt(SectionHeaderOffset, &Header, sizeof(Header));
466 SectionHeaderOffset += sizeof(Header);
467 }
468
469 // Output symbol table.
470 if (CP.Obj.Header.NumberOfSymbols || CP.StringTable.size() > 4)
472 else
473 CP.Obj.Header.PointerToSymbolTable = 0;
474
475 CBA.updateDataAt(PointerToSymbolTableOffset,
476 CP.Obj.Header.PointerToSymbolTable, LittleEndian);
477
478 for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(),
479 e = CP.Obj.Symbols.end();
480 i != e; ++i) {
481 CBA.write(i->Header.Name, COFF::NameSize);
482 CBA.write(i->Header.Value, LittleEndian);
483 if (CP.useBigObj())
484 CBA.write(i->Header.SectionNumber, LittleEndian);
485 else
486 CBA.write(static_cast<int16_t>(i->Header.SectionNumber), LittleEndian);
487 CBA.write(i->Header.Type, LittleEndian);
488 CBA.write(i->Header.StorageClass, LittleEndian);
489 CBA.write(i->Header.NumberOfAuxSymbols, LittleEndian);
490
491 if (i->FunctionDefinition) {
492 CBA.write(i->FunctionDefinition->TagIndex, LittleEndian);
493 CBA.write(i->FunctionDefinition->TotalSize, LittleEndian);
494 CBA.write(i->FunctionDefinition->PointerToLinenumber, LittleEndian);
495 CBA.write(i->FunctionDefinition->PointerToNextFunction, LittleEndian);
496 CBA.writeZeros(sizeof(i->FunctionDefinition->unused));
497 CBA.writeZeros(CP.getSymbolSize() - COFF::Symbol16Size);
498 }
499 if (i->bfAndefSymbol) {
500 CBA.writeZeros(sizeof(i->bfAndefSymbol->unused1));
501 CBA.write(i->bfAndefSymbol->Linenumber, LittleEndian);
502 CBA.writeZeros(sizeof(i->bfAndefSymbol->unused2));
503 CBA.write(i->bfAndefSymbol->PointerToNextFunction, LittleEndian);
504 CBA.writeZeros(sizeof(i->bfAndefSymbol->unused3));
505 CBA.writeZeros(CP.getSymbolSize() - COFF::Symbol16Size);
506 }
507 if (i->WeakExternal) {
508 CBA.write(i->WeakExternal->TagIndex, LittleEndian);
509 CBA.write(i->WeakExternal->Characteristics, LittleEndian);
510 CBA.writeZeros(sizeof(i->WeakExternal->unused));
511 CBA.writeZeros(CP.getSymbolSize() - COFF::Symbol16Size);
512 }
513 if (!i->File.empty()) {
514 unsigned SymbolSize = CP.getSymbolSize();
515 uint32_t NumberOfAuxRecords =
516 (i->File.size() + SymbolSize - 1) / SymbolSize;
517 uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize;
518 uint32_t NumZeros = NumberOfAuxBytes - i->File.size();
519 CBA.write(i->File.data(), i->File.size());
520 CBA.writeZeros(NumZeros);
521 }
522 if (i->SectionDefinition) {
523 CBA.write(i->SectionDefinition->Length, LittleEndian);
524 CBA.write(i->SectionDefinition->NumberOfRelocations, LittleEndian);
525 CBA.write(i->SectionDefinition->NumberOfLinenumbers, LittleEndian);
526 CBA.write(i->SectionDefinition->CheckSum, LittleEndian);
527 CBA.write(static_cast<int16_t>(i->SectionDefinition->Number),
528 LittleEndian);
529 CBA.write(i->SectionDefinition->Selection, LittleEndian);
530 CBA.writeZeros(sizeof(i->SectionDefinition->unused));
531 CBA.write(static_cast<int16_t>(i->SectionDefinition->Number >> 16),
532 LittleEndian);
533 CBA.writeZeros(CP.getSymbolSize() - COFF::Symbol16Size);
534 }
535 if (i->CLRToken) {
536 CBA.write(i->CLRToken->AuxType, LittleEndian);
537 CBA.writeZeros(sizeof(i->CLRToken->unused1));
538 CBA.write(i->CLRToken->SymbolTableIndex, LittleEndian);
539 CBA.writeZeros(sizeof(i->CLRToken->unused2));
540 CBA.writeZeros(CP.getSymbolSize() - COFF::Symbol16Size);
541 }
542 }
543
544 // Output string table.
545 if (CP.Obj.Header.PointerToSymbolTable) {
546 *reinterpret_cast<support::ulittle32_t *>(CP.StringTable.data()) =
547 CP.StringTable.size();
548 CBA.write(CP.StringTable.data(), CP.StringTable.size());
549 }
550 return true;
551}
552
554 size_t Size = Binary.binary_size();
555 if (UInt32)
556 Size += sizeof(*UInt32);
557 if (LoadConfig32)
558 Size += LoadConfig32->Size;
559 if (LoadConfig64)
560 Size += LoadConfig64->Size;
561 return Size;
562}
563
564template <typename T>
566 CBA.write(reinterpret_cast<const char *>(&S),
567 std::min(sizeof(S), static_cast<size_t>(S.Size)));
568 if (sizeof(S) < S.Size)
569 CBA.writeZeros(S.Size - sizeof(S));
570}
571
573 ContiguousBlobAccumulator &CBA) const {
574 if (UInt32)
575 CBA.write(*UInt32, LittleEndian);
577 if (LoadConfig32)
579 if (LoadConfig64)
581}
582
583namespace llvm {
584namespace yaml {
585
587 ErrorHandler ErrHandler, uint64_t MaxSize) {
588 COFFParser CP(Doc, ErrHandler);
589 if (!CP.parse()) {
590 ErrHandler("failed to parse YAML file");
591 return false;
592 }
593
594 // Limit the output size to guard against a runaway YAML description.
595 ContiguousBlobAccumulator CBA(/*BaseOffset=*/0, MaxSize);
596 if (!writeCOFF(CP, CBA)) {
597 ErrHandler("failed to write COFF file");
598 return false;
599 }
600 if (Error E = CBA.takeLimitError()) {
601 // Match ELF by reporting a custom error message instead below.
602 consumeError(std::move(E));
603 ErrHandler("the desired output size is greater than permitted. Use the "
604 "--max-size option to change the limit");
605 return false;
606 }
607
608 CBA.writeBlobToStream(Out);
609 return true;
610}
611
612} // namespace yaml
613} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
unsigned uint64_t
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool writeCOFF(COFFParser &CP, ContiguousBlobAccumulator &CBA)
static yaml::BinaryRef toDebugS(ArrayRef< CodeViewYAML::YAMLDebugSubsection > Subsections, const codeview::StringsAndChecksums &SC, BumpPtrAllocator &Allocator)
static void writeLoadConfig(T &S, ContiguousBlobAccumulator &CBA)
static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic, T Header)
static bool writeSectionContent(COFFParser &CP, COFFYAML::Section &S, ContiguousBlobAccumulator &CBA)
This file defines ContiguousBlobAccumulator, the size-limited output buffer shared by the yaml2obj em...
static size_t getStringIndex(StringRef Name)
Definition LVElement.cpp:77
static llvm::Error parse(GsymDataExtractor &Data, uint64_t BaseAddr, LineEntryCallback const &Callback)
Definition LineTable.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
Basic Register Allocator
This file contains some functions that are useful when dealing with strings.
static bool is64Bit(const char *name)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Helper for check-and-exit error handling.
Definition Error.h:1460
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
static LLVM_ABI raw_ostream & error()
Convenience method for printing "error: " to stderr.
Definition WithColor.cpp:84
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Specialized YAMLIO scalar type for representing a binary blob.
Definition YAML.h:64
ArrayRef< uint8_t >::size_type binary_size() const
The number of bytes that are represented by this BinaryRef.
Definition YAML.h:81
LLVM_ABI uint64_t padToAlignment(unsigned Align)
LLVM_ABI void writeAsBinary(const BinaryRef &Bin, uint64_t N=UINT64_MAX)
void write(const char *Ptr, size_t Size)
void updateDataAt(uint64_t Pos, T Val, llvm::endianness E)
@ NameSize
Definition COFF.h:58
@ Symbol16Size
Definition COFF.h:59
@ SectionSize
Definition COFF.h:61
@ Symbol32Size
Definition COFF.h:60
@ IMAGE_FILE_MACHINE_UNKNOWN
Definition COFF.h:96
@ IMAGE_SCN_CNT_CODE
Definition COFF.h:303
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition COFF.h:305
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition COFF.h:304
@ IMAGE_SCN_LNK_NRELOC_OVFL
Definition COFF.h:330
@ DEBUG_SECTION_MAGIC
Definition COFF.h:839
bool is64Bit(T Machine)
Definition COFF.h:134
const int32_t MaxNumberOfSections16
Definition COFF.h:33
static const char BigObjMagic[]
Definition COFF.h:38
static const char PEMagic[]
Definition COFF.h:36
@ SCT_COMPLEX_TYPE_SHIFT
Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
Definition COFF.h:280
LLVM_ABI void initializeStringsAndChecksums(ArrayRef< YAMLDebugSubsection > Sections, codeview::StringsAndChecksums &SC)
LLVM_ABI Expected< std::vector< std::shared_ptr< codeview::DebugSubsection > > > toCodeViewSubsectionList(BumpPtrAllocator &Allocator, ArrayRef< YAMLDebugSubsection > Subsections, const codeview::StringsAndChecksums &SC)
LLVM_ABI ArrayRef< uint8_t > toDebugH(const DebugHSection &DebugH, BumpPtrAllocator &Alloc)
LLVM_ABI ArrayRef< uint8_t > toDebugT(ArrayRef< LeafRecord >, BumpPtrAllocator &Alloc, StringRef SectionName)
detail::packed_endian_specific_integral< uint32_t, llvm::endianness::little, unaligned > ulittle32_t
Definition Endian.h:270
detail::packed_endian_specific_integral< uint32_t, llvm::endianness::little, aligned > aligned_ulittle32_t
Definition Endian.h:290
llvm::function_ref< void(const Twine &Msg)> ErrorHandler
Definition yaml2obj.h:68
LLVM_ABI bool yaml2coff(COFFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH, uint64_t MaxSize)
This is an optimization pass for GlobalISel generic memory operations.
std::string utostr(uint64_t X, bool isNeg=false)
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:326
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1885
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
std::optional< PEHeader > OptionalHeader
Definition COFFYAML.h:121
std::vector< Section > Sections
Definition COFFYAML.h:123
std::vector< Symbol > Symbols
Definition COFFYAML.h:124
COFF::header Header
Definition COFFYAML.h:122
std::optional< object::coff_load_configuration64 > LoadConfig64
Definition COFFYAML.h:78
std::optional< object::coff_load_configuration32 > LoadConfig32
Definition COFFYAML.h:77
LLVM_ABI void writeAsBinary(yaml::ContiguousBlobAccumulator &CBA) const
std::optional< uint32_t > UInt32
Definition COFFYAML.h:75
LLVM_ABI size_t size() const
std::vector< CodeViewYAML::YAMLDebugSubsection > DebugS
Definition COFFYAML.h:88
std::vector< SectionDataEntry > StructuredData
Definition COFFYAML.h:92
std::vector< CodeViewYAML::LeafRecord > DebugT
Definition COFFYAML.h:89
yaml::BinaryRef SectionData
Definition COFFYAML.h:87
std::optional< CodeViewYAML::DebugHSection > DebugH
Definition COFFYAML.h:91
std::vector< CodeViewYAML::LeafRecord > DebugP
Definition COFFYAML.h:90
COFF::section Header
Definition COFFYAML.h:85
std::vector< Relocation > Relocations
Definition COFFYAML.h:93
std::optional< COFF::AuxiliaryWeakExternal > WeakExternal
Definition COFFYAML.h:105
std::optional< COFF::AuxiliarybfAndefSymbol > bfAndefSymbol
Definition COFFYAML.h:104
COFF::SymbolComplexType ComplexType
Definition COFFYAML.h:102
std::optional< COFF::AuxiliarySectionDefinition > SectionDefinition
Definition COFFYAML.h:107
std::optional< COFF::AuxiliaryFunctionDefinition > FunctionDefinition
Definition COFFYAML.h:103
COFF::symbol Header
Definition COFFYAML.h:100
COFF::SymbolBaseType SimpleType
Definition COFFYAML.h:101
std::optional< COFF::AuxiliaryCLRToken > CLRToken
Definition COFFYAML.h:108
uint16_t Machine
Definition COFF.h:66
uint32_t TimeDateStamp
Definition COFF.h:68
uint16_t SizeOfOptionalHeader
Definition COFF.h:71
uint32_t NumberOfSymbols
Definition COFF.h:70
int32_t NumberOfSections
Definition COFF.h:67
uint16_t Characteristics
Definition COFF.h:72
uint32_t PointerToSymbolTable
Definition COFF.h:69
uint32_t VirtualSize
Definition COFF.h:287
uint32_t PointerToRelocations
Definition COFF.h:291
uint16_t NumberOfLineNumbers
Definition COFF.h:294
uint32_t PointerToRawData
Definition COFF.h:290
uint32_t SizeOfRawData
Definition COFF.h:289
uint32_t Characteristics
Definition COFF.h:295
uint16_t NumberOfRelocations
Definition COFF.h:293
char Name[NameSize]
Definition COFF.h:286
uint32_t VirtualAddress
Definition COFF.h:288
uint32_t PointerToLineNumbers
Definition COFF.h:292
uint8_t NumberOfAuxSymbols
Definition COFF.h:208
uint16_t Type
Definition COFF.h:206
char Name[NameSize]
Definition COFF.h:203
The DOS compatible header at the front of all PE/COFF executables.
Definition COFF.h:58
support::ulittle16_t AddressOfRelocationTable
Definition COFF.h:71
support::ulittle32_t AddressOfNewExeHeader
Definition COFF.h:77
The 32-bit PE header that follows the COFF header.
Definition COFF.h:109
support::ulittle32_t BaseOfData
Definition COFF.h:118
The 64-bit PE header that follows the COFF header.
Definition COFF.h:145
Common declarations for yaml2obj.