spvtools_as_fuzzer.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (c) 2019 Google Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <cstdint>
  15. #include <cstring> // memcpy
  16. #include <vector>
  17. #include "source/spirv_target_env.h"
  18. #include "spirv-tools/libspirv.hpp"
  19. #include "test/fuzzers/random_generator.h"
  20. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  21. spv_target_env target_env = SPV_ENV_UNIVERSAL_1_0;
  22. if (size > 0) {
  23. spvtools::fuzzers::RandomGenerator random_gen(data, size);
  24. target_env = random_gen.GetTargetEnv();
  25. }
  26. const spv_context context = spvContextCreate(target_env);
  27. if (context == nullptr) {
  28. return 0;
  29. }
  30. std::vector<char> contents;
  31. contents.resize(size);
  32. memcpy(contents.data(), data, size);
  33. spv_binary binary = nullptr;
  34. spv_diagnostic diagnostic = nullptr;
  35. spvTextToBinaryWithOptions(context, contents.data(), contents.size(),
  36. SPV_TEXT_TO_BINARY_OPTION_NONE, &binary,
  37. &diagnostic);
  38. if (diagnostic) {
  39. spvDiagnosticPrint(diagnostic);
  40. spvDiagnosticDestroy(diagnostic);
  41. diagnostic = nullptr;
  42. }
  43. if (binary) {
  44. spvBinaryDestroy(binary);
  45. binary = nullptr;
  46. }
  47. spvTextToBinaryWithOptions(context, contents.data(), contents.size(),
  48. SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS,
  49. &binary, &diagnostic);
  50. if (diagnostic) {
  51. spvDiagnosticPrint(diagnostic);
  52. spvDiagnosticDestroy(diagnostic);
  53. diagnostic = nullptr;
  54. }
  55. if (binary) {
  56. spvBinaryDestroy(binary);
  57. binary = nullptr;
  58. }
  59. spvContextDestroy(context);
  60. return 0;
  61. }