xref: /freebsd/contrib/expat/fuzz/xml_parsebuffer_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 #include <string.h>
20 
21 #include "expat.h"
22 #include "siphash.h"
23 
24 // Macros to convert preprocessor macros to string literals. See
25 // https://gcc.gnu.org/onlinedocs/gcc-3.4.3/cpp/Stringification.html
26 #define xstr(s) str(s)
27 #define str(s) #s
28 
29 // The encoder type that we wish to fuzz should come from the compile-time
30 // definition `ENCODING_FOR_FUZZING`. This allows us to have a separate fuzzer
31 // binary for
32 #ifndef ENCODING_FOR_FUZZING
33 #  error "ENCODING_FOR_FUZZING was not provided to this fuzz target."
34 #endif
35 
36 // 16-byte deterministic hash key.
37 static unsigned char hash_key[16] = "FUZZING IS FUN!";
38 
39 static void XMLCALL
40 start(void *userData, const XML_Char *name, const XML_Char **atts) {
41   (void)userData;
42   (void)name;
43   (void)atts;
44 }
45 static void XMLCALL
46 end(void *userData, const XML_Char *name) {
47   (void)userData;
48   (void)name;
49 }
50 
51 int
52 LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
53   if (size == 0)
54     return 0;
55 
56   XML_Parser p = XML_ParserCreate(xstr(ENCODING_FOR_FUZZING));
57   assert(p);
58   XML_SetElementHandler(p, start, end);
59 
60   // Set the hash salt using siphash to generate a deterministic hash.
61   struct sipkey *key = sip_keyof(hash_key);
62   XML_SetHashSalt(p, (unsigned long)siphash24(data, size, key));
63 
64   void *buf = XML_GetBuffer(p, size);
65   assert(buf);
66 
67   memcpy(buf, data, size);
68   XML_ParseBuffer(p, size, size == 0);
69   XML_ParserFree(p);
70   return 0;
71 }
72