contrib/fuzz/pyutil.cc
changeset 41013 ef103c96ed33
child 43807 c78f8f0720cc
equal deleted inserted replaced
41012:1e51dc85ce12 41013:ef103c96ed33
       
     1 #include "pyutil.h"
       
     2 
       
     3 #include <string>
       
     4 
       
     5 namespace contrib
       
     6 {
       
     7 
       
     8 static char cpypath[8192] = "\0";
       
     9 
       
    10 static PyObject *mainmod;
       
    11 static PyObject *globals;
       
    12 
       
    13 /* TODO: use Python 3 for this fuzzing? */
       
    14 PyMODINIT_FUNC initparsers(void);
       
    15 
       
    16 void initpy(const char *cselfpath)
       
    17 {
       
    18 	const std::string subdir = "/sanpy/lib/python2.7";
       
    19 	/* HACK ALERT: we need a full Python installation built without
       
    20 	   pymalloc and with ASAN, so we dump one in
       
    21 	   $OUT/sanpy/lib/python2.7. This helps us wire that up. */
       
    22 	std::string selfpath(cselfpath);
       
    23 	std::string pypath;
       
    24 	auto pos = selfpath.rfind("/");
       
    25 	if (pos == std::string::npos) {
       
    26 		char wd[8192];
       
    27 		getcwd(wd, 8192);
       
    28 		pypath = std::string(wd) + subdir;
       
    29 	} else {
       
    30 		pypath = selfpath.substr(0, pos) + subdir;
       
    31 	}
       
    32 	strncpy(cpypath, pypath.c_str(), pypath.size());
       
    33 	setenv("PYTHONPATH", cpypath, 1);
       
    34 	setenv("PYTHONNOUSERSITE", "1", 1);
       
    35 	/* prevent Python from looking up users in the fuzz environment */
       
    36 	setenv("PYTHONUSERBASE", cpypath, 1);
       
    37 	Py_SetPythonHome(cpypath);
       
    38 	Py_InitializeEx(0);
       
    39 	mainmod = PyImport_AddModule("__main__");
       
    40 	globals = PyModule_GetDict(mainmod);
       
    41 	initparsers();
       
    42 }
       
    43 
       
    44 PyObject *pyglobals()
       
    45 {
       
    46 	return globals;
       
    47 }
       
    48 
       
    49 } // namespace contrib