/src/mercurial/contrib/fuzz/pyutil.cc
Line | Count | Source |
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 | 14 | { |
23 | 14 | #ifdef HG_FUZZER_PY3 |
24 | 14 | 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 | 14 | std::string selfpath(cselfpath); |
33 | 14 | std::string pypath; |
34 | 14 | auto pos = selfpath.rfind("/"); |
35 | 14 | if (pos == std::string::npos) { |
36 | 0 | char wd[8192]; |
37 | 0 | if (!getcwd(wd, 8192)) { |
38 | 0 | std::cerr << "Failed to call getcwd: errno " << errno |
39 | 0 | << std::endl; |
40 | 0 | exit(1); |
41 | 0 | } |
42 | 0 | pypath = std::string(wd) + subdir; |
43 | 14 | } else { |
44 | 14 | pypath = selfpath.substr(0, pos) + subdir; |
45 | 14 | } |
46 | 14 | strncpy(cpypath, pypath.c_str(), pypath.size()); |
47 | 14 | setenv("PYTHONPATH", cpypath, 1); |
48 | 14 | setenv("PYTHONNOUSERSITE", "1", 1); |
49 | | /* prevent Python from looking up users in the fuzz environment */ |
50 | 14 | setenv("PYTHONUSERBASE", cpypath, 1); |
51 | 14 | #ifdef HG_FUZZER_PY3 |
52 | 14 | std::wstring wcpypath(pypath.begin(), pypath.end()); |
53 | 14 | Py_SetPythonHome(wcpypath.c_str()); |
54 | | #else |
55 | | Py_SetPythonHome(cpypath); |
56 | | #endif |
57 | 14 | Py_InitializeEx(0); |
58 | 14 | mainmod = PyImport_AddModule("__main__"); |
59 | 14 | globals = PyModule_GetDict(mainmod); |
60 | | |
61 | 14 | #ifdef HG_FUZZER_PY3 |
62 | 14 | PyObject *mod = PyInit_parsers(); |
63 | | #else |
64 | | initparsers(); |
65 | | PyObject *mod = PyImport_ImportModule("parsers"); |
66 | | #endif |
67 | | |
68 | 14 | PyDict_SetItemString(globals, "parsers", mod); |
69 | 14 | } |
70 | | |
71 | | PyObject *pyglobals() |
72 | 2.58k | { |
73 | 2.58k | return globals; |
74 | 2.58k | } |
75 | | |
76 | | } // namespace contrib |