spvtools_dis_fuzzer.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. if (size < 4) {
  22. // There are not enough bytes to constitute a binary that can be
  23. // disassembled.
  24. return 0;
  25. }
  26. spvtools::fuzzers::RandomGenerator random_gen(data, size);
  27. const spv_context context = spvContextCreate(random_gen.GetTargetEnv());
  28. if (context == nullptr) {
  29. return 0;
  30. }
  31. std::vector<uint32_t> input;
  32. input.resize(size >> 2);
  33. size_t count = 0;
  34. for (size_t i = 0; (i + 3) < size; i += 4) {
  35. input[count++] = data[i] | (data[i + 1] << 8) | (data[i + 2] << 16) |
  36. (data[i + 3]) << 24;
  37. }
  38. std::vector<char> input_str;
  39. size_t char_count = input.size() * sizeof(uint32_t) / sizeof(char);
  40. input_str.resize(char_count);
  41. memcpy(input_str.data(), input.data(), input.size() * sizeof(uint32_t));
  42. spv_text text = nullptr;
  43. spv_diagnostic diagnostic = nullptr;
  44. for (uint32_t options = SPV_BINARY_TO_TEXT_OPTION_NONE;
  45. options <
  46. (SPV_BINARY_TO_TEXT_OPTION_PRINT | SPV_BINARY_TO_TEXT_OPTION_COLOR |
  47. SPV_BINARY_TO_TEXT_OPTION_INDENT |
  48. SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET |
  49. SPV_BINARY_TO_TEXT_OPTION_NO_HEADER |
  50. SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
  51. options++) {
  52. spvBinaryToText(context, input.data(), input.size(), options, &text,
  53. &diagnostic);
  54. if (diagnostic) {
  55. spvDiagnosticDestroy(diagnostic);
  56. diagnostic = nullptr;
  57. }
  58. if (text) {
  59. spvTextDestroy(text);
  60. text = nullptr;
  61. }
  62. }
  63. spvContextDestroy(context);
  64. return 0;
  65. }