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
15 #include <cstdint>
16 #include <cstring> // memcpy
17 #include <vector>
18
19 #include "source/spirv_target_env.h"
20 #include "spirv-tools/libspirv.hpp"
21 #include "test/fuzzers/random_generator.h"
22
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)23 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
24 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_0;
25 if (size > 0) {
26 spvtools::fuzzers::RandomGenerator random_gen(data, size);
27 target_env = random_gen.GetTargetEnv();
28 }
29
30 const spv_context context = spvContextCreate(target_env);
31 if (context == nullptr) {
32 return 0;
33 }
34
35 std::vector<uint32_t> input;
36 input.resize(size >> 2);
37 size_t count = 0;
38 for (size_t i = 0; (i + 3) < size; i += 4) {
39 input[count++] = data[i] | (data[i + 1] << 8) | (data[i + 2] << 16) |
40 (data[i + 3]) << 24;
41 }
42
43 std::vector<char> input_str;
44 size_t char_count = input.size() * sizeof(uint32_t) / sizeof(char);
45 input_str.resize(char_count);
46 memcpy(input_str.data(), input.data(), input.size() * sizeof(uint32_t));
47
48 spv_binary binary = nullptr;
49 spv_diagnostic diagnostic = nullptr;
50 spvTextToBinaryWithOptions(context, input_str.data(), input_str.size(),
51 SPV_TEXT_TO_BINARY_OPTION_NONE, &binary,
52 &diagnostic);
53 if (diagnostic) {
54 spvDiagnosticPrint(diagnostic);
55 spvDiagnosticDestroy(diagnostic);
56 diagnostic = nullptr;
57 }
58
59 if (binary) {
60 spvBinaryDestroy(binary);
61 binary = nullptr;
62 }
63
64 spvTextToBinaryWithOptions(context, input_str.data(), input_str.size(),
65 SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS,
66 &binary, &diagnostic);
67 if (diagnostic) {
68 spvDiagnosticPrint(diagnostic);
69 spvDiagnosticDestroy(diagnostic);
70 diagnostic = nullptr;
71 }
72
73 if (binary) {
74 spvBinaryDestroy(binary);
75 binary = nullptr;
76 }
77
78 spvContextDestroy(context);
79
80 return 0;
81 }
82