| 1 |
#include "pyutil.h" |
| 2 |
|
| 3 |
#include <iostream> |
| 4 |
#include <string> |
| 5 |
|
| 6 |
namespace contrib |
| 7 |
{ |
| 8 |
|
| 9 |
#if PY_MAJOR_VERSION >= 3 |
| 10 |
#define HG_FUZZER_PY3 1 |
| 11 |
PyMODINIT_FUNC PyInit_parsers(void); |
| 12 |
#else |
| 13 |
PyMODINIT_FUNC initparsers(void); |
| 14 |
#endif |
| 15 |
|
| 16 |
static char cpypath[8192] = "\0"; |
| 17 |
|
| 18 |
static PyObject *mainmod; |
| 19 |
static PyObject *globals; |
| 20 |
|
| 21 |
void initpy(const char *cselfpath) |
| 22 |
{ |
| 23 |
#ifdef HG_FUZZER_PY3 |
| 24 |
const std::string subdir = "/sanpy/lib/python3.8"; |
| 25 |
#else |
| 26 |
const std::string subdir = "/sanpy/lib/python2.7"; |
| 27 |
#endif |
| 28 |
|
| 29 |
/* HACK ALERT: we need a full Python installation built without |
| 30 |
pymalloc and with ASAN, so we dump one in |
| 31 |
$OUT/sanpy/lib/python2.7. This helps us wire that up. */ |
| 32 |
std::string selfpath(cselfpath); |
| 33 |
std::string pypath; |
| 34 |
auto pos = selfpath.rfind("/"); |
| 35 |
if (pos == std::string::npos) { |
| 36 |
char wd[8192]; |
| 37 |
if (!getcwd(wd, 8192)) { |
| 38 |
std::cerr << "Failed to call getcwd: errno " << errno |
| 39 |
<< std::endl; |
| 40 |
exit(1); |
| 41 |
} |
| 42 |
pypath = std::string(wd) + subdir; |
| 43 |
} else { |
| 44 |
pypath = selfpath.substr(0, pos) + subdir; |
| 45 |
} |
| 46 |
strncpy(cpypath, pypath.c_str(), pypath.size()); |
| 47 |
setenv("PYTHONPATH", cpypath, 1); |
| 48 |
setenv("PYTHONNOUSERSITE", "1", 1); |
| 49 |
/* prevent Python from looking up users in the fuzz environment */ |
| 50 |
setenv("PYTHONUSERBASE", cpypath, 1); |
| 51 |
#ifdef HG_FUZZER_PY3 |
| 52 |
std::wstring wcpypath(pypath.begin(), pypath.end()); |
| 53 |
Py_SetPythonHome(wcpypath.c_str()); |
| 54 |
#else |
| 55 |
Py_SetPythonHome(cpypath); |
| 56 |
#endif |
| 57 |
Py_InitializeEx(0); |
| 58 |
mainmod = PyImport_AddModule("__main__"); |
| 59 |
globals = PyModule_GetDict(mainmod); |
| 60 |
|
| 61 |
#ifdef HG_FUZZER_PY3 |
| 62 |
PyObject *mod = PyInit_parsers(); |
| 63 |
#else |
| 64 |
initparsers(); |
| 65 |
PyObject *mod = PyImport_ImportModule("parsers"); |
| 66 |
#endif |
| 67 |
|
| 68 |
PyDict_SetItemString(globals, "parsers", mod); |
| 69 |
} |
| 70 |
|
| 71 |
PyObject *pyglobals() |
| 72 |
{ |
| 73 |
return globals; |
| 74 |
} |
| 75 |
|
| 76 |
} // namespace contrib |