| 1 |
/* |
| 2 |
* Copyright 2024 Google LLC |
| 3 |
* |
| 4 |
* Use of this source code is governed by a BSD-style license that can be |
| 5 |
* found in the LICENSE file. |
| 6 |
*/ |
| 7 |
|
| 8 |
#include "src/sksl/codegen/SkSLSPIRVValidator.h" |
| 9 |
|
| 10 |
#include "src/sksl/SkSLErrorReporter.h" |
| 11 |
#include "src/sksl/SkSLPosition.h" |
| 12 |
|
| 13 |
#include "spirv-tools/libspirv.hpp" |
| 14 |
|
| 15 |
namespace SkSL { |
| 16 |
|
| 17 |
static bool validate_spirv(ErrorReporter& reporter, |
| 18 |
SkSpan<const uint32_t> program, |
| 19 |
bool disassemble) { |
| 20 |
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0); |
| 21 |
std::string errors; |
| 22 |
auto msgFn = [&errors](spv_message_level_t, const char*, const spv_position_t&, const char* m) { |
| 23 |
errors += "SPIR-V validation error: "; |
| 24 |
errors += m; |
| 25 |
errors += '\n'; |
| 26 |
}; |
| 27 |
tools.SetMessageConsumer(msgFn); |
| 28 |
|
| 29 |
bool result = tools.Validate(program.data(), program.size()); |
| 30 |
if (result) { |
| 31 |
return true; |
| 32 |
} |
| 33 |
// If disassemble is set, we won't abort but instead append the errors. This allows |
| 34 |
// us to keep going and show all the errors, which is used by skslc to make sure |
| 35 |
// expected validation errors fail as expected.. |
| 36 |
if (disassemble) { |
| 37 |
// Send the message, plus the entire disassembled SPIR-V (for easier context & debugging) |
| 38 |
// as if were an SkSL compile error message. |
| 39 |
std::string disassembly; |
| 40 |
uint32_t options = spvtools::SpirvTools::kDefaultDisassembleOption; |
| 41 |
options |= SPV_BINARY_TO_TEXT_OPTION_COMMENT | SPV_BINARY_TO_TEXT_OPTION_INDENT | |
| 42 |
SPV_BINARY_TO_TEXT_OPTION_NESTED_INDENT; |
| 43 |
if (tools.Disassemble(program.data(), program.size(), &disassembly, options)) { |
| 44 |
errors.append(disassembly); |
| 45 |
} |
| 46 |
reporter.error(Position(), errors); |
| 47 |
} else { |
| 48 |
// Normal validation mode - abort() in a debug build with an error message. |
| 49 |
SkDEBUGFAILF("%s", errors.c_str()); |
| 50 |
} |
| 51 |
return false; |
| 52 |
} |
| 53 |
|
| 54 |
bool ValidateSPIRV(ErrorReporter& reporter, SkSpan<const uint32_t> program) { |
| 55 |
return validate_spirv(reporter, program, false); |
| 56 |
} |
| 57 |
|
| 58 |
bool ValidateSPIRVAndDissassemble(ErrorReporter& reporter, SkSpan<const uint32_t> program) { |
| 59 |
return validate_spirv(reporter, program, true); |
| 60 |
} |
| 61 |
|
| 62 |
} // namespace SkSL |