1 #include <fuzzer/FuzzedDataProvider.h>
2 #include <libxml/parser.h>
3 #include <cstdio>
4 #include <unistd.h>
5 #include <fcntl.h>
6
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)7 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
8 FuzzedDataProvider stream(data, size);
9
10 // Initialize the XML parser
11 xmlInitParser();
12
13 // Create and initialize parser context
14 xmlParserCtxtPtr ctxt = xmlNewParserCtxt();
15 if (ctxt == nullptr) {
16 return 0;
17 }
18
19 // Create a temporary file
20 std::unique_ptr<std::FILE, decltype(&fclose)> fp(tmpfile(), &fclose);
21 if (!fp) {
22 xmlFreeParserCtxt(ctxt);
23 return 0;
24 }
25
26 // Write fuzzed data to the temporary file
27 fwrite(data, 1, size, fp.get());
28 fflush(fp.get());
29 rewind(fp.get());
30
31 // Get the file descriptor from the FILE object
32 int fd = fileno(fp.get());
33
34 // Generate other fuzzed inputs
35 std::string URL = stream.ConsumeRandomLengthString();
36 std::string encoding = stream.ConsumeRandomLengthString();
37 int options = stream.ConsumeIntegral<int>();
38
39 // Call the function under test
40 xmlDocPtr doc = xmlCtxtReadFd(ctxt, fd, URL.c_str(), encoding.c_str(), options);
41
42 // Cleanup
43 if (doc != nullptr) {
44 xmlFreeDoc(doc);
45 }
46 xmlFreeParserCtxt(ctxt);
47 xmlCleanupParser();
48
49 return 0;
50 }
51