Debian Codegraph @

contrib/fuzz/manifest.cc

raw
1 #include <Python.h>
2 #include <assert.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5
6 #include "FuzzedDataProvider.h"
7 #include "pyutil.h"
8
9 #include <string>
10
11 extern "C" {
12
13 static PYCODETYPE *code;
14
15 extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv)
16 {
17 contrib::initpy(*argv[0]);
18 code = (PYCODETYPE *)Py_CompileString(R"py(
19 try:
20 lm = parsers.lazymanifest(mdata)
21 # iterate the whole thing, which causes the code to fully parse
22 # every line in the manifest
23 for e, _, _ in lm.iterentries():
24 # also exercise __getitem__ et al
25 lm[e]
26 e in lm
27 (e + 'nope') in lm
28 lm[b'xyzzy'] = (b'\0' * nlen, 'x')
29 # do an insert, text should change
30 assert lm.text() != mdata, "insert should change text and didn't: %r %r" % (lm.text(), mdata)
31 cloned = lm.filtercopy(lambda x: x != 'xyzzy')
32 assert cloned.text() == mdata, 'cloned text should equal mdata'
33 cloned.diff(lm)
34 del lm[b'xyzzy']
35 cloned.diff(lm)
36 # should be back to the same
37 assert lm.text() == mdata, "delete should have restored text but didn't: %r %r" % (lm.text(), mdata)
38 except Exception as e:
39 pass
40 # uncomment this print if you're editing this Python code
41 # to debug failures.
42 # print e
43 )py",
44 "fuzzer", Py_file_input);
45 return 0;
46 }
47
48 int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)
49 {
50 // Don't allow fuzzer inputs larger than 100k, since we'll just bog
51 // down and not accomplish much.
52 if (Size > 100000) {
53 return 0;
54 }
55 FuzzedDataProvider provider(Data, Size);
56 Py_ssize_t nodelength = provider.ConsumeBool() ? 20 : 32;
57 PyObject *nlen = PyLong_FromSsize_t(nodelength);
58 PyObject *mtext =
59 PyBytes_FromStringAndSize((const char *)Data, (Py_ssize_t)Size);
60 PyObject *locals = PyDict_New();
61 PyDict_SetItemString(locals, "mdata", mtext);
62 PyDict_SetItemString(locals, "nlen", nlen);
63 PyObject *res = PyEval_EvalCode(code, contrib::pyglobals(), locals);
64 if (!res) {
65 PyErr_Print();
66 }
67 Py_XDECREF(res);
68 Py_DECREF(locals);
69 Py_DECREF(mtext);
70 return 0; // Non-zero return values are reserved for future use.
71 }
72 }