llvm-project
462 строки · 16.4 Кб
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
9#include "llvm/Object/DXContainer.h"10#include "llvm/BinaryFormat/DXContainer.h"11#include "llvm/Object/Error.h"12#include "llvm/Support/Alignment.h"13#include "llvm/Support/FormatVariadic.h"14
15using namespace llvm;16using namespace llvm::object;17
18static Error parseFailed(const Twine &Msg) {19return make_error<GenericBinaryError>(Msg.str(), object_error::parse_failed);20}
21
22template <typename T>23static Error readStruct(StringRef Buffer, const char *Src, T &Struct) {24// Don't read before the beginning or past the end of the file25if (Src < Buffer.begin() || Src + sizeof(T) > Buffer.end())26return parseFailed("Reading structure out of file bounds");27
28memcpy(&Struct, Src, sizeof(T));29// DXContainer is always little endian30if (sys::IsBigEndianHost)31Struct.swapBytes();32return Error::success();33}
34
35template <typename T>36static Error readInteger(StringRef Buffer, const char *Src, T &Val,37Twine Str = "structure") {38static_assert(std::is_integral_v<T>,39"Cannot call readInteger on non-integral type.");40// Don't read before the beginning or past the end of the file41if (Src < Buffer.begin() || Src + sizeof(T) > Buffer.end())42return parseFailed(Twine("Reading ") + Str + " out of file bounds");43
44// The DXContainer offset table is comprised of uint32_t values but not padded45// to a 64-bit boundary. So Parts may start unaligned if there is an odd46// number of parts and part data itself is not required to be padded.47if (reinterpret_cast<uintptr_t>(Src) % alignof(T) != 0)48memcpy(reinterpret_cast<char *>(&Val), Src, sizeof(T));49else50Val = *reinterpret_cast<const T *>(Src);51// DXContainer is always little endian52if (sys::IsBigEndianHost)53sys::swapByteOrder(Val);54return Error::success();55}
56
57DXContainer::DXContainer(MemoryBufferRef O) : Data(O) {}58
59Error DXContainer::parseHeader() {60return readStruct(Data.getBuffer(), Data.getBuffer().data(), Header);61}
62
63Error DXContainer::parseDXILHeader(StringRef Part) {64if (DXIL)65return parseFailed("More than one DXIL part is present in the file");66const char *Current = Part.begin();67dxbc::ProgramHeader Header;68if (Error Err = readStruct(Part, Current, Header))69return Err;70Current += offsetof(dxbc::ProgramHeader, Bitcode) + Header.Bitcode.Offset;71DXIL.emplace(std::make_pair(Header, Current));72return Error::success();73}
74
75Error DXContainer::parseShaderFeatureFlags(StringRef Part) {76if (ShaderFeatureFlags)77return parseFailed("More than one SFI0 part is present in the file");78uint64_t FlagValue = 0;79if (Error Err = readInteger(Part, Part.begin(), FlagValue))80return Err;81ShaderFeatureFlags = FlagValue;82return Error::success();83}
84
85Error DXContainer::parseHash(StringRef Part) {86if (Hash)87return parseFailed("More than one HASH part is present in the file");88dxbc::ShaderHash ReadHash;89if (Error Err = readStruct(Part, Part.begin(), ReadHash))90return Err;91Hash = ReadHash;92return Error::success();93}
94
95Error DXContainer::parsePSVInfo(StringRef Part) {96if (PSVInfo)97return parseFailed("More than one PSV0 part is present in the file");98PSVInfo = DirectX::PSVRuntimeInfo(Part);99// Parsing the PSVRuntime info occurs late because we need to read data from100// other parts first.101return Error::success();102}
103
104Error DirectX::Signature::initialize(StringRef Part) {105dxbc::ProgramSignatureHeader SigHeader;106if (Error Err = readStruct(Part, Part.begin(), SigHeader))107return Err;108size_t Size = sizeof(dxbc::ProgramSignatureElement) * SigHeader.ParamCount;109
110if (Part.size() < Size + SigHeader.FirstParamOffset)111return parseFailed("Signature parameters extend beyond the part boundary");112
113Parameters.Data = Part.substr(SigHeader.FirstParamOffset, Size);114
115StringTableOffset = SigHeader.FirstParamOffset + static_cast<uint32_t>(Size);116StringTable = Part.substr(SigHeader.FirstParamOffset + Size);117
118for (const auto &Param : Parameters) {119if (Param.NameOffset < StringTableOffset)120return parseFailed("Invalid parameter name offset: name starts before "121"the first name offset");122if (Param.NameOffset - StringTableOffset > StringTable.size())123return parseFailed("Invalid parameter name offset: name starts after the "124"end of the part data");125}126return Error::success();127}
128
129Error DXContainer::parsePartOffsets() {130uint32_t LastOffset =131sizeof(dxbc::Header) + (Header.PartCount * sizeof(uint32_t));132const char *Current = Data.getBuffer().data() + sizeof(dxbc::Header);133for (uint32_t Part = 0; Part < Header.PartCount; ++Part) {134uint32_t PartOffset;135if (Error Err = readInteger(Data.getBuffer(), Current, PartOffset))136return Err;137if (PartOffset < LastOffset)138return parseFailed(139formatv(140"Part offset for part {0} begins before the previous part ends",141Part)142.str());143Current += sizeof(uint32_t);144if (PartOffset >= Data.getBufferSize())145return parseFailed("Part offset points beyond boundary of the file");146// To prevent overflow when reading the part name, we subtract the part name147// size from the buffer size, rather than adding to the offset. Since the148// file header is larger than the part header we can't reach this code149// unless the buffer is at least as large as a part header, so this150// subtraction can't underflow.151if (PartOffset >= Data.getBufferSize() - sizeof(dxbc::PartHeader::Name))152return parseFailed("File not large enough to read part name");153PartOffsets.push_back(PartOffset);154
155dxbc::PartType PT =156dxbc::parsePartType(Data.getBuffer().substr(PartOffset, 4));157uint32_t PartDataStart = PartOffset + sizeof(dxbc::PartHeader);158uint32_t PartSize;159if (Error Err = readInteger(Data.getBuffer(),160Data.getBufferStart() + PartOffset + 4,161PartSize, "part size"))162return Err;163StringRef PartData = Data.getBuffer().substr(PartDataStart, PartSize);164LastOffset = PartOffset + PartSize;165switch (PT) {166case dxbc::PartType::DXIL:167if (Error Err = parseDXILHeader(PartData))168return Err;169break;170case dxbc::PartType::SFI0:171if (Error Err = parseShaderFeatureFlags(PartData))172return Err;173break;174case dxbc::PartType::HASH:175if (Error Err = parseHash(PartData))176return Err;177break;178case dxbc::PartType::PSV0:179if (Error Err = parsePSVInfo(PartData))180return Err;181break;182case dxbc::PartType::ISG1:183if (Error Err = InputSignature.initialize(PartData))184return Err;185break;186case dxbc::PartType::OSG1:187if (Error Err = OutputSignature.initialize(PartData))188return Err;189break;190case dxbc::PartType::PSG1:191if (Error Err = PatchConstantSignature.initialize(PartData))192return Err;193break;194case dxbc::PartType::Unknown:195break;196}197}198
199// Fully parsing the PSVInfo requires knowing the shader kind which we read200// out of the program header in the DXIL part.201if (PSVInfo) {202if (!DXIL)203return parseFailed("Cannot fully parse pipeline state validation "204"information without DXIL part.");205if (Error Err = PSVInfo->parse(DXIL->first.ShaderKind))206return Err;207}208return Error::success();209}
210
211Expected<DXContainer> DXContainer::create(MemoryBufferRef Object) {212DXContainer Container(Object);213if (Error Err = Container.parseHeader())214return std::move(Err);215if (Error Err = Container.parsePartOffsets())216return std::move(Err);217return Container;218}
219
220void DXContainer::PartIterator::updateIteratorImpl(const uint32_t Offset) {221StringRef Buffer = Container.Data.getBuffer();222const char *Current = Buffer.data() + Offset;223// Offsets are validated during parsing, so all offsets in the container are224// valid and contain enough readable data to read a header.225cantFail(readStruct(Buffer, Current, IteratorState.Part));226IteratorState.Data =227StringRef(Current + sizeof(dxbc::PartHeader), IteratorState.Part.Size);228IteratorState.Offset = Offset;229}
230
231Error DirectX::PSVRuntimeInfo::parse(uint16_t ShaderKind) {232Triple::EnvironmentType ShaderStage = dxbc::getShaderStage(ShaderKind);233
234const char *Current = Data.begin();235if (Error Err = readInteger(Data, Current, Size))236return Err;237Current += sizeof(uint32_t);238
239StringRef PSVInfoData = Data.substr(sizeof(uint32_t), Size);240
241if (PSVInfoData.size() < Size)242return parseFailed(243"Pipeline state data extends beyond the bounds of the part");244
245using namespace dxbc::PSV;246
247const uint32_t PSVVersion = getVersion();248
249// Detect the PSVVersion by looking at the size field.250if (PSVVersion == 3) {251v3::RuntimeInfo Info;252if (Error Err = readStruct(PSVInfoData, Current, Info))253return Err;254if (sys::IsBigEndianHost)255Info.swapBytes(ShaderStage);256BasicInfo = Info;257} else if (PSVVersion == 2) {258v2::RuntimeInfo Info;259if (Error Err = readStruct(PSVInfoData, Current, Info))260return Err;261if (sys::IsBigEndianHost)262Info.swapBytes(ShaderStage);263BasicInfo = Info;264} else if (PSVVersion == 1) {265v1::RuntimeInfo Info;266if (Error Err = readStruct(PSVInfoData, Current, Info))267return Err;268if (sys::IsBigEndianHost)269Info.swapBytes(ShaderStage);270BasicInfo = Info;271} else if (PSVVersion == 0) {272v0::RuntimeInfo Info;273if (Error Err = readStruct(PSVInfoData, Current, Info))274return Err;275if (sys::IsBigEndianHost)276Info.swapBytes(ShaderStage);277BasicInfo = Info;278} else279return parseFailed(280"Cannot read PSV Runtime Info, unsupported PSV version.");281
282Current += Size;283
284uint32_t ResourceCount = 0;285if (Error Err = readInteger(Data, Current, ResourceCount))286return Err;287Current += sizeof(uint32_t);288
289if (ResourceCount > 0) {290if (Error Err = readInteger(Data, Current, Resources.Stride))291return Err;292Current += sizeof(uint32_t);293
294size_t BindingDataSize = Resources.Stride * ResourceCount;295Resources.Data = Data.substr(Current - Data.begin(), BindingDataSize);296
297if (Resources.Data.size() < BindingDataSize)298return parseFailed(299"Resource binding data extends beyond the bounds of the part");300
301Current += BindingDataSize;302} else303Resources.Stride = sizeof(v2::ResourceBindInfo);304
305// PSV version 0 ends after the resource bindings.306if (PSVVersion == 0)307return Error::success();308
309// String table starts at a 4-byte offset.310Current = reinterpret_cast<const char *>(311alignTo<4>(reinterpret_cast<uintptr_t>(Current)));312
313uint32_t StringTableSize = 0;314if (Error Err = readInteger(Data, Current, StringTableSize))315return Err;316if (StringTableSize % 4 != 0)317return parseFailed("String table misaligned");318Current += sizeof(uint32_t);319StringTable = StringRef(Current, StringTableSize);320
321Current += StringTableSize;322
323uint32_t SemanticIndexTableSize = 0;324if (Error Err = readInteger(Data, Current, SemanticIndexTableSize))325return Err;326Current += sizeof(uint32_t);327
328SemanticIndexTable.reserve(SemanticIndexTableSize);329for (uint32_t I = 0; I < SemanticIndexTableSize; ++I) {330uint32_t Index = 0;331if (Error Err = readInteger(Data, Current, Index))332return Err;333Current += sizeof(uint32_t);334SemanticIndexTable.push_back(Index);335}336
337uint8_t InputCount = getSigInputCount();338uint8_t OutputCount = getSigOutputCount();339uint8_t PatchOrPrimCount = getSigPatchOrPrimCount();340
341uint32_t ElementCount = InputCount + OutputCount + PatchOrPrimCount;342
343if (ElementCount > 0) {344if (Error Err = readInteger(Data, Current, SigInputElements.Stride))345return Err;346Current += sizeof(uint32_t);347// Assign the stride to all the arrays.348SigOutputElements.Stride = SigPatchOrPrimElements.Stride =349SigInputElements.Stride;350
351if (Data.end() - Current <352(ptrdiff_t)(ElementCount * SigInputElements.Stride))353return parseFailed(354"Signature elements extend beyond the size of the part");355
356size_t InputSize = SigInputElements.Stride * InputCount;357SigInputElements.Data = Data.substr(Current - Data.begin(), InputSize);358Current += InputSize;359
360size_t OutputSize = SigOutputElements.Stride * OutputCount;361SigOutputElements.Data = Data.substr(Current - Data.begin(), OutputSize);362Current += OutputSize;363
364size_t PSize = SigPatchOrPrimElements.Stride * PatchOrPrimCount;365SigPatchOrPrimElements.Data = Data.substr(Current - Data.begin(), PSize);366Current += PSize;367}368
369ArrayRef<uint8_t> OutputVectorCounts = getOutputVectorCounts();370uint8_t PatchConstOrPrimVectorCount = getPatchConstOrPrimVectorCount();371uint8_t InputVectorCount = getInputVectorCount();372
373auto maskDwordSize = [](uint8_t Vector) {374return (static_cast<uint32_t>(Vector) + 7) >> 3;375};376
377auto mapTableSize = [maskDwordSize](uint8_t X, uint8_t Y) {378return maskDwordSize(Y) * X * 4;379};380
381if (usesViewID()) {382for (uint32_t I = 0; I < OutputVectorCounts.size(); ++I) {383// The vector mask is one bit per component and 4 components per vector.384// We can compute the number of dwords required by rounding up to the next385// multiple of 8.386uint32_t NumDwords =387maskDwordSize(static_cast<uint32_t>(OutputVectorCounts[I]));388size_t NumBytes = NumDwords * sizeof(uint32_t);389OutputVectorMasks[I].Data = Data.substr(Current - Data.begin(), NumBytes);390Current += NumBytes;391}392
393if (ShaderStage == Triple::Hull && PatchConstOrPrimVectorCount > 0) {394uint32_t NumDwords = maskDwordSize(PatchConstOrPrimVectorCount);395size_t NumBytes = NumDwords * sizeof(uint32_t);396PatchOrPrimMasks.Data = Data.substr(Current - Data.begin(), NumBytes);397Current += NumBytes;398}399}400
401// Input/Output mapping table402for (uint32_t I = 0; I < OutputVectorCounts.size(); ++I) {403if (InputVectorCount == 0 || OutputVectorCounts[I] == 0)404continue;405uint32_t NumDwords = mapTableSize(InputVectorCount, OutputVectorCounts[I]);406size_t NumBytes = NumDwords * sizeof(uint32_t);407InputOutputMap[I].Data = Data.substr(Current - Data.begin(), NumBytes);408Current += NumBytes;409}410
411// Hull shader: Input/Patch mapping table412if (ShaderStage == Triple::Hull && PatchConstOrPrimVectorCount > 0 &&413InputVectorCount > 0) {414uint32_t NumDwords =415mapTableSize(InputVectorCount, PatchConstOrPrimVectorCount);416size_t NumBytes = NumDwords * sizeof(uint32_t);417InputPatchMap.Data = Data.substr(Current - Data.begin(), NumBytes);418Current += NumBytes;419}420
421// Domain Shader: Patch/Output mapping table422if (ShaderStage == Triple::Domain && PatchConstOrPrimVectorCount > 0 &&423OutputVectorCounts[0] > 0) {424uint32_t NumDwords =425mapTableSize(PatchConstOrPrimVectorCount, OutputVectorCounts[0]);426size_t NumBytes = NumDwords * sizeof(uint32_t);427PatchOutputMap.Data = Data.substr(Current - Data.begin(), NumBytes);428Current += NumBytes;429}430
431return Error::success();432}
433
434uint8_t DirectX::PSVRuntimeInfo::getSigInputCount() const {435if (const auto *P = std::get_if<dxbc::PSV::v3::RuntimeInfo>(&BasicInfo))436return P->SigInputElements;437if (const auto *P = std::get_if<dxbc::PSV::v2::RuntimeInfo>(&BasicInfo))438return P->SigInputElements;439if (const auto *P = std::get_if<dxbc::PSV::v1::RuntimeInfo>(&BasicInfo))440return P->SigInputElements;441return 0;442}
443
444uint8_t DirectX::PSVRuntimeInfo::getSigOutputCount() const {445if (const auto *P = std::get_if<dxbc::PSV::v3::RuntimeInfo>(&BasicInfo))446return P->SigOutputElements;447if (const auto *P = std::get_if<dxbc::PSV::v2::RuntimeInfo>(&BasicInfo))448return P->SigOutputElements;449if (const auto *P = std::get_if<dxbc::PSV::v1::RuntimeInfo>(&BasicInfo))450return P->SigOutputElements;451return 0;452}
453
454uint8_t DirectX::PSVRuntimeInfo::getSigPatchOrPrimCount() const {455if (const auto *P = std::get_if<dxbc::PSV::v3::RuntimeInfo>(&BasicInfo))456return P->SigPatchOrPrimElements;457if (const auto *P = std::get_if<dxbc::PSV::v2::RuntimeInfo>(&BasicInfo))458return P->SigPatchOrPrimElements;459if (const auto *P = std::get_if<dxbc::PSV::v1::RuntimeInfo>(&BasicInfo))460return P->SigPatchOrPrimElements;461return 0;462}
463