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), SectionTableStart(0), SectionTableSize(0), 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 getHeaderSize() const {
58 return useBigObj() ? COFF::Header32Size : COFF::Header16Size;
59 }
60
61 unsigned getSymbolSize() const {
62 return useBigObj() ? COFF::Symbol32Size : COFF::Symbol16Size;
63 }
64
65 bool parseSections() {
66 for (COFFYAML::Section &Sec : Obj.Sections) {
67 // If the name is less than 8 bytes, store it in place, otherwise
68 // store it in the string table.
69 StringRef Name = Sec.Name;
70
71 if (Name.size() <= COFF::NameSize) {
72 llvm::copy(Name, Sec.Header.Name);
73 } else {
74 // Add string to the string table and format the index for output.
75 unsigned Index = getStringIndex(Name);
76 std::string str = utostr(Index);
77 if (str.size() > 7) {
78 ErrHandler("string table got too large");
79 return false;
80 }
81 Sec.Header.Name[0] = '/';
82 llvm::copy(str, Sec.Header.Name + 1);
83 }
84
85 if (Sec.Alignment) {
86 if (Sec.Alignment > 8192) {
87 ErrHandler("section alignment is too large");
88 return false;
89 }
90 if (!isPowerOf2_32(Sec.Alignment)) {
91 ErrHandler("section alignment is not a power of 2");
92 return false;
93 }
94 Sec.Header.Characteristics |= (Log2_32(Sec.Alignment) + 1) << 20;
95 }
96 }
97 return true;
98 }
99
100 bool parseSymbols() {
101 for (COFFYAML::Symbol &Sym : Obj.Symbols) {
102 // If the name is less than 8 bytes, store it in place, otherwise
103 // store it in the string table.
104 StringRef Name = Sym.Name;
105 if (Name.size() <= COFF::NameSize) {
106 llvm::copy(Name, Sym.Header.Name);
107 } else {
108 // Add string to the string table and format the index for output.
109 unsigned Index = getStringIndex(Name);
110 *reinterpret_cast<support::aligned_ulittle32_t *>(Sym.Header.Name + 4) =
111 Index;
112 }
113
114 Sym.Header.Type = Sym.SimpleType;
116 }
117 return true;
118 }
119
120 bool parse() {
121 if (!parseSections())
122 return false;
123 if (!parseSymbols())
124 return false;
125 return true;
126 }
127
128 unsigned getStringIndex(StringRef Str) {
129 auto [It, Inserted] = StringTableMap.try_emplace(Str, StringTable.size());
130 if (Inserted) {
131 StringTable.append(Str.begin(), Str.end());
132 StringTable.push_back(0);
133 }
134 return It->second;
135 }
136
137 COFFYAML::Object &Obj;
138
139 codeview::StringsAndChecksums StringsAndChecksums;
140 BumpPtrAllocator Allocator;
141 StringMap<unsigned> StringTableMap;
142 std::string StringTable;
143 uint32_t SectionTableStart;
144 uint32_t SectionTableSize;
145
146 yaml::ErrorHandler ErrHandler;
147};
148
149enum { DOSStubSize = 128 };
150
151} // end anonymous namespace
152
153// Take a CP and assign addresses and sizes to everything. Returns false if the
154// layout is not valid to do.
155static bool layoutOptionalHeader(COFFParser &CP) {
156 if (!CP.isPE())
157 return true;
158 unsigned PEHeaderSize = CP.is64Bit() ? sizeof(object::pe32plus_header)
159 : sizeof(object::pe32_header);
161 PEHeaderSize + sizeof(object::data_directory) *
162 CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
163 return true;
164}
165
166static yaml::BinaryRef
169 using namespace codeview;
170 ExitOnError Err("Error occurred writing .debug$S section");
171 auto CVSS =
173
174 std::vector<DebugSubsectionRecordBuilder> Builders;
175 uint32_t Size = sizeof(uint32_t);
176 for (auto &SS : CVSS) {
177 DebugSubsectionRecordBuilder B(SS);
178 Size += B.calculateSerializedLength();
179 Builders.push_back(std::move(B));
180 }
181 uint8_t *Buffer = Allocator.Allocate<uint8_t>(Size);
182 MutableArrayRef<uint8_t> Output(Buffer, Size);
184
186 for (const auto &B : Builders) {
187 Err(B.commit(Writer, CodeViewContainer::ObjectFile));
188 }
189 return {Output};
190}
191
192// Take a CP and assign addresses and sizes to everything. Returns false if the
193// layout is not valid to do.
194static bool layoutCOFF(COFFParser &CP) {
195 // The section table starts immediately after the header, including the
196 // optional header.
197 CP.SectionTableStart =
198 CP.getHeaderSize() + CP.Obj.Header.SizeOfOptionalHeader;
199 if (CP.isPE())
200 CP.SectionTableStart += DOSStubSize + sizeof(COFF::PEMagic);
201 CP.SectionTableSize = COFF::SectionSize * CP.Obj.Sections.size();
202
203 uint32_t CurrentSectionDataOffset =
204 CP.SectionTableStart + CP.SectionTableSize;
205
206 for (COFFYAML::Section &S : CP.Obj.Sections) {
207 // We support specifying exactly one of SectionData or Subsections. So if
208 // there is already some SectionData, then we don't need to do any of this.
209 if (S.Name == ".debug$S" && S.SectionData.binary_size() == 0) {
211 CP.StringsAndChecksums);
212 if (CP.StringsAndChecksums.hasChecksums() &&
213 CP.StringsAndChecksums.hasStrings())
214 break;
215 }
216 }
217
218 // Assign each section data address consecutively.
219 for (COFFYAML::Section &S : CP.Obj.Sections) {
220 if (S.Name == ".debug$S") {
221 if (S.SectionData.binary_size() == 0) {
222 assert(CP.StringsAndChecksums.hasStrings() &&
223 "Object file does not have debug string table!");
224
225 S.SectionData =
226 toDebugS(S.DebugS, CP.StringsAndChecksums, CP.Allocator);
227 }
228 } else if (S.Name == ".debug$T") {
229 if (S.SectionData.binary_size() == 0)
230 S.SectionData = CodeViewYAML::toDebugT(S.DebugT, CP.Allocator, S.Name);
231 } else if (S.Name == ".debug$P") {
232 if (S.SectionData.binary_size() == 0)
233 S.SectionData = CodeViewYAML::toDebugT(S.DebugP, CP.Allocator, S.Name);
234 } else if (S.Name == ".debug$H") {
235 if (S.DebugH && S.SectionData.binary_size() == 0)
236 S.SectionData = CodeViewYAML::toDebugH(*S.DebugH, CP.Allocator);
237 }
238
239 size_t DataSize = S.SectionData.binary_size();
240 for (auto E : S.StructuredData)
241 DataSize += E.size();
242 if (DataSize > 0) {
243 CurrentSectionDataOffset = alignTo(CurrentSectionDataOffset,
244 CP.isPE() ? CP.getFileAlignment() : 4);
245 S.Header.SizeOfRawData = DataSize;
246 if (CP.isPE())
248 alignTo(S.Header.SizeOfRawData, CP.getFileAlignment());
249 S.Header.PointerToRawData = CurrentSectionDataOffset;
250 CurrentSectionDataOffset += S.Header.SizeOfRawData;
251 if (!S.Relocations.empty()) {
252 S.Header.PointerToRelocations = CurrentSectionDataOffset;
254 S.Header.NumberOfRelocations = 0xffff;
255 CurrentSectionDataOffset += COFF::RelocationSize;
256 } else
258 CurrentSectionDataOffset += S.Relocations.size() * COFF::RelocationSize;
259 }
260 } else {
261 // Leave SizeOfRawData unaltered. For .bss sections in object files, it
262 // carries the section size.
264 }
265 }
266
267 uint32_t SymbolTableStart = CurrentSectionDataOffset;
268
269 // Calculate number of symbols.
270 uint32_t NumberOfSymbols = 0;
271 for (std::vector<COFFYAML::Symbol>::iterator i = CP.Obj.Symbols.begin(),
272 e = CP.Obj.Symbols.end();
273 i != e; ++i) {
274 uint32_t NumberOfAuxSymbols = 0;
275 if (i->FunctionDefinition)
276 NumberOfAuxSymbols += 1;
277 if (i->bfAndefSymbol)
278 NumberOfAuxSymbols += 1;
279 if (i->WeakExternal)
280 NumberOfAuxSymbols += 1;
281 if (!i->File.empty())
282 NumberOfAuxSymbols +=
283 (i->File.size() + CP.getSymbolSize() - 1) / CP.getSymbolSize();
284 if (i->SectionDefinition)
285 NumberOfAuxSymbols += 1;
286 if (i->CLRToken)
287 NumberOfAuxSymbols += 1;
288 i->Header.NumberOfAuxSymbols = NumberOfAuxSymbols;
289 NumberOfSymbols += 1 + NumberOfAuxSymbols;
290 }
291
292 // Store all the allocated start addresses in the header.
293 CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size();
294 CP.Obj.Header.NumberOfSymbols = NumberOfSymbols;
295 if (NumberOfSymbols > 0 || CP.StringTable.size() > 4)
296 CP.Obj.Header.PointerToSymbolTable = SymbolTableStart;
297 else
298 CP.Obj.Header.PointerToSymbolTable = 0;
299
300 *reinterpret_cast<support::ulittle32_t *>(CP.StringTable.data()) =
301 CP.StringTable.size();
302
303 return true;
304}
305
306template <typename T>
307static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic,
308 T Header) {
309 memset(Header, 0, sizeof(*Header));
310 Header->Magic = Magic;
311 Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment;
312 Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment;
313 uint32_t SizeOfCode = 0, SizeOfInitializedData = 0,
314 SizeOfUninitializedData = 0;
315 uint32_t SizeOfHeaders = alignTo(CP.SectionTableStart + CP.SectionTableSize,
316 Header->FileAlignment);
317 uint32_t SizeOfImage = alignTo(SizeOfHeaders, Header->SectionAlignment);
318 uint32_t BaseOfData = 0;
319 for (const COFFYAML::Section &S : CP.Obj.Sections) {
321 SizeOfCode += S.Header.SizeOfRawData;
323 SizeOfInitializedData += S.Header.SizeOfRawData;
325 SizeOfUninitializedData += S.Header.SizeOfRawData;
326 if (S.Name == ".text")
327 Header->BaseOfCode = S.Header.VirtualAddress; // RVA
328 else if (S.Name == ".data")
329 BaseOfData = S.Header.VirtualAddress; // RVA
331 SizeOfImage += alignTo(S.Header.VirtualSize, Header->SectionAlignment);
332 }
333 Header->SizeOfCode = SizeOfCode;
334 Header->SizeOfInitializedData = SizeOfInitializedData;
335 Header->SizeOfUninitializedData = SizeOfUninitializedData;
336 Header->AddressOfEntryPoint =
337 CP.Obj.OptionalHeader->Header.AddressOfEntryPoint; // RVA
338 Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase;
339 Header->MajorOperatingSystemVersion =
340 CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion;
341 Header->MinorOperatingSystemVersion =
342 CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion;
343 Header->MajorImageVersion = CP.Obj.OptionalHeader->Header.MajorImageVersion;
344 Header->MinorImageVersion = CP.Obj.OptionalHeader->Header.MinorImageVersion;
345 Header->MajorSubsystemVersion =
346 CP.Obj.OptionalHeader->Header.MajorSubsystemVersion;
347 Header->MinorSubsystemVersion =
348 CP.Obj.OptionalHeader->Header.MinorSubsystemVersion;
349 Header->SizeOfImage = SizeOfImage;
350 Header->SizeOfHeaders = SizeOfHeaders;
351 Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem;
352 Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics;
353 Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve;
354 Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit;
355 Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve;
356 Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit;
357 Header->NumberOfRvaAndSize = CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
358 return BaseOfData;
359}
360
361static bool writeCOFF(COFFParser &CP, ContiguousBlobAccumulator &CBA) {
362 if (CP.isPE()) {
363 // PE files start with a DOS stub.
365 memset(&DH, 0, sizeof(DH));
366
367 // DOS EXEs start with "MZ" magic.
368 DH.Magic[0] = 'M';
369 DH.Magic[1] = 'Z';
370 // Initializing the AddressOfRelocationTable is strictly optional but
371 // mollifies certain tools which expect it to have a value greater than
372 // 0x40.
373 DH.AddressOfRelocationTable = sizeof(DH);
374 // This is the address of the PE signature.
375 DH.AddressOfNewExeHeader = DOSStubSize;
376
377 // Write out our DOS stub.
378 CBA.write(reinterpret_cast<const char *>(&DH), sizeof(DH));
379 // Write padding until we reach the position of where our PE signature
380 // should live.
381 CBA.writeZeros(DOSStubSize - sizeof(DH));
382 // Write out the PE signature.
383 CBA.write(COFF::PEMagic, sizeof(COFF::PEMagic));
384 }
385 if (CP.useBigObj()) {
387 LittleEndian);
388 CBA.write(static_cast<uint16_t>(0xffff), LittleEndian);
390 LittleEndian);
391 CBA.write(CP.Obj.Header.Machine, LittleEndian);
392 CBA.write(CP.Obj.Header.TimeDateStamp, LittleEndian);
394 CBA.writeZeros(4 * sizeof(uint32_t));
395 CBA.write(CP.Obj.Header.NumberOfSections, LittleEndian);
396 CBA.write(CP.Obj.Header.PointerToSymbolTable, LittleEndian);
397 CBA.write(CP.Obj.Header.NumberOfSymbols, LittleEndian);
398 } else {
399 CBA.write(CP.Obj.Header.Machine, LittleEndian);
400 CBA.write(static_cast<int16_t>(CP.Obj.Header.NumberOfSections),
401 LittleEndian);
402 CBA.write(CP.Obj.Header.TimeDateStamp, LittleEndian);
403 CBA.write(CP.Obj.Header.PointerToSymbolTable, LittleEndian);
404 CBA.write(CP.Obj.Header.NumberOfSymbols, LittleEndian);
405 CBA.write(CP.Obj.Header.SizeOfOptionalHeader, LittleEndian);
406 CBA.write(CP.Obj.Header.Characteristics, LittleEndian);
407 }
408 if (CP.isPE()) {
409 if (CP.is64Bit()) {
412 CBA.write(reinterpret_cast<const char *>(&PEH), sizeof(PEH));
413 } else {
415 uint32_t BaseOfData =
417 PEH.BaseOfData = BaseOfData;
418 CBA.write(reinterpret_cast<const char *>(&PEH), sizeof(PEH));
419 }
420 for (uint32_t I = 0; I < CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;
421 ++I) {
422 const std::optional<COFF::DataDirectory> *DataDirectories =
423 CP.Obj.OptionalHeader->DataDirectories;
424 uint32_t NumDataDir = std::size(CP.Obj.OptionalHeader->DataDirectories);
425 if (I >= NumDataDir || !DataDirectories[I]) {
426 CBA.writeZeros(2 * sizeof(uint32_t));
427 } else {
428 CBA.write(DataDirectories[I]->RelativeVirtualAddress, LittleEndian);
429 CBA.write(DataDirectories[I]->Size, LittleEndian);
430 }
431 }
432 }
433
434 assert(CBA.getOffset() == CP.SectionTableStart);
435 // Output section table.
436 for (const COFFYAML::Section &S : CP.Obj.Sections) {
438 CBA.write(S.Header.VirtualSize, LittleEndian);
439 CBA.write(S.Header.VirtualAddress, LittleEndian);
440 CBA.write(S.Header.SizeOfRawData, LittleEndian);
441 CBA.write(S.Header.PointerToRawData, LittleEndian);
442 CBA.write(S.Header.PointerToRelocations, LittleEndian);
443 CBA.write(S.Header.PointerToLineNumbers, LittleEndian);
444 CBA.write(S.Header.NumberOfRelocations, LittleEndian);
445 CBA.write(S.Header.NumberOfLineNumbers, LittleEndian);
446 CBA.write(S.Header.Characteristics, LittleEndian);
447 }
448 assert(CBA.getOffset() == CP.SectionTableStart + CP.SectionTableSize);
449
450 unsigned CurSymbol = 0;
451 StringMap<unsigned> SymbolTableIndexMap;
452 for (const COFFYAML::Symbol &Sym : CP.Obj.Symbols) {
453 SymbolTableIndexMap[Sym.Name] = CurSymbol;
454 CurSymbol += 1 + Sym.Header.NumberOfAuxSymbols;
455 }
456
457 // Output section data.
458 for (const COFFYAML::Section &S : CP.Obj.Sections) {
459 if (S.Header.SizeOfRawData == 0 || S.Header.PointerToRawData == 0)
460 continue;
463 for (auto E : S.StructuredData)
464 E.writeAsBinary(CBA);
467 CBA.getOffset());
469 CBA.getOffset());
471 CBA.write<uint32_t>(/*VirtualAddress=*/S.Relocations.size() + 1,
472 LittleEndian);
473 CBA.write<uint32_t>(/*SymbolTableIndex=*/0, LittleEndian);
474 CBA.write<uint16_t>(/*Type=*/0, LittleEndian);
475 }
476 for (const COFFYAML::Relocation &R : S.Relocations) {
477 uint32_t SymbolTableIndex;
478 if (R.SymbolTableIndex) {
479 if (!R.SymbolName.empty())
481 << "Both SymbolName and SymbolTableIndex specified\n";
482 SymbolTableIndex = *R.SymbolTableIndex;
483 } else {
484 SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];
485 }
486 CBA.write(R.VirtualAddress, LittleEndian);
487 CBA.write(SymbolTableIndex, LittleEndian);
488 CBA.write(R.Type, LittleEndian);
489 }
490 }
491
492 // Output symbol table.
493 for (std::vector<COFFYAML::Symbol>::const_iterator i = CP.Obj.Symbols.begin(),
494 e = CP.Obj.Symbols.end();
495 i != e; ++i) {
496 CBA.write(i->Header.Name, COFF::NameSize);
497 CBA.write(i->Header.Value, LittleEndian);
498 if (CP.useBigObj())
499 CBA.write(i->Header.SectionNumber, LittleEndian);
500 else
501 CBA.write(static_cast<int16_t>(i->Header.SectionNumber), LittleEndian);
502 CBA.write(i->Header.Type, LittleEndian);
503 CBA.write(i->Header.StorageClass, LittleEndian);
504 CBA.write(i->Header.NumberOfAuxSymbols, LittleEndian);
505
506 if (i->FunctionDefinition) {
507 CBA.write(i->FunctionDefinition->TagIndex, LittleEndian);
508 CBA.write(i->FunctionDefinition->TotalSize, LittleEndian);
509 CBA.write(i->FunctionDefinition->PointerToLinenumber, LittleEndian);
510 CBA.write(i->FunctionDefinition->PointerToNextFunction, LittleEndian);
511 CBA.writeZeros(sizeof(i->FunctionDefinition->unused));
512 CBA.writeZeros(CP.getSymbolSize() - COFF::Symbol16Size);
513 }
514 if (i->bfAndefSymbol) {
515 CBA.writeZeros(sizeof(i->bfAndefSymbol->unused1));
516 CBA.write(i->bfAndefSymbol->Linenumber, LittleEndian);
517 CBA.writeZeros(sizeof(i->bfAndefSymbol->unused2));
518 CBA.write(i->bfAndefSymbol->PointerToNextFunction, LittleEndian);
519 CBA.writeZeros(sizeof(i->bfAndefSymbol->unused3));
520 CBA.writeZeros(CP.getSymbolSize() - COFF::Symbol16Size);
521 }
522 if (i->WeakExternal) {
523 CBA.write(i->WeakExternal->TagIndex, LittleEndian);
524 CBA.write(i->WeakExternal->Characteristics, LittleEndian);
525 CBA.writeZeros(sizeof(i->WeakExternal->unused));
526 CBA.writeZeros(CP.getSymbolSize() - COFF::Symbol16Size);
527 }
528 if (!i->File.empty()) {
529 unsigned SymbolSize = CP.getSymbolSize();
530 uint32_t NumberOfAuxRecords =
531 (i->File.size() + SymbolSize - 1) / SymbolSize;
532 uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize;
533 uint32_t NumZeros = NumberOfAuxBytes - i->File.size();
534 CBA.write(i->File.data(), i->File.size());
535 CBA.writeZeros(NumZeros);
536 }
537 if (i->SectionDefinition) {
538 CBA.write(i->SectionDefinition->Length, LittleEndian);
539 CBA.write(i->SectionDefinition->NumberOfRelocations, LittleEndian);
540 CBA.write(i->SectionDefinition->NumberOfLinenumbers, LittleEndian);
541 CBA.write(i->SectionDefinition->CheckSum, LittleEndian);
542 CBA.write(static_cast<int16_t>(i->SectionDefinition->Number),
543 LittleEndian);
544 CBA.write(i->SectionDefinition->Selection, LittleEndian);
545 CBA.writeZeros(sizeof(i->SectionDefinition->unused));
546 CBA.write(static_cast<int16_t>(i->SectionDefinition->Number >> 16),
547 LittleEndian);
548 CBA.writeZeros(CP.getSymbolSize() - COFF::Symbol16Size);
549 }
550 if (i->CLRToken) {
551 CBA.write(i->CLRToken->AuxType, LittleEndian);
552 CBA.writeZeros(sizeof(i->CLRToken->unused1));
553 CBA.write(i->CLRToken->SymbolTableIndex, LittleEndian);
554 CBA.writeZeros(sizeof(i->CLRToken->unused2));
555 CBA.writeZeros(CP.getSymbolSize() - COFF::Symbol16Size);
556 }
557 }
558
559 // Output string table.
560 if (CP.Obj.Header.PointerToSymbolTable)
561 CBA.write(CP.StringTable.data(), CP.StringTable.size());
562 return true;
563}
564
566 size_t Size = Binary.binary_size();
567 if (UInt32)
568 Size += sizeof(*UInt32);
569 if (LoadConfig32)
570 Size += LoadConfig32->Size;
571 if (LoadConfig64)
572 Size += LoadConfig64->Size;
573 return Size;
574}
575
576template <typename T>
578 CBA.write(reinterpret_cast<const char *>(&S),
579 std::min(sizeof(S), static_cast<size_t>(S.Size)));
580 if (sizeof(S) < S.Size)
581 CBA.writeZeros(S.Size - sizeof(S));
582}
583
585 ContiguousBlobAccumulator &CBA) const {
586 if (UInt32)
587 CBA.write(*UInt32, LittleEndian);
589 if (LoadConfig32)
591 if (LoadConfig64)
593}
594
595namespace llvm {
596namespace yaml {
597
599 ErrorHandler ErrHandler, uint64_t MaxSize) {
600 COFFParser CP(Doc, ErrHandler);
601 if (!CP.parse()) {
602 ErrHandler("failed to parse YAML file");
603 return false;
604 }
605
606 if (!layoutOptionalHeader(CP)) {
607 ErrHandler("failed to layout optional header for COFF file");
608 return false;
609 }
610
611 if (!layoutCOFF(CP)) {
612 ErrHandler("failed to layout COFF file");
613 return false;
614 }
615
616 // Limit the output size to guard against a runaway YAML description.
617 ContiguousBlobAccumulator CBA(/*BaseOffset=*/0, MaxSize);
618 if (!writeCOFF(CP, CBA)) {
619 ErrHandler("failed to write COFF file");
620 return false;
621 }
622 if (Error E = CBA.takeLimitError()) {
623 // Match ELF by reporting a custom error message instead below.
624 consumeError(std::move(E));
625 ErrHandler("the desired output size is greater than permitted. Use the "
626 "--max-size option to change the limit");
627 return false;
628 }
629
630 CBA.writeBlobToStream(Out);
631 return true;
632}
633
634} // namespace yaml
635} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool layoutCOFF(COFFParser &CP)
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 layoutOptionalHeader(COFFParser &CP)
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
static LLVM_PACKED_END size_t getHeaderSize(uint16_t Version)
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:128
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 void writeAsBinary(const BinaryRef &Bin, uint64_t N=UINT64_MAX)
void write(const char *Ptr, size_t Size)
@ NameSize
Definition COFF.h:58
@ Header16Size
Definition COFF.h:56
@ Symbol16Size
Definition COFF.h:59
@ Header32Size
Definition COFF.h:57
@ SectionSize
Definition COFF.h:61
@ Symbol32Size
Definition COFF.h:60
@ RelocationSize
Definition COFF.h:62
@ 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:290
detail::packed_endian_specific_integral< uint32_t, llvm::endianness::little, aligned > aligned_ulittle32_t
Definition Endian.h:310
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:331
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
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
COFF::SymbolComplexType ComplexType
Definition COFFYAML.h:102
COFF::symbol Header
Definition COFFYAML.h:100
COFF::SymbolBaseType SimpleType
Definition COFFYAML.h:101
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.