1 #include <fuzzer/FuzzedDataProvider.h>
2 #include <string>
3 #include <libxml/parser.h>
4
5
GenerateRandomXML(FuzzedDataProvider & stream)6 std::string GenerateRandomXML(FuzzedDataProvider& stream) {
7 std::string xml = "<root>";
8 int numberOfElements = stream.ConsumeIntegralInRange<int>(1, 10);
9
10 for (int i = 0; i < numberOfElements; ++i) {
11 std::string elementName = stream.ConsumeRandomLengthString(10); // Limiting name length to 10
12 xml += "<" + elementName + ">";
13
14 if (stream.ConsumeBool()) {
15 std::string textContent = stream.ConsumeRandomLengthString(20); // Limiting text content length
16 xml += textContent;
17 }
18
19 int numberOfAttributes = stream.ConsumeIntegralInRange<int>(0, 5);
20 for (int j = 0; j < numberOfAttributes; ++j) {
21 std::string attributeName = stream.ConsumeRandomLengthString(10); // Limiting attribute name length
22 std::string attributeValue = stream.ConsumeRandomLengthString(20); // Limiting attribute value length
23 xml += " " + attributeName + "=\"" + attributeValue + "\"";
24 }
25
26 xml += "</" + elementName + ">";
27 }
28
29 xml += "</root>";
30 return xml;
31 }
32
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)33 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
34 FuzzedDataProvider stream(data, size);
35
36 // Initialize the XML parser
37 xmlInitParser();
38
39 // Create and initialize parser context
40 xmlParserCtxtPtr ctxt = xmlNewParserCtxt();
41 if (ctxt == nullptr) {
42 // If cannot allocate context, early return
43 return 0;
44 }
45
46 // Generate fuzzed inputs
47 std::string buffer = GenerateRandomXML(stream);
48 int bufferSize = buffer.length();
49 std::string URL = stream.ConsumeRandomLengthString();
50 std::string encoding = stream.ConsumeRandomLengthString();
51 int options = stream.ConsumeIntegral<int>();
52
53 // Call the function under test
54 xmlDocPtr doc = xmlCtxtReadMemory(ctxt, buffer.data(), bufferSize, URL.c_str(), encoding.c_str(), options);
55
56 // Cleanup
57 if (doc != nullptr) {
58 xmlFreeDoc(doc);
59 }
60 xmlFreeParserCtxt(ctxt);
61 xmlCleanupParser();
62
63 return 0;
64 }
65