| 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 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 |
for fn in ( |
| 21 |
parsers.isasciistr, |
| 22 |
parsers.asciilower, |
| 23 |
parsers.asciiupper, |
| 24 |
parsers.encodedir, |
| 25 |
parsers.pathencode, |
| 26 |
parsers.lowerencode, |
| 27 |
): |
| 28 |
try: |
| 29 |
fn(data) |
| 30 |
except UnicodeDecodeError: |
| 31 |
pass # some functions emit this exception |
| 32 |
except AttributeError: |
| 33 |
# pathencode needs hashlib, which fails to import because the time |
| 34 |
# module fails to import. We should try and fix that some day, but |
| 35 |
# for now we at least get coverage on non-hashencoded codepaths. |
| 36 |
if fn != pathencode: |
| 37 |
raise |
| 38 |
# uncomment this for debugging exceptions |
| 39 |
# except Exception as e: |
| 40 |
# raise Exception('%r: %r' % (fn, e)) |
| 41 |
except Exception as e: |
| 42 |
pass |
| 43 |
# uncomment this print if you're editing this Python code |
| 44 |
# to debug failures. |
| 45 |
# print(e) |
| 46 |
)py", |
| 47 |
"fuzzer", Py_file_input); |
| 48 |
if (!code) { |
| 49 |
std::cerr << "failed to compile Python code!" << std::endl; |
| 50 |
} |
| 51 |
return 0; |
| 52 |
} |
| 53 |
|
| 54 |
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) |
| 55 |
{ |
| 56 |
PyObject *mtext = |
| 57 |
PyBytes_FromStringAndSize((const char *)Data, (Py_ssize_t)Size); |
| 58 |
PyObject *locals = PyDict_New(); |
| 59 |
PyDict_SetItemString(locals, "data", mtext); |
| 60 |
PyObject *res = PyEval_EvalCode(code, contrib::pyglobals(), locals); |
| 61 |
if (!res) { |
| 62 |
PyErr_Print(); |
| 63 |
} |
| 64 |
Py_XDECREF(res); |
| 65 |
Py_DECREF(locals); |
| 66 |
Py_DECREF(mtext); |
| 67 |
return 0; // Non-zero return values are reserved for future use. |
| 68 |
} |
| 69 |
} |