LLVM 23.0.0git
DXContainer.cpp
Go to the documentation of this file.
1//===- DXContainer.cpp - DXContainer object file implementation -----------===//
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
10#include "llvm/ADT/Sequence.h"
12#include "llvm/Object/Error.h"
14#include "llvm/Support/Endian.h"
17
18using namespace llvm;
19using namespace llvm::object;
20
24
25static bool readIsOutOfBounds(StringRef Buffer, const char *Src, size_t Size) {
26 return !Src || Size > static_cast<size_t>(Buffer.end() - Src);
27}
28
29template <typename T, bool FixEndianness = true>
30static Error readStruct(StringRef Buffer, const char *Src, T &Struct) {
31 // Don't read before the beginning or past the end of the file
32 if (readIsOutOfBounds(Buffer, Src, sizeof(T)))
33 return parseFailed("Reading structure out of file bounds");
34
35 memcpy(&Struct, Src, sizeof(T));
36 // DXContainer is always little endian
37 if constexpr (FixEndianness)
39 Struct.swapBytes();
40 return Error::success();
41}
42
43template <typename T>
44static Error readInteger(StringRef Buffer, const char *Src, T &Val,
45 Twine Str = "structure") {
46 static_assert(std::is_integral_v<T>,
47 "Cannot call readInteger on non-integral type.");
48 // Don't read before the beginning or past the end of the file
49 if (readIsOutOfBounds(Buffer, Src, sizeof(T)))
50 return parseFailed(Twine("Reading ") + Str + " out of file bounds");
51
52 // The DXContainer offset table is comprised of uint32_t values but not padded
53 // to a 64-bit boundary. So Parts may start unaligned if there is an odd
54 // number of parts and part data itself is not required to be padded.
55 if (reinterpret_cast<uintptr_t>(Src) % alignof(T) != 0)
56 memcpy(reinterpret_cast<char *>(&Val), Src, sizeof(T));
57 else
58 Val = *reinterpret_cast<const T *>(Src);
59 // DXContainer is always little endian
62 return Error::success();
63}
64
65/// Read a null-terminated string at the position Src from Buffer, with maximum
66/// byte size of MaxSize (including the null-terminator). Advance Src by the
67/// number of bytes read.
68static Error readString(StringRef Buffer, const char *&Src, size_t MaxSize,
69 StringRef &Val, Twine Desc) {
70 if (readIsOutOfBounds(Buffer, Src, MaxSize))
71 return parseFailed(Desc + " is out of file bounds");
72
73 // Ensure that the null-terminator is somewhere within MaxSize bytes.
74 Buffer = Buffer.substr(Src - Buffer.data(), MaxSize);
75 size_t Length = Buffer.find('\0');
76 if (Length == Buffer.npos)
77 return parseFailed(Desc + " does not end with null-terminator");
78
79 Val = StringRef(Buffer.data(), Length);
80 Src += Length + 1;
81 return Error::success();
82}
83
84DXContainer::DXContainer(MemoryBufferRef O) : Data(O) {}
85
86Error DXContainer::parseHeader() {
87 if (Error Err = readStruct(Data.getBuffer(), Data.getBuffer().data(), Header))
88 return Err;
89 if (StringRef(reinterpret_cast<char *>(Header.Magic), 4) != "DXBC")
90 return parseFailed("Missing DXBC header magic");
91 return Error::success();
92}
93
94Error DXContainer::parseDXILHeader(dxbc::PartType PT, StringRef Part) {
95 bool IsDebug = dxbc::isDebugProgramPart(PT);
96 std::optional<DXILData> &DXIL = IsDebug ? this->DebugDXIL : this->DXIL;
97
98 if (DXIL)
99 return parseFailed(formatv("more than one {0} part is present in the file",
100 dxbc::getProgramPartName(IsDebug)));
101 const char *Current = Part.begin();
102 dxbc::ProgramHeader Header;
103 if (Error Err = readStruct(Part, Current, Header))
104 return Err;
105 Current += offsetof(dxbc::ProgramHeader, Bitcode) + Header.Bitcode.Offset;
106 DXIL.emplace(std::make_pair(Header, Current));
107 return Error::success();
108}
109
110Error DXContainer::parseDebugName(StringRef Part) {
111 if (DebugName)
112 return parseFailed("more than one ILDN part is present in the file");
113 const char *Current = Part.begin();
114 dxbc::DebugNameHeader Header;
115 if (Error Err = readStruct(Part, Current, Header))
116 return Err;
117 Current += sizeof(Header);
118
119 StringRef Name;
120 if (Error Err = readString(Part, Current, Header.NameLength + 1, Name,
121 "debug file name"))
122 return Err;
123 if (Name.size() != Header.NameLength)
124 return parseFailed("debug file name length mismatch");
125 DebugName.emplace(Header, Name.data());
126
127 return Error::success();
128}
129
130Error DXContainer::parseShaderFeatureFlags(StringRef Part) {
131 if (ShaderFeatureFlags)
132 return parseFailed("More than one SFI0 part is present in the file");
133 uint64_t FlagValue = 0;
134 if (Error Err = readInteger(Part, Part.begin(), FlagValue))
135 return Err;
136 ShaderFeatureFlags = FlagValue;
137 return Error::success();
138}
139
140Error DXContainer::parseHash(StringRef Part) {
141 if (Hash)
142 return parseFailed("More than one HASH part is present in the file");
143 dxbc::ShaderHash ReadHash;
144 if (Error Err = readStruct(Part, Part.begin(), ReadHash))
145 return Err;
146 Hash = ReadHash;
147 return Error::success();
148}
149
150Error DXContainer::parseRootSignature(StringRef Part) {
151 if (RootSignature)
152 return parseFailed("More than one RTS0 part is present in the file");
153 RootSignature = DirectX::RootSignature(Part);
154 if (Error Err = RootSignature->parse())
155 return Err;
156 return Error::success();
157}
158
159Error DXContainer::parsePSVInfo(StringRef Part) {
160 if (PSVInfo)
161 return parseFailed("More than one PSV0 part is present in the file");
162 PSVInfo = DirectX::PSVRuntimeInfo(Part);
163 // Parsing the PSVRuntime info occurs late because we need to read data from
164 // other parts first.
165 return Error::success();
166}
167
170 if (Error Err = readStruct(Part, Part.begin(), SigHeader))
171 return Err;
172 size_t Size = sizeof(dxbc::ProgramSignatureElement) * SigHeader.ParamCount;
173
174 if (Part.size() < Size + SigHeader.FirstParamOffset)
175 return parseFailed("Signature parameters extend beyond the part boundary");
176
177 Parameters.Data = Part.substr(SigHeader.FirstParamOffset, Size);
178
179 StringTableOffset = SigHeader.FirstParamOffset + static_cast<uint32_t>(Size);
180 StringTable = Part.substr(SigHeader.FirstParamOffset + Size);
181
182 for (const auto &Param : Parameters) {
183 if (Param.NameOffset < StringTableOffset)
184 return parseFailed("Invalid parameter name offset: name starts before "
185 "the first name offset");
186 if (Param.NameOffset - StringTableOffset > StringTable.size())
187 return parseFailed("Invalid parameter name offset: name starts after the "
188 "end of the part data");
189 }
190 return Error::success();
191}
192
193Error DXContainer::parseCompilerVersionInfo(StringRef Part) {
194 if (VersionInfo)
195 return parseFailed("more than one VERS part is present in the file");
196 const char *Current = Part.begin();
198 if (Error Err = readStruct(Part, Current, Header))
199 return Err;
200 Current += sizeof(Header);
201
203 return parseFailed("Incorrect shader compiler version flags combination");
204
205 StringRef CommitSha;
206 const char *Prev = Current;
207 if (Error Err = readString(Part, Current, Header.ContentSizeInBytes,
208 CommitSha, "CommitSha"))
209 return Err;
210 StringRef CustomVersionString;
211 if (Error Err = readString(Part, Current,
212 Header.ContentSizeInBytes - (Current - Prev),
213 CustomVersionString, "CustomVersionString"))
214 return Err;
215
216 VersionInfo.emplace();
217 VersionInfo->Parameters = Header;
218 VersionInfo->CommitSha = CommitSha;
219 VersionInfo->CustomVersionString = CustomVersionString;
220 return Error::success();
221}
222
225 const char *Current = Section.begin();
226 dxbc::SourceInfo::Names::HeaderOnDisk HeaderOnDisk;
227 if (Error Err = readStruct<decltype(HeaderOnDisk), false>(Section, Current,
228 HeaderOnDisk))
229 return Err;
230 Names.Parameters = HeaderOnDisk;
232 Names.Parameters.swapBytes();
233 Current += sizeof(HeaderOnDisk);
234
235 if (Names.Parameters.Flags)
236 return parseFailed("SRCI Names header flags must be zero");
237 if (Current + Names.Parameters.EntriesSizeInBytes > Section.end())
238 return parseFailed(
239 "SRCI Names section content ends beyond the section boundary");
240
241 Names.Entries.reserve(Names.Parameters.Count);
242 for (size_t I : llvm::seq(Names.Parameters.Count)) {
243 auto &Entry = Names.Entries.emplace_back();
244 if (Error Err = readStruct(Section, Current, Entry.Parameters))
245 return Err;
246
247 const char *Next = Current + Entry.Parameters.AlignedSizeInBytes;
248 if (Next > Section.end())
249 return parseFailed(
250 formatv("SRCI Names entry {0} ends beyond the section boundary", I));
251 if (Entry.Parameters.Flags)
252 return parseFailed(formatv("SRCI Names entry {0} flags must be zero", I));
253
254 const char *FileName = Current + sizeof(Entry.Parameters);
255 if (Error Err = readString(
256 Section, FileName, Entry.Parameters.NameSizeInBytes, Entry.FileName,
257 Twine("SRCI Names entry ") + Twine(I) + Twine(" file name")))
258 return Err;
259 if (FileName > Next)
260 return parseFailed(formatv(
261 "SRCI Names entry {0} file name ends beyond the entry boundary", I));
262 Current = Next;
263 }
264
265 return Current - Section.begin();
266}
267
268static Expected<size_t>
271 const char *Current = Entries.begin();
272
273 Contents.Entries.reserve(Contents.Parameters.Count);
274 for (size_t I : llvm::seq(Contents.Parameters.Count)) {
275 auto &Entry = Contents.Entries.emplace_back();
276 if (Error Err = readStruct(Entries, Current, Entry.Parameters))
277 return Err;
278
279 const char *Next = Current + Entry.Parameters.AlignedSizeInBytes;
280 if (Next > Entries.end())
281 return parseFailed(formatv(
282 "SRCI Contents entry {0} ends beyond the section boundary", I));
283 if (Entry.Parameters.Flags)
284 return parseFailed(
285 formatv("SRCI Contents entry {0} flags must be zero", I));
286
287 const char *FileContentPtr = Current + sizeof(Entry.Parameters);
288 const char *FileContentEndPtr = FileContentPtr;
289 StringRef FileContent;
290 if (Error Err = readString(Entries, FileContentEndPtr,
291 Entry.Parameters.ContentSizeInBytes, FileContent,
292 Twine("SRCI Contents entry ") + Twine(I) +
293 Twine(" file content")))
294 return Err;
295 if (FileContentEndPtr - FileContentPtr !=
296 Entry.Parameters.ContentSizeInBytes)
297 return parseFailed(
298 formatv("file size from header ({0} bytes) does not match content "
299 "size in SRCI Contents entry {1} ({2} bytes)",
300 FileContentEndPtr - FileContentPtr, I,
301 Entry.Parameters.ContentSizeInBytes));
302 if (FileContentEndPtr > Next)
303 return parseFailed(formatv(
304 "SRCI Contents entry {0} file content ends beyond the entry boundary",
305 I));
306
307 Entry.FileContent = std::string(FileContent.data(),
308 Entry.Parameters.ContentSizeInBytes - 1);
309
310 Current = Next;
311 }
312
313 return Current - Entries.begin();
314}
315
316static Expected<size_t>
320
322 to_underlying(Contents.Parameters.Type)))
323 return parseFailed("SRCI Contents section uses unknown compression type");
324
325 SmallVector<uint8_t> UncompressedEntriesData;
326 switch (Contents.Parameters.Type) {
327 case CompressionType::None: {
328 if (Contents.Parameters.EntriesSizeInBytes !=
330 return parseFailed(formatv(
331 "SRCI Contents is not compressed, but compressed size ({0} bytes) "
332 "doesn't match uncompressed size ({1} bytes) in section header",
335
336 return parseUncompressedContentsEntries(Entries, Contents);
337 }
338 case CompressionType::Zlib: {
340 return parseFailed(formatv(
341 "SRCI Contents is compressed with Zlib, but {0}",
344 ArrayRef(reinterpret_cast<const uint8_t *>(Entries.begin()),
346 UncompressedEntriesData,
348 return Err;
349
350 if (UncompressedEntriesData.size() !=
352 return parseFailed("SRCI Contents uncompressed size from header does not "
353 "match with actual content size");
354
356 StringRef(reinterpret_cast<const char *>(
357 UncompressedEntriesData.data()),
358 UncompressedEntriesData.size()),
359 Contents)
360 .takeError())
361 return Err;
362
363 return Contents.Parameters.EntriesSizeInBytes;
364 }
365 }
366}
367
368static Expected<size_t>
370 const char *Current = Section.begin();
371 if (Error Err = readStruct(Section, Current, Contents.Parameters))
372 return Err;
373 size_t BytesRead = sizeof(Contents.Parameters);
374 Current += BytesRead;
375
376 if (Section.begin() + Contents.Parameters.EntriesSizeInBytes > Section.end())
377 return parseFailed(
378 formatv("SRCI Contents section ends beyond the section boundary"));
379 if (Contents.Parameters.Flags)
380 return parseFailed("SRCI Contents header flags must be zero");
381 if (Current + Contents.Parameters.EntriesSizeInBytes > Section.end())
382 return parseFailed(
383 formatv("SRCI Contents entries end beyond the section boundary"));
384
385 size_t BodyBytesRead = 0;
386 if (Error Err = parseContentsEntries(Section.substr(BytesRead), Contents)
387 .moveInto(BodyBytesRead))
388 return Err;
389 return BytesRead + BodyBytesRead;
390}
391
394 const char *Current = Section.begin();
395 if (Error Err = readStruct(Section, Current, Args.Parameters))
396 return Err;
397 Current += sizeof(Args.Parameters);
398
399 if (Args.Parameters.Flags)
400 return parseFailed("SRCI Args header flags must be zero");
401 if (Current + Args.Parameters.SizeInBytes > Section.end())
402 return parseFailed(
403 formatv("SRCI Args entries end beyond the section boundary", Section));
404
405 Args.Args.reserve(Args.Parameters.Count);
406 for (size_t I : llvm::seq(Args.Parameters.Count)) {
407 auto &Entry = Args.Args.emplace_back();
408 if (Error Err =
409 readString(Section, Current, Section.end() - Current, Entry.first,
410 Twine("SRCI Args entry ") + Twine(I) + Twine(" name")))
411 return Err;
412 if (Error Err =
413 readString(Section, Current, Section.end() - Current, Entry.second,
414 Twine("SRCI Args entry ") + Twine(I) + Twine(" value")))
415 return Err;
416 }
417
418 return Current - Section.begin();
419}
420
421static Expected<size_t>
423 StringRef SectionData, mcdxbc::SourceInfo &SourceInfo) {
425 switch (Header.Type) {
426 case SectionType::SourceNames: {
427 SourceInfo.Names.GenericHeader = Header;
428 return parseNames(SectionData, SourceInfo.Names);
429 }
430 case SectionType::SourceContents: {
431 SourceInfo.Contents.GenericHeader = Header;
432 return parseContents(SectionData, SourceInfo.Contents);
433 }
434 case SectionType::Args: {
435 SourceInfo.Args.GenericHeader = Header;
436 return parseArgs(SectionData, SourceInfo.Args);
437 }
438 }
439
440 llvm_unreachable("Unknown source info section type");
441}
442
443Error DXContainer::parseSourceInfo(StringRef Part) {
445
446 if (SourceInfo)
447 return parseFailed("more than one SRCI part is present in the file");
448 SourceInfo.emplace();
449
450 const char *Current = Part.begin();
451 if (Error Err = readStruct(Part, Current, SourceInfo->Parameters))
452 return Err;
453 Current += sizeof(SourceInfo->Parameters);
454
455 if (SourceInfo->Parameters.AlignedSizeInBytes != Part.size())
456 return parseFailed(formatv("size field in SRCI header ({0} bytes) does not "
457 "match SRCI part size ({1} bytes)",
458 SourceInfo->Parameters.AlignedSizeInBytes,
459 Part.size()));
460 if (SourceInfo->Parameters.Flags)
461 return parseFailed("SRCI header flags must be zero");
462 if (SourceInfo->Parameters.SectionCount != 3)
463 return parseFailed("SRCI part must contain 3 sections");
464
465 bool IsSectionPresent[to_underlying(
466 SectionType::LLVM_BITMASK_LARGEST_ENUMERATOR) +
467 1];
468 std::fill(IsSectionPresent,
469 IsSectionPresent +
470 sizeof(IsSectionPresent) / sizeof(*IsSectionPresent),
471 false);
472 for (uint32_t Section = 0; Section < SourceInfo->Parameters.SectionCount;
473 ++Section) {
474 dxbc::SourceInfo::SectionHeader SectionHeader;
475 if (Error Err = readStruct(Part, Current, SectionHeader))
476 return Err;
477 size_t BytesRead = sizeof(SectionHeader);
478
479 StringRef SectionName =
481 if (Current + SectionHeader.AlignedSizeInBytes > Part.end())
482 return parseFailed(
483 formatv("SRCI section {0} (#{1}) extends beyond the part boundary",
484 SectionName, Section));
485 if (SectionHeader.Flags)
486 return parseFailed(
487 formatv("SRCI section {0} (#{1}) header flags must be zero",
488 SectionName, Section));
489
490 size_t SectionTypeIdx = to_underlying(SectionHeader.Type);
491 if (!dxbc::SourceInfo::isValidSectionType(SectionTypeIdx))
492 return parseFailed(
493 formatv("unknown SRCI section type {0}", SectionTypeIdx));
494 if (IsSectionPresent[SectionTypeIdx])
495 return parseFailed(formatv(
496 "more than one {0} section is present in SRCI part", SectionName));
497 IsSectionPresent[SectionTypeIdx] = true;
498
499 size_t SectionBytesRead = 0;
501 SectionHeader,
502 Part.substr(Current + BytesRead - Part.begin(),
503 SectionHeader.AlignedSizeInBytes),
504 *SourceInfo)
505 .moveInto(SectionBytesRead))
506 return Err;
507 BytesRead += SectionBytesRead;
508 BytesRead = alignTo<dxbc::DXCONTAINER_STRUCT_ALIGNMENT>(BytesRead);
509
510 if (BytesRead != SectionHeader.AlignedSizeInBytes)
511 return parseFailed(formatv(
512 "size of SRCI section {0} (#{1} - {2} bytes) does not match size "
513 "specified in generic header ({3} bytes)",
514 SectionName, Section, BytesRead, SectionHeader.AlignedSizeInBytes));
515 Current += SectionHeader.AlignedSizeInBytes;
516 }
517
518 if (SourceInfo->Contents.Parameters.Count !=
519 SourceInfo->Names.Parameters.Count)
520 return parseFailed(
521 "SRCI Contents entries count is not equal to SRCI Names entries count");
522
523 for (size_t I : llvm::seq(SourceInfo->Contents.Parameters.Count))
524 if (SourceInfo->Contents.Entries[I].Parameters.ContentSizeInBytes !=
525 SourceInfo->Names.Entries[I].Parameters.ContentSizeInBytes)
526 return parseFailed(formatv(
527 "content size for entry {0} ({1} bytes) in SRCI Contents section "
528 "does not match with size in SRCI Names section ({2} bytes)",
529 I, SourceInfo->Contents.Entries[I].Parameters.ContentSizeInBytes,
530 SourceInfo->Names.Entries[I].Parameters.ContentSizeInBytes));
531
532 return Error::success();
533}
534
535Error DXContainer::parsePartOffsets() {
536 uint32_t LastOffset =
537 sizeof(dxbc::Header) + (Header.PartCount * sizeof(uint32_t));
538 const char *Current = Data.getBuffer().data() + sizeof(dxbc::Header);
539 for (uint32_t Part = 0; Part < Header.PartCount; ++Part) {
540 uint32_t PartOffset;
541 if (Error Err = readInteger(Data.getBuffer(), Current, PartOffset))
542 return Err;
543 if (PartOffset < LastOffset)
544 return parseFailed(
545 formatv(
546 "Part offset for part {0} begins before the previous part ends",
547 Part)
548 .str());
549 Current += sizeof(uint32_t);
550 if (PartOffset >= Data.getBufferSize())
551 return parseFailed("Part offset points beyond boundary of the file");
552 // To prevent overflow when reading the part name, we subtract the part name
553 // size from the buffer size, rather than adding to the offset. Since the
554 // file header is larger than the part header we can't reach this code
555 // unless the buffer is at least as large as a part header, so this
556 // subtraction can't underflow.
557 if (PartOffset >= Data.getBufferSize() - sizeof(dxbc::PartHeader::Name))
558 return parseFailed("File not large enough to read part name");
559 PartOffsets.push_back(PartOffset);
560
561 dxbc::PartType PT =
562 dxbc::parsePartType(Data.getBuffer().substr(PartOffset, 4));
563 uint32_t PartDataStart = PartOffset + sizeof(dxbc::PartHeader);
564 uint32_t PartSize;
565 if (Error Err = readInteger(Data.getBuffer(),
566 Data.getBufferStart() + PartOffset + 4,
567 PartSize, "part size"))
568 return Err;
569 StringRef PartData = Data.getBuffer().substr(PartDataStart, PartSize);
570 LastOffset = PartOffset + PartSize;
571 switch (PT) {
572 case dxbc::PartType::DXIL:
573 case dxbc::PartType::ILDB:
574 if (Error Err = parseDXILHeader(PT, PartData))
575 return Err;
576 break;
577 case dxbc::PartType::ILDN:
578 if (Error Err = parseDebugName(PartData))
579 return Err;
580 break;
581 case dxbc::PartType::SFI0:
582 if (Error Err = parseShaderFeatureFlags(PartData))
583 return Err;
584 break;
585 case dxbc::PartType::HASH:
586 if (Error Err = parseHash(PartData))
587 return Err;
588 break;
589 case dxbc::PartType::PSV0:
590 if (Error Err = parsePSVInfo(PartData))
591 return Err;
592 break;
593 case dxbc::PartType::ISG1:
594 if (Error Err = InputSignature.initialize(PartData))
595 return Err;
596 break;
597 case dxbc::PartType::OSG1:
598 if (Error Err = OutputSignature.initialize(PartData))
599 return Err;
600 break;
601 case dxbc::PartType::PSG1:
602 if (Error Err = PatchConstantSignature.initialize(PartData))
603 return Err;
604 break;
606 break;
607 case dxbc::PartType::RTS0:
608 if (Error Err = parseRootSignature(PartData))
609 return Err;
610 break;
611 case dxbc::PartType::SRCI:
612 if (Error Err = parseSourceInfo(PartData))
613 return Err;
614 break;
615 case dxbc::PartType::VERS:
616 if (Error Err = parseCompilerVersionInfo(PartData))
617 return Err;
618 break;
619 }
620 }
621
622 if (DXIL && DebugDXIL &&
623 DXIL->first.ShaderKind != DebugDXIL->first.ShaderKind)
624 return parseFailed(
625 "ILDB part shader kind does not match DXIL part shader kind");
626
627 // Fully parsing the PSVInfo requires knowing the shader kind which we read
628 // out of the program header in the DXIL part.
629 if (PSVInfo) {
630 std::optional<uint16_t> ShaderKind = getShaderKind();
631 if (!ShaderKind)
632 return parseFailed("cannot fully parse pipeline state validation "
633 "information without DXIL or ILDB part");
634 if (Error Err = PSVInfo->parse(*ShaderKind))
635 return Err;
636 }
637 return Error::success();
638}
639
641 DXContainer Container(Object);
642 if (Error Err = Container.parseHeader())
643 return std::move(Err);
644 if (Error Err = Container.parsePartOffsets())
645 return std::move(Err);
646 return Container;
647}
648
649void DXContainer::PartIterator::updateIteratorImpl(const uint32_t Offset) {
650 StringRef Buffer = Container.Data.getBuffer();
651 const char *Current = Buffer.data() + Offset;
652 // Offsets are validated during parsing, so all offsets in the container are
653 // valid and contain enough readable data to read a header.
654 cantFail(readStruct(Buffer, Current, IteratorState.Part));
655 IteratorState.Data =
656 StringRef(Current + sizeof(dxbc::PartHeader), IteratorState.Part.Size);
657 IteratorState.Offset = Offset;
658}
659
661 const char *Current = PartData.begin();
662
663 // Root Signature headers expects 6 integers to be present.
664 if (PartData.size() < 6 * sizeof(uint32_t))
665 return parseFailed(
666 "Invalid root signature, insufficient space for header.");
667
669 Current += sizeof(uint32_t);
670
671 NumParameters =
673 Current += sizeof(uint32_t);
674
675 RootParametersOffset =
677 Current += sizeof(uint32_t);
678
679 NumStaticSamplers =
681 Current += sizeof(uint32_t);
682
683 StaticSamplersOffset =
685 Current += sizeof(uint32_t);
686
688 Current += sizeof(uint32_t);
689
690 ParametersHeaders.Data = PartData.substr(
691 RootParametersOffset,
692 NumParameters * sizeof(dxbc::RTS0::v1::RootParameterHeader));
693
694 StaticSamplers.Stride = (Version <= 2)
697
698 StaticSamplers.Data = PartData.substr(StaticSamplersOffset,
699 static_cast<size_t>(NumStaticSamplers) *
700 StaticSamplers.Stride);
701
702 return Error::success();
703}
704
706 Triple::EnvironmentType ShaderStage = dxbc::getShaderStage(ShaderKind);
707
708 const char *Current = Data.begin();
709 if (Error Err = readInteger(Data, Current, Size))
710 return Err;
711 Current += sizeof(uint32_t);
712
713 StringRef PSVInfoData = Data.substr(sizeof(uint32_t), Size);
714
715 if (PSVInfoData.size() < Size)
716 return parseFailed(
717 "Pipeline state data extends beyond the bounds of the part");
718
719 using namespace dxbc::PSV;
720
721 const uint32_t PSVVersion = getVersion();
722
723 // Detect the PSVVersion by looking at the size field.
724 if (PSVVersion == 3) {
725 v3::RuntimeInfo Info;
726 if (Error Err = readStruct(PSVInfoData, Current, Info))
727 return Err;
729 Info.swapBytes(ShaderStage);
730 BasicInfo = Info;
731 } else if (PSVVersion == 2) {
732 v2::RuntimeInfo Info;
733 if (Error Err = readStruct(PSVInfoData, Current, Info))
734 return Err;
736 Info.swapBytes(ShaderStage);
737 BasicInfo = Info;
738 } else if (PSVVersion == 1) {
739 v1::RuntimeInfo Info;
740 if (Error Err = readStruct(PSVInfoData, Current, Info))
741 return Err;
743 Info.swapBytes(ShaderStage);
744 BasicInfo = Info;
745 } else if (PSVVersion == 0) {
746 v0::RuntimeInfo Info;
747 if (Error Err = readStruct(PSVInfoData, Current, Info))
748 return Err;
750 Info.swapBytes(ShaderStage);
751 BasicInfo = Info;
752 } else
753 return parseFailed(
754 "Cannot read PSV Runtime Info, unsupported PSV version.");
755
756 Current += Size;
757
758 uint32_t ResourceCount = 0;
759 if (Error Err = readInteger(Data, Current, ResourceCount))
760 return Err;
761 Current += sizeof(uint32_t);
762
763 if (ResourceCount > 0) {
764 if (Error Err = readInteger(Data, Current, Resources.Stride))
765 return Err;
766 Current += sizeof(uint32_t);
767
768 size_t BindingDataSize = Resources.Stride * ResourceCount;
769 Resources.Data = Data.substr(Current - Data.begin(), BindingDataSize);
770
771 if (Resources.Data.size() < BindingDataSize)
772 return parseFailed(
773 "Resource binding data extends beyond the bounds of the part");
774
775 Current += BindingDataSize;
776 } else
777 Resources.Stride = sizeof(v2::ResourceBindInfo);
778
779 // PSV version 0 ends after the resource bindings.
780 if (PSVVersion == 0)
781 return Error::success();
782
783 // String table starts at a 4-byte offset.
784 Current = reinterpret_cast<const char *>(
786 reinterpret_cast<uintptr_t>(Current)));
787
788 uint32_t StringTableSize = 0;
789 if (Error Err = readInteger(Data, Current, StringTableSize))
790 return Err;
791 if (StringTableSize % 4 != 0)
792 return parseFailed("String table misaligned");
793 Current += sizeof(uint32_t);
794 StringTable = StringRef(Current, StringTableSize);
795
796 Current += StringTableSize;
797
798 uint32_t SemanticIndexTableSize = 0;
799 if (Error Err = readInteger(Data, Current, SemanticIndexTableSize))
800 return Err;
801 Current += sizeof(uint32_t);
802
803 SemanticIndexTable.reserve(SemanticIndexTableSize);
804 for (uint32_t I = 0; I < SemanticIndexTableSize; ++I) {
805 uint32_t Index = 0;
806 if (Error Err = readInteger(Data, Current, Index))
807 return Err;
808 Current += sizeof(uint32_t);
809 SemanticIndexTable.push_back(Index);
810 }
811
812 uint8_t InputCount = getSigInputCount();
813 uint8_t OutputCount = getSigOutputCount();
814 uint8_t PatchOrPrimCount = getSigPatchOrPrimCount();
815
816 uint32_t ElementCount = InputCount + OutputCount + PatchOrPrimCount;
817
818 if (ElementCount > 0) {
819 if (Error Err = readInteger(Data, Current, SigInputElements.Stride))
820 return Err;
821 Current += sizeof(uint32_t);
822 // Assign the stride to all the arrays.
823 SigOutputElements.Stride = SigPatchOrPrimElements.Stride =
824 SigInputElements.Stride;
825
826 if (Data.end() - Current <
827 (ptrdiff_t)(ElementCount * SigInputElements.Stride))
828 return parseFailed(
829 "Signature elements extend beyond the size of the part");
830
831 size_t InputSize = SigInputElements.Stride * InputCount;
832 SigInputElements.Data = Data.substr(Current - Data.begin(), InputSize);
833 Current += InputSize;
834
835 size_t OutputSize = SigOutputElements.Stride * OutputCount;
836 SigOutputElements.Data = Data.substr(Current - Data.begin(), OutputSize);
837 Current += OutputSize;
838
839 size_t PSize = SigPatchOrPrimElements.Stride * PatchOrPrimCount;
840 SigPatchOrPrimElements.Data = Data.substr(Current - Data.begin(), PSize);
841 Current += PSize;
842 }
843
844 ArrayRef<uint8_t> OutputVectorCounts = getOutputVectorCounts();
845 uint8_t PatchConstOrPrimVectorCount = getPatchConstOrPrimVectorCount();
846 uint8_t InputVectorCount = getInputVectorCount();
847
848 auto maskDwordSize = [](uint8_t Vector) {
849 return (static_cast<uint32_t>(Vector) + 7) >> 3;
850 };
851
852 auto mapTableSize = [maskDwordSize](uint8_t X, uint8_t Y) {
853 return maskDwordSize(Y) * X * 4;
854 };
855
856 if (usesViewID()) {
857 for (uint32_t I = 0; I < OutputVectorCounts.size(); ++I) {
858 // The vector mask is one bit per component and 4 components per vector.
859 // We can compute the number of dwords required by rounding up to the next
860 // multiple of 8.
861 uint32_t NumDwords =
862 maskDwordSize(static_cast<uint32_t>(OutputVectorCounts[I]));
863 size_t NumBytes = NumDwords * sizeof(uint32_t);
864 OutputVectorMasks[I].Data = Data.substr(Current - Data.begin(), NumBytes);
865 Current += NumBytes;
866 }
867
868 if (ShaderStage == Triple::Hull && PatchConstOrPrimVectorCount > 0) {
869 uint32_t NumDwords = maskDwordSize(PatchConstOrPrimVectorCount);
870 size_t NumBytes = NumDwords * sizeof(uint32_t);
871 PatchOrPrimMasks.Data = Data.substr(Current - Data.begin(), NumBytes);
872 Current += NumBytes;
873 }
874 }
875
876 // Input/Output mapping table
877 for (uint32_t I = 0; I < OutputVectorCounts.size(); ++I) {
878 if (InputVectorCount == 0 || OutputVectorCounts[I] == 0)
879 continue;
880 uint32_t NumDwords = mapTableSize(InputVectorCount, OutputVectorCounts[I]);
881 size_t NumBytes = NumDwords * sizeof(uint32_t);
882 InputOutputMap[I].Data = Data.substr(Current - Data.begin(), NumBytes);
883 Current += NumBytes;
884 }
885
886 // Hull shader: Input/Patch mapping table
887 if (ShaderStage == Triple::Hull && PatchConstOrPrimVectorCount > 0 &&
888 InputVectorCount > 0) {
889 uint32_t NumDwords =
890 mapTableSize(InputVectorCount, PatchConstOrPrimVectorCount);
891 size_t NumBytes = NumDwords * sizeof(uint32_t);
892 InputPatchMap.Data = Data.substr(Current - Data.begin(), NumBytes);
893 Current += NumBytes;
894 }
895
896 // Domain Shader: Patch/Output mapping table
897 if (ShaderStage == Triple::Domain && PatchConstOrPrimVectorCount > 0 &&
898 OutputVectorCounts[0] > 0) {
899 uint32_t NumDwords =
900 mapTableSize(PatchConstOrPrimVectorCount, OutputVectorCounts[0]);
901 size_t NumBytes = NumDwords * sizeof(uint32_t);
902 PatchOutputMap.Data = Data.substr(Current - Data.begin(), NumBytes);
903 Current += NumBytes;
904 }
905
906 return Error::success();
907}
908
910 if (const auto *P = std::get_if<dxbc::PSV::v3::RuntimeInfo>(&BasicInfo))
911 return P->SigInputElements;
912 if (const auto *P = std::get_if<dxbc::PSV::v2::RuntimeInfo>(&BasicInfo))
913 return P->SigInputElements;
914 if (const auto *P = std::get_if<dxbc::PSV::v1::RuntimeInfo>(&BasicInfo))
915 return P->SigInputElements;
916 return 0;
917}
918
920 if (const auto *P = std::get_if<dxbc::PSV::v3::RuntimeInfo>(&BasicInfo))
921 return P->SigOutputElements;
922 if (const auto *P = std::get_if<dxbc::PSV::v2::RuntimeInfo>(&BasicInfo))
923 return P->SigOutputElements;
924 if (const auto *P = std::get_if<dxbc::PSV::v1::RuntimeInfo>(&BasicInfo))
925 return P->SigOutputElements;
926 return 0;
927}
928
930 if (const auto *P = std::get_if<dxbc::PSV::v3::RuntimeInfo>(&BasicInfo))
931 return P->SigPatchOrPrimElements;
932 if (const auto *P = std::get_if<dxbc::PSV::v2::RuntimeInfo>(&BasicInfo))
933 return P->SigPatchOrPrimElements;
934 if (const auto *P = std::get_if<dxbc::PSV::v1::RuntimeInfo>(&BasicInfo))
935 return P->SigPatchOrPrimElements;
936 return 0;
937}
938
939class DXNotSupportedError : public ErrorInfo<DXNotSupportedError> {
940public:
941 static char ID;
942
943 DXNotSupportedError(StringRef S) : FeatureString(S) {}
944
945 void log(raw_ostream &OS) const override {
946 OS << "DXContainer does not support " << FeatureString;
947 }
948
949 std::error_code convertToErrorCode() const override {
950 return inconvertibleErrorCode();
951 }
952
953private:
954 StringRef FeatureString;
955};
956
958
959Expected<section_iterator>
963
967
972
974 llvm_unreachable("DXContainer does not support symbols");
975}
978 llvm_unreachable("DXContainer does not support symbols");
979}
980
985
987 PartIterator It = reinterpret_cast<PartIterator>(Sec.p);
988 if (It == Parts.end())
989 return;
990
991 ++It;
992 Sec.p = reinterpret_cast<uintptr_t>(It);
993}
994
997 PartIterator It = reinterpret_cast<PartIterator>(Sec.p);
998 return StringRef(It->Part.getName());
999}
1000
1002 PartIterator It = reinterpret_cast<PartIterator>(Sec.p);
1003 return It->Offset;
1004}
1005
1007 return (Sec.p - reinterpret_cast<uintptr_t>(Parts.begin())) /
1008 sizeof(PartIterator);
1009}
1010
1012 PartIterator It = reinterpret_cast<PartIterator>(Sec.p);
1013 return It->Data.size();
1014}
1017 PartIterator It = reinterpret_cast<PartIterator>(Sec.p);
1018 return ArrayRef<uint8_t>(It->Data.bytes_begin(), It->Data.size());
1019}
1020
1024
1026 return false;
1027}
1028
1030 return false;
1031}
1032
1034 return false;
1035}
1036
1038 return false;
1039}
1040
1042 return false;
1043}
1044
1049
1054
1056 llvm_unreachable("DXContainer does not support relocations");
1057}
1058
1060 llvm_unreachable("DXContainer does not support relocations");
1061}
1062
1067
1069 llvm_unreachable("DXContainer does not support relocations");
1070}
1071
1073 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1074 llvm_unreachable("DXContainer does not support relocations");
1075}
1076
1078 DataRefImpl Sec;
1079 Sec.p = reinterpret_cast<uintptr_t>(Parts.begin());
1080 return section_iterator(SectionRef(Sec, this));
1081}
1083 DataRefImpl Sec;
1084 Sec.p = reinterpret_cast<uintptr_t>(Parts.end());
1085 return section_iterator(SectionRef(Sec, this));
1086}
1087
1089
1091 return "DirectX Container";
1092}
1093
1095
1099
1104
1109
1112 auto ExC = DXContainer::create(Object);
1113 if (!ExC)
1114 return ExC.takeError();
1115 std::unique_ptr<DXContainerObjectFile> Obj(new DXContainerObjectFile(*ExC));
1116 return std::move(Obj);
1117}
#define X(NUM, ENUM, NAME)
Definition ELF.h:853
write Write Bitcode
#define offsetof(TYPE, MEMBER)
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static Error readString(StringRef Buffer, const char *&Src, size_t MaxSize, StringRef &Val, Twine Desc)
Read a null-terminated string at the position Src from Buffer, with maximum byte size of MaxSize (inc...
static Expected< size_t > parseArgs(StringRef Section, mcdxbc::SourceInfo::ProgramArgs &Args)
static Error readStruct(StringRef Buffer, const char *Src, T &Struct)
static Error parseFailed(const Twine &Msg)
static Expected< size_t > parseContents(StringRef Section, mcdxbc::SourceInfo::SourceContents &Contents)
static Expected< size_t > parseSourceInfoSection(const dxbc::SourceInfo::SectionHeader &Header, StringRef SectionData, mcdxbc::SourceInfo &SourceInfo)
static Expected< size_t > parseContentsEntries(StringRef Entries, mcdxbc::SourceInfo::SourceContents &Contents)
static bool readIsOutOfBounds(StringRef Buffer, const char *Src, size_t Size)
static Error readInteger(StringRef Buffer, const char *Src, T &Val, Twine Str="structure")
static Expected< size_t > parseNames(StringRef Section, mcdxbc::SourceInfo::SourceNames &Names)
static Expected< size_t > parseUncompressedContentsEntries(StringRef Entries, mcdxbc::SourceInfo::SourceContents &Contents)
#define P(N)
Provides some synthesis utilities to produce sequences of values.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
DXNotSupportedError(StringRef S)
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Base class for user error types.
Definition Error.h:354
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:591
iterator begin() const
Definition StringRef.h:114
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
iterator end() const
Definition StringRef.h:116
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
Manages the enabling and disabling of subtarget specific features.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
Expected< SymbolRef::Type > getSymbolType(DataRefImpl Symb) const override
uint64_t getRelocationOffset(DataRefImpl Rel) const override
uint64_t getSectionSize(DataRefImpl Sec) const override
relocation_iterator section_rel_begin(DataRefImpl Sec) const override
Triple::ArchType getArch() const override
bool isSectionCompressed(DataRefImpl Sec) const override
section_iterator section_end() const override
void getRelocationTypeName(DataRefImpl Rel, SmallVectorImpl< char > &Result) const override
uint64_t getSectionIndex(DataRefImpl Sec) const override
Expected< section_iterator > getSymbolSection(DataRefImpl Symb) const override
Expected< StringRef > getSectionName(DataRefImpl Sec) const override
uint64_t getSectionAddress(DataRefImpl Sec) const override
Expected< ArrayRef< uint8_t > > getSectionContents(DataRefImpl Sec) const override
section_iterator section_begin() const override
bool isSectionVirtual(DataRefImpl Sec) const override
void moveRelocationNext(DataRefImpl &Rel) const override
relocation_iterator section_rel_end(DataRefImpl Sec) const override
void moveSectionNext(DataRefImpl &Sec) const override
bool isSectionData(DataRefImpl Sec) const override
symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override
StringRef getFileFormatName() const override
uint64_t getSectionAlignment(DataRefImpl Sec) const override
Error printSymbolName(raw_ostream &OS, DataRefImpl Symb) const override
uint8_t getBytesInAddress() const override
The number of bytes used to represent an address in this object file format.
uint64_t getRelocationType(DataRefImpl Rel) const override
Expected< uint64_t > getSymbolAddress(DataRefImpl Symb) const override
bool isSectionBSS(DataRefImpl Sec) const override
uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override
uint64_t getSymbolValueImpl(DataRefImpl Symb) const override
Expected< uint32_t > getSymbolFlags(DataRefImpl Symb) const override
bool isSectionText(DataRefImpl Sec) const override
Expected< SubtargetFeatures > getFeatures() const override
Expected< StringRef > getSymbolName(DataRefImpl) const override
static LLVM_ABI Expected< DXContainer > create(MemoryBufferRef Object)
ArrayRef< uint8_t > getOutputVectorCounts() const
LLVM_ABI uint8_t getSigInputCount() const
LLVM_ABI uint8_t getSigPatchOrPrimCount() const
LLVM_ABI Error parse(uint16_t ShaderKind)
LLVM_ABI uint8_t getSigOutputCount() const
LLVM_ABI Error initialize(StringRef Part)
static Expected< std::unique_ptr< DXContainerObjectFile > > createDXContainerObjectFile(MemoryBufferRef Object)
friend class RelocationRef
Definition ObjectFile.h:289
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const char SectionName[]
LLVM_ABI Error decompress(ArrayRef< uint8_t > Input, uint8_t *Output, size_t &UncompressedSize)
LLVM_ABI bool isAvailable()
LLVM_ABI const char * getReasonIfUnsupported(Format F)
bool isValidCompressionType(uint16_t V)
LLVM_ABI bool isValidSectionType(uint16_t V)
LLVM_ABI StringRef getSectionName(SectionType Type)
LLVM_ABI PartType parsePartType(StringRef S)
Triple::EnvironmentType getShaderStage(uint32_t Kind)
Definition DXContainer.h:49
bool isDebugProgramPart(PartType PT)
bool isValidCompilerVersionFlags(uint32_t V)
const char * getProgramPartName(bool IsDebug)
static Error parseFailed(const Twine &Msg)
content_iterator< SectionRef > section_iterator
Definition ObjectFile.h:49
content_iterator< RelocationRef > relocation_iterator
Definition ObjectFile.h:79
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
Definition Endian.h:60
constexpr bool IsBigEndianHost
void swapByteOrder(T &Value)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
@ Length
Definition DWP.cpp:558
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
Op::Description Desc
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
FunctionAddr VTableAddr Next
Definition InstrProf.h:141
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
Use this type to describe the size and type of a DXIL container part.
CompressionType Type
Type of compression used to compress the whole section content.
uint32_t UncompressedEntriesSizeInBytes
Total size of the data entries when uncompressed.
uint32_t EntriesSizeInBytes
The size of the data entries following this header.
uint32_t Count
The number of data entries.
uint16_t Flags
Reserved, must be zero.
dxbc::SourceInfo::Contents::Header Parameters