This repository was archived by the owner on Oct 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathpython-interposer.c
More file actions
51 lines (42 loc) · 1.6 KB
/
python-interposer.c
File metadata and controls
51 lines (42 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <Python.h>
#include <dlfcn.h>
typedef void (*orig_Py_Finalize_type)();
typedef PyThreadState* (*orig_Py_NewInterpreter_type)();
typedef void (*orig_Py_EndInterpreter_type)(PyThreadState *tstate);
int interpreter_count = 0;
PyThreadState *Py_NewInterpreter() {
#ifdef DEBUG
fprintf(stderr, "Py_NewInterpreter called with %d sub-interpreters already present\n", interpreter_count);
#endif
interpreter_count++;
orig_Py_NewInterpreter_type orig_Py_NewInterpreter = (orig_Py_NewInterpreter_type)dlsym(RTLD_NEXT,"Py_NewInterpreter");
if(orig_Py_NewInterpreter == NULL) {
fprintf(stderr, "Error loading from SO %s\n", dlerror());
exit(1);
}
return orig_Py_NewInterpreter();
}
void Py_EndInterpreter(PyThreadState *tstate) {
interpreter_count--;
orig_Py_EndInterpreter_type orig_Py_EndInterpreter = (orig_Py_EndInterpreter_type)dlsym(RTLD_NEXT,"Py_EndInterpreter");
if(orig_Py_EndInterpreter == NULL) {
fprintf(stderr, "Error loading from SO: %s\n", dlerror());
exit(1);
}
#ifdef DEBUG
fprintf(stderr, "Py_EndInterpreter called with %d sub-interpreters remaining\n", interpreter_count);
#endif
return orig_Py_EndInterpreter(tstate);
}
void Py_Finalize() {
orig_Py_Finalize_type orig_Py_Finalize = (orig_Py_Finalize_type)dlsym(RTLD_NEXT,"Py_Finalize");
if(orig_Py_Finalize == NULL) {
fprintf(stderr, "Error loading from SO: %s\n", dlerror());
exit(1);
}
#ifdef DEBUG
fprintf(stderr, "Py_Finalize called with %d sub-interpreters\n", interpreter_count);
#endif
if(interpreter_count == 0)
orig_Py_Finalize();
}