1 // Copyright 2017 Google Inc. All rights reserved.
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 "libxml/parser.h"
16 #include "libxml/xmlsave.h"
17
18 #include "examples/xml/xml.pb.h"
19 #include "examples/xml/xml_writer.h"
20 #include "src/libfuzzer/libfuzzer_macro.h"
21
22 namespace {
23 protobuf_mutator::protobuf::LogSilencer log_silincer;
ignore(void * ctx,const char * msg,...)24 void ignore(void* ctx, const char* msg, ...) {}
25
26 template <class T, class D>
MakeUnique(T * obj,D del)27 std::unique_ptr<T, D> MakeUnique(T* obj, D del) {
28 return {obj, del};
29 }
30 }
31
DEFINE_PROTO_FUZZER(const protobuf_mutator::xml::Input & message)32 DEFINE_PROTO_FUZZER(const protobuf_mutator::xml::Input& message) {
33 std::string xml = MessageToXml(message.document());
34 int options = message.options();
35
36 // Network requests are too slow.
37 options |= XML_PARSE_NONET;
38 // These flags can cause network or file access and hangs.
39 options &= ~(XML_PARSE_NOENT | XML_PARSE_HUGE | XML_PARSE_DTDVALID |
40 XML_PARSE_DTDLOAD | XML_PARSE_DTDATTR);
41
42 xmlSetGenericErrorFunc(nullptr, &ignore);
43
44 if (auto doc =
45 MakeUnique(xmlReadMemory(xml.c_str(), static_cast<int>(xml.size()),
46 "", nullptr, options),
47 &xmlFreeDoc)) {
48 auto buf = MakeUnique(xmlBufferCreate(), &xmlBufferFree);
49 auto ctxt =
50 MakeUnique(xmlSaveToBuffer(buf.get(), nullptr, 0), &xmlSaveClose);
51 xmlSaveDoc(ctxt.get(), doc.get());
52 }
53 }
54