|
1 #include <Python.h> |
|
2 #include <assert.h> |
|
3 #include <stdlib.h> |
|
4 #include <unistd.h> |
|
5 |
|
6 #include "pyutil.h" |
|
7 |
|
8 #include <iostream> |
|
9 #include <string> |
|
10 |
|
11 extern "C" { |
|
12 |
|
13 static PyCodeObject *code; |
|
14 |
|
15 extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) |
|
16 { |
|
17 contrib::initpy(*argv[0]); |
|
18 code = (PyCodeObject *)Py_CompileString(R"py( |
|
19 from parsers import ( |
|
20 isasciistr, |
|
21 asciilower, |
|
22 asciiupper, |
|
23 encodedir, |
|
24 pathencode, |
|
25 lowerencode, |
|
26 ) |
|
27 |
|
28 try: |
|
29 for fn in ( |
|
30 isasciistr, |
|
31 asciilower, |
|
32 asciiupper, |
|
33 encodedir, |
|
34 pathencode, |
|
35 lowerencode, |
|
36 ): |
|
37 try: |
|
38 fn(data) |
|
39 except UnicodeDecodeError: |
|
40 pass # some functions emit this exception |
|
41 except AttributeError: |
|
42 # pathencode needs hashlib, which fails to import because the time |
|
43 # module fails to import. We should try and fix that some day, but |
|
44 # for now we at least get coverage on non-hashencoded codepaths. |
|
45 if fn != pathencode: |
|
46 raise |
|
47 # uncomment this for debugging exceptions |
|
48 # except Exception as e: |
|
49 # raise Exception('%r: %r' % (fn, e)) |
|
50 except Exception as e: |
|
51 pass |
|
52 # uncomment this print if you're editing this Python code |
|
53 # to debug failures. |
|
54 # print(e) |
|
55 )py", |
|
56 "fuzzer", Py_file_input); |
|
57 if (!code) { |
|
58 std::cerr << "failed to compile Python code!" << std::endl; |
|
59 } |
|
60 return 0; |
|
61 } |
|
62 |
|
63 int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) |
|
64 { |
|
65 PyObject *mtext = |
|
66 PyBytes_FromStringAndSize((const char *)Data, (Py_ssize_t)Size); |
|
67 PyObject *locals = PyDict_New(); |
|
68 PyDict_SetItemString(locals, "data", mtext); |
|
69 PyObject *res = PyEval_EvalCode(code, contrib::pyglobals(), locals); |
|
70 if (!res) { |
|
71 PyErr_Print(); |
|
72 } |
|
73 Py_XDECREF(res); |
|
74 Py_DECREF(locals); |
|
75 Py_DECREF(mtext); |
|
76 return 0; // Non-zero return values are reserved for future use. |
|
77 } |
|
78 } |