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 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)22 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
23   if (size < sizeof(spv_target_env) + 1) return 0;
24 
25   const spv_context context =
26       spvContextCreate(*reinterpret_cast<const spv_target_env*>(data));
27   if (context == nullptr) return 0;
28 
29   data += sizeof(spv_target_env);
30   size -= sizeof(spv_target_env);
31 
32   std::vector<uint32_t> input;
33 
34   std::vector<char> input_str;
35   size_t char_count = input.size() * sizeof(uint32_t) / sizeof(char);
36   input_str.resize(char_count);
37   memcpy(input_str.data(), input.data(), input.size() * sizeof(uint32_t));
38 
39   spv_binary binary = nullptr;
40   spv_diagnostic diagnostic = nullptr;
41   spvTextToBinaryWithOptions(context, input_str.data(), input_str.size(),
42                              SPV_TEXT_TO_BINARY_OPTION_NONE, &binary,
43                              &diagnostic);
44   if (diagnostic) {
45     spvDiagnosticPrint(diagnostic);
46     spvDiagnosticDestroy(diagnostic);
47     diagnostic = nullptr;
48   }
49 
50   if (binary) {
51     spvBinaryDestroy(binary);
52     binary = nullptr;
53   }
54 
55   spvTextToBinaryWithOptions(context, input_str.data(), input_str.size(),
56                              SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS,
57                              &binary, &diagnostic);
58   if (diagnostic) {
59     spvDiagnosticPrint(diagnostic);
60     spvDiagnosticDestroy(diagnostic);
61     diagnostic = nullptr;
62   }
63 
64   if (binary) {
65     spvBinaryDestroy(binary);
66     binary = nullptr;
67   }
68 
69   spvContextDestroy(context);
70 
71   return 0;
72 }
73