1 // Copyright 2020 Google LLC
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 "common.h"
16 #include <fuzzer/FuzzedDataProvider.h>
17 
18 #ifndef HASHTYPE
19 #error Macro HASHTYPE must be defined.
20 #endif
21 
22 #ifndef FNAME
23 #error Macro FNAME must be defined.
24 #endif
25 
26 #define CONCAT_TYPE(x) _PASTE2(HASHTYPE, x)
27 
28 #define init CONCAT_TYPE(_init)
29 #define update CONCAT_TYPE(_update)
30 #define digest CONCAT_TYPE(_digest)
31 #define destroy CONCAT_TYPE(_destroy)
32 
33 #define STR(x) #x
34 #define INCLUDE(x) STR(x)
35 
36 #include INCLUDE(FNAME)
37 
38 #ifndef DIGEST_SIZE
39 #error Macro DIGEST_SIZE must be defined.
40 #endif
41 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)42 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
43 
44   if (!size)
45     return 0;
46 
47   FuzzedDataProvider stream(data, size);
48   hash_state *hs;
49   if (init(&hs))
50     return 0;
51 
52   while (stream.remaining_bytes()) {
53     size_t num_bytes = stream.ConsumeIntegral<size_t>();
54     std::vector<uint8_t> buffer = stream.ConsumeBytes<uint8_t>(num_bytes);
55 
56     if (update(hs, buffer.data(), buffer.size()))
57       goto error;
58   }
59 
60   uint8_t result[DIGEST_SIZE];
61 
62 #ifndef DIGEST_THIRD_PARAM
63   digest(hs, result);
64 #else
65   digest(hs, result, DIGEST_SIZE);
66 #endif
67 
68 error:
69   destroy(hs);
70   return 0;
71 }
72