-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdict_research.py
57 lines (50 loc) · 2.12 KB
/
dict_research.py
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
52
53
54
55
56
57
from asm_hook import hook
from native_ctypes import PyTypeObject
from ctypes import *
from _ctypes import PyObj_FromPtr
dict_struct = PyTypeObject.from_address(id(dict))
_FuncPtr = type(pythonapi.Py_IncRef)
dict_new = _FuncPtr(dict_struct.tp_new)
dict_init = _FuncPtr(dict_struct.tp_init)
dict_vectorcall = _FuncPtr(dict_struct.tp_vectorcall)
def protect(func):
def new_func(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
return builtinexc(e, 1)
return new_func
def builtinexc(exc, level=0):
frame = sys._getframe(2 + level)
mem = getmem(id(frame.f_code.co_code) + bytes.__basicsize__ - 1, len(frame.f_code.co_code))
mem[frame.f_lasti + 2:frame.f_lasti + 4] = bytes([dis.opmap['RAISE_VARARGS'], 1])
return exc
@hook(dict_init, restype=c_int, argtypes=[py_object, c_void_p, c_void_p])
@protect
def hooked_dict_init(self, args, kwargs):
print('dict_init called',
'\n\targs:', PyObj_FromPtr(args) if args else 'NULL',
'\n\tkwargs:', PyObj_FromPtr(kwargs) if kwargs else 'NULL')
return dict_init(self, args, kwargs)
@hook(dict_new, restype=py_object, argtypes=[py_object, c_void_p, c_void_p])
@protect
def hooked_dict_new(typ, args, kwargs):
print('dict_new called',
'\n\targs:', PyObj_FromPtr(args) if args else 'NULL',
'\n\tkwargs:', PyObj_FromPtr(kwargs) if kwargs else 'NULL')
return dict_new(typ, args, kwargs)
@hook(pythonapi._PyDict_NewPresized, restype=py_object, argtypes=[c_ssize_t])
@protect
def hooked__PyDict_NewPresized(size):
print('_PyDict_NewPresized called',
'\n\tsize:', size)
return pythonapi._PyDict_NewPresized(size)
@hook(dict_vectorcall, restype=py_object, argtypes=[py_object, POINTER(py_object), c_size_t, c_void_p])
@protect
def hooked_dict_vectorcall(typ, argv, argcf, kwnames):
argc = argcf & ~(1 << (8 * sizeof(c_size_t) - 1))
args = argv[:argc]
print('dict_vectorcall',
'\n\targs:', args,
'\n\tkwargs:', {key:argv[argc + idx] for idx, key in enumerate(PyObj_FromPtr(kwnames))} if kwnames else 'NULL')
return dict_vectorcall(typ, argv, argc, kwnames)