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