forked from snoack/python-goto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoto.py
75 lines (60 loc) · 1.88 KB
/
goto.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import dis
import struct
import ctypes
import types
import itertools
_STRUCT = struct.Struct('<BHBHB')
_NOP = struct.pack('B', dis.opmap['NOP'])
if hasattr(lambda: 0, '__code__'):
_FUNC_CODE_ATTRIBUTE = '__code__' # PY3
else:
_FUNC_CODE_ATTRIBUTE = 'func_code' # PY2
def _make_code(code, codestring):
args = [
code.co_argcount, code.co_nlocals, code.co_stacksize,
code.co_flags, codestring, code.co_consts,
code.co_names, code.co_varnames, code.co_filename,
code.co_name, code.co_firstlineno, code.co_lnotab,
code.co_freevars, code.co_cellvars
]
try:
args.insert(1, code.co_kwonlyargcount) # PY3
except AttributeError:
pass
return types.CodeType(*args)
def _find_instructions(code, name):
for pos in itertools.count():
try:
op1, arg1, op2, arg2, op3 = _STRUCT.unpack_from(code.co_code, pos)
except struct.error:
break
if dis.opname[op1] not in ('LOAD_GLOBAL', 'LOAD_NAME'):
continue
if code.co_names[arg1] != name:
continue
if dis.opname[op2] != 'LOAD_ATTR':
continue
if dis.opname[op3] != 'POP_TOP':
continue
yield pos, arg2
def _inject_nop_sled(buf, offset):
for i in range(_STRUCT.size):
buf[offset + i] = _NOP
def _patch_code(code):
buf = ctypes.create_string_buffer(code.co_code, len(code.co_code))
labels = {}
for pos, arg in _find_instructions(code, 'label'):
_inject_nop_sled(buf, pos)
labels[arg] = pos + _STRUCT.size
for pos, arg in _find_instructions(code, 'goto'):
target = labels.get(arg)
if target is not None:
_inject_nop_sled(buf, pos)
struct.pack_into('<BH', buf, pos, dis.opmap['JUMP_ABSOLUTE'], target)
return _make_code(code, buf.raw)
def with_goto(func_or_code):
if isinstance(func_or_code, types.CodeType):
return _patch_code(func_or_code)
code = _patch_code(getattr(func_or_code, _FUNC_CODE_ATTRIBUTE))
setattr(func_or_code, _FUNC_CODE_ATTRIBUTE, code)
return func_or_code