xref: /freebsd/contrib/expat/fuzz/xml_parse_fuzzer.c (revision 7ef62cebc2f965b0f640263e179276928885e33d)
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <assert.h>
18 #include <stdint.h>
19 
20 #include "expat.h"
21 #include "siphash.h"
22 
23 // Macros to convert preprocessor macros to string literals. See
24 // https://gcc.gnu.org/onlinedocs/gcc-3.4.3/cpp/Stringification.html
25 #define xstr(s) str(s)
26 #define str(s) #s
27 
28 // The encoder type that we wish to fuzz should come from the compile-time
29 // definition `ENCODING_FOR_FUZZING`. This allows us to have a separate fuzzer
30 // binary for
31 #ifndef ENCODING_FOR_FUZZING
32 #  error "ENCODING_FOR_FUZZING was not provided to this fuzz target."
33 #endif
34 
35 // 16-byte deterministic hash key.
36 static unsigned char hash_key[16] = "FUZZING IS FUN!";
37 
38 static void XMLCALL
39 start(void *userData, const XML_Char *name, const XML_Char **atts) {
40   (void)userData;
41   (void)name;
42   (void)atts;
43 }
44 static void XMLCALL
45 end(void *userData, const XML_Char *name) {
46   (void)userData;
47   (void)name;
48 }
49 
50 int
51 LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
52   XML_Parser p = XML_ParserCreate(xstr(ENCODING_FOR_FUZZING));
53   assert(p);
54 
55   // Set the hash salt using siphash to generate a deterministic hash.
56   struct sipkey *key = sip_keyof(hash_key);
57   XML_SetHashSalt(p, (unsigned long)siphash24(data, size, key));
58 
59   XML_SetElementHandler(p, start, end);
60   XML_Parse(p, (const XML_Char *)data, size, 0);
61   XML_Parse(p, (const XML_Char *)data, size, 1);
62   XML_ParserFree(p);
63   return 0;
64 }
65