forked from lrq3000/bytecode-hack
/
test_bytecode_tracer.py
490 lines (437 loc) · 17.8 KB
/
test_bytecode_tracer.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import cPickle
import dis
import os
import shutil
import sys
import tempfile
from nose import SkipTest
from nose.tools import assert_equal
from pythoscope.store import CodeTree
from pythoscope.util import write_content_to_file
from bytecode_tracer import BytecodeTracer, rewrite_function
return_value = None
class TestBytecodeTracer:
def setup(self):
self._traces = []
self.btracer = BytecodeTracer()
def _trace(self, frame, event, arg):
try:
if arg is not sys.settrace:
for ret in self.btracer.trace(frame, event):
if ret[0] is not None:
self._traces.append(ret)
except TypeError:
pass
return self._trace
def assert_trace(self, *traces):
assert_equal(self._traces, list(traces))
def assert_trace_slice(self, start, end, *traces):
assert_equal(self._traces[start:end], list(traces))
def trace_function(self, fun):
dis.dis(fun.func_code)
rewrite_function(fun)
self.btracer.setup()
sys.settrace(self._trace)
try:
fun()
finally:
sys.settrace(None)
self.btracer.teardown()
class TestBytecodeTracerWithDifferentArgumentsCombinations(TestBytecodeTracer):
def test_traces_builtin_functions_with_no_arguments(self):
def fun():
list()
self.trace_function(fun)
self.assert_trace(('c_call', (list, [], {})),
('c_return', []))
def test_traces_builtin_functions_with_single_argument(self):
def fun():
repr(4)
self.trace_function(fun)
self.assert_trace(('c_call', (repr, [4], {})),
('c_return', "4"))
def test_traces_builtin_functions_with_two_arguments(self):
def fun():
pow(2, 3)
self.trace_function(fun)
self.assert_trace(('c_call', (pow, [2, 3], {})),
('c_return', 8))
def test_traces_builtin_functions_with_keyword_argument(self):
def fun():
global return_value
return_value = property(doc="asdf")
self.trace_function(fun)
self.assert_trace(('c_call', (property, [], {'doc': "asdf"})),
('c_return', return_value))
def test_traces_builtin_functions_with_varargs(self):
def fun():
x = [1, 10]
range(*x)
self.trace_function(fun)
self.assert_trace(('c_call', (range, [1, 10], {})),
('c_return', [1, 2, 3, 4, 5, 6, 7, 8, 9]))
def test_traces_builtin_functions_with_kwargs(self):
def fun():
z = {'real': 1, 'imag': 2}
complex(**z)
self.trace_function(fun)
self.assert_trace(('c_call', (complex, [], {'real': 1, 'imag': 2})),
('c_return', complex(1, 2)))
def test_traces_builtin_functions_with_keyword_and_kwargs(self):
def fun():
z = {'imag': 2}
complex(real=1, **z)
self.trace_function(fun)
self.assert_trace(('c_call', (complex, [], {'real': 1, 'imag': 2})),
('c_return', complex(1, 2)))
def test_traces_builtin_functions_with_keyword_and_varargs(self):
def fun():
a = (1,)
complex(imag=2, *a)
self.trace_function(fun)
self.assert_trace(('c_call', (complex, [1], {'imag': 2})),
('c_return', complex(1, 2)))
def test_traces_builtin_functions_with_both_varargs_and_kwargs(self):
def fun():
a = ("asdf", "ascii")
k = {'errors': 'ignore'}
unicode(*a, **k)
self.trace_function(fun)
self.assert_trace(('c_call', (unicode, ["asdf", "ascii"], {'errors': 'ignore'})),
('c_return', unicode('asdf')))
def test_traces_builtin_functions_with_keyword_varargs_and_kwargs(self):
def fun():
a = ("asdf",)
k = {'encoding': 'ascii'}
unicode(errors='ignore', *a, **k)
self.trace_function(fun)
self.assert_trace(('c_call', (unicode, ["asdf"], {'encoding': 'ascii', 'errors': 'ignore'})),
('c_return', unicode('asdf')))
def test_traces_builtin_functions_with_positional_argument_and_kwargs(self):
def fun():
z = {'imag': 2}
complex(1, **z)
self.trace_function(fun)
self.assert_trace(('c_call', (complex, [1], {'imag': 2})),
('c_return', complex(1, 2)))
def test_traces_builtin_functions_with_positional_argument_and_varargs(self):
def fun():
global return_value
a = ("", 'eval')
return_value = compile("1", *a)
self.trace_function(fun)
self.assert_trace(('c_call', (compile, ["1", "", 'eval'], {})),
('c_return', return_value))
def test_traces_builtin_functions_with_positional_argument_varargs_and_kwargs(self):
def fun():
a = ('ascii',)
k = {'errors': 'ignore'}
unicode("asdf", *a, **k)
self.trace_function(fun)
self.assert_trace(('c_call', (unicode, ["asdf", "ascii"], {'errors': 'ignore'})),
('c_return', unicode('asdf')))
def test_traces_builtin_functions_with_positional_argument_and_keyword_argument(self):
def fun():
unicode("asdf", "ascii", errors='ignore')
self.trace_function(fun)
self.assert_trace(('c_call', (unicode, ["asdf", "ascii"], {'errors': 'ignore'})),
('c_return', unicode('asdf')))
def test_traces_builtin_functions_with_positional_argument_and_keyword_and_kwargs(self):
def fun():
k = {'errors': 'ignore'}
unicode("asdf", encoding='ascii', **k)
self.trace_function(fun)
self.assert_trace(('c_call', (unicode, ["asdf"], {'encoding': 'ascii', 'errors': 'ignore'})),
('c_return', unicode('asdf')))
def test_traces_builtin_functions_with_positional_argument_and_keyword_and_varargs(self):
def fun():
a = ("ascii",)
unicode("asdf", errors='ignore', *a)
self.trace_function(fun)
self.assert_trace(('c_call', (unicode, ["asdf", "ascii"], {'errors': 'ignore'})),
('c_return', unicode('asdf')))
def test_traces_builtin_functions_with_positional_argument_and_keyword_and_varargs_and_kwargs(self):
def fun():
global return_value
a = (1,)
k = {'doc': ""}
return_value = property(2, fdel=3, *a, **k)
self.trace_function(fun)
self.assert_trace(('c_call', (property, [2, 1], {'fdel': 3, 'doc': ""})),
('c_return', return_value))
class TestBytecodeTracerReturnValues(TestBytecodeTracer):
def test_traces_builtin_functions_returning_multiple_values(self):
def fun():
coerce(1, 1.25)
self.trace_function(fun)
self.assert_trace(('c_call', (coerce, [1, 1.25], {})),
('c_return', (1.0, 1.25)))
class TestBytecodeTracerLanguageConstructs(TestBytecodeTracer):
def test_traces_for_loop(self):
def fun():
for x in range(3):
complex(0, x)
self.trace_function(fun)
self.assert_trace(('c_call', (range, [3], {})),
('c_return', [0, 1, 2]),
('c_call', (complex, [0, 0], {})),
('c_return', complex(0, 0)),
('c_call', (complex, [0, 1], {})),
('c_return', complex(0, 1)),
('c_call', (complex, [0, 2], {})),
('c_return', complex(0, 2)))
def test_traces_for_loop_with_an_iterator_continue_and_else(self):
def fun():
global return_value
return_value = xrange(5)
for x in return_value:
if x < 3:
continue
chr(97+x)
else:
complex(2, 3)
self.trace_function(fun)
self.assert_trace(('c_call', (xrange, [5], {})),
('c_return', return_value),
('c_call', (chr, [100], {})),
('c_return', 'd'),
('c_call', (chr, [101], {})),
('c_return', 'e'),
('c_call', (complex, [2, 3], {})),
('c_return', complex(2, 3)))
def test_traces_chained_calls(self):
def fun():
complex(sum(range(1,11)), 3)
self.trace_function(fun)
self.assert_trace(('c_call', (range, [1, 11], {})),
('c_return', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
('c_call', (sum, [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], {})),
('c_return', 55),
('c_call', (complex, [55, 3], {})),
('c_return', complex(55, 3)))
def test_traces_chained_calls_with_extra_computation(self):
def fun():
range(sum([1, 2]) + 3)
self.trace_function(fun)
self.assert_trace(('c_call', (sum, [[1, 2]], {})),
('c_return', 3),
('c_call', (range, [6], {})),
('c_return', [0, 1, 2, 3, 4, 5]))
def test_traces_with_blocks(self):
if sys.version_info < (2, 5):
raise SkipTest("with statement was added in Python 2.5")
code = "from __future__ import with_statement; import threading; lock = threading.Lock()\nwith lock: chr(102)"
def fun():
eval(compile(code, '<string>', 'exec'))
self.trace_function(fun)
# Skip compile, eval, and lock allocation.
self.assert_trace_slice(7, -1,
('c_call', (chr, [102], {})),
('c_return', 'f'))
class TestBytecodeTracerWithExceptions(TestBytecodeTracer):
def test_keeps_tracing_properly_after_an_exception(self):
def fun():
try:
chr(256)
except ValueError:
pass
chr(90)
self.trace_function(fun)
self.assert_trace(('c_call', (chr, [256], {})),
('c_call', (chr, [90], {})),
('c_return', 'Z'))
def test_keeps_tracing_properly_after_no_arguments_exception(self):
def fun():
try:
abs()
except TypeError:
pass
chr(65)
self.trace_function(fun)
self.assert_trace(('c_call', (abs, [], {})),
('c_call', (chr, [65], {})),
('c_return', 'A'))
def test_keeps_tracing_properly_after_bad_arguments_exception(self):
def fun():
try:
abs("a")
except TypeError:
pass
chr(97)
self.trace_function(fun)
self.assert_trace(('c_call', (abs, ["a"], {})),
('c_call', (chr, [97], {})),
('c_return', 'a'))
def test_keeps_tracing_properly_after_not_callable_is_passed_when_it_was_expected(self):
def fun():
try:
map(1, [2, 3])
except TypeError: # 'int' object is not callable
pass
chr(66)
self.trace_function(fun)
self.assert_trace(('c_call', (map, [1, [2, 3]], {})),
('c_call', (chr, [66], {})),
('c_return', 'B'))
def test_keeps_tracing_properly_after_exception_in_callback_code(self):
def bad(x):
if x > 0:
raise ValueError
def fun():
try:
map(bad, [0, 1, 2])
except ValueError:
pass
chr(67)
self.trace_function(fun)
self.assert_trace(('c_call', (map, [bad, [0, 1, 2]], {})),
('c_call', (chr, [67], {})),
('c_return', 'C'))
def test_keeps_tracing_finally_block_after_an_exception(self):
def fun():
try:
try:
raise AttributeError
except AttributeError:
pass
finally:
chr(68)
self.trace_function(fun)
self.assert_trace(('c_call', (chr, [68], {})),
('c_return', 'D'))
def test_keeps_tracing_except_block_after_an_exception(self):
def fun():
try:
raise NameError
except NameError:
complex(1, 2)
self.trace_function(fun)
self.assert_trace(('c_call', (complex, [1, 2], {})),
('c_return', complex(1, 2)))
class TestPrint(TestBytecodeTracer):
def test_handles_normal_print_with_newline(self):
def fun():
print "foo"
self.trace_function(fun)
self.assert_trace(('print', "foo"),
('print', os.linesep))
def test_handles_normal_print_without_newline(self):
def fun():
print "foo",
self.trace_function(fun)
self.assert_trace(('print', "foo"))
def test_handles_extended_print_with_newline(self):
def fun():
print>>sys.stdout, "foo"
self.trace_function(fun)
self.assert_trace(('print_to', ("foo", sys.stdout)),
('print_to', (os.linesep, sys.stdout)))
def test_handles_extended_print_without_newline(self):
def fun():
print>>sys.stdout, "foo",
self.trace_function(fun)
self.assert_trace(('print_to', ("foo", sys.stdout)))
class TestBytecodeTracerAutomaticRewriting(TestBytecodeTracer):
def test_automatically_traces_bytecodes_of_other_callables_being_called(self):
def other():
abs(-2)
def fun():
other()
self.trace_function(fun)
self.assert_trace(('c_call', (abs, [-2], {})),
('c_return', 2))
def test_handles_python_functions_called_from_within_c_functions(self):
def other(x):
return x + 1
def fun():
map(other, [1, 2, 3])
self.trace_function(fun)
self.assert_trace(('c_call', (map, [other, [1, 2, 3]], {})),
('c_return', [2, 3, 4]))
def test_handles_c_function_called_from_python_functions_called_from_c_functions(self):
def other(x):
return abs(x)
def fun():
map(other, [-1, 0, 1])
self.trace_function(fun)
self.assert_trace(('c_call', (map, [other, [-1, 0, 1]], {})),
('c_call', (abs, [-1], {})),
('c_return', 1),
('c_call', (abs, [0], {})),
('c_return', 0),
('c_call', (abs, [1], {})),
('c_return', 1),
('c_return', [1, 0, 1]))
def test_rewrites_each_function_only_once(self):
def other():
pass
def fun():
other()
other()
rewrite_function(other)
rewritten_code = other.func_code
self.trace_function(fun)
assert other.func_code is rewritten_code
def test_rewrites_code_returned_by_compile(self):
def fun():
global return_value
return_value = compile('abs(-1)', '', 'exec')
eval(return_value)
self.trace_function(fun)
self.assert_trace(('c_call', (compile, ['abs(-1)', '', 'exec'], {})),
('c_return', return_value),
('c_call', (eval, [return_value], {})),
('c_call', (abs, [-1], {})),
('c_return', 1),
('c_return', None))
def test_rewrites_modules_during_import(self):
tmpdir = tempfile.mkdtemp()
write_content_to_file("abs(-2)", os.path.join(tmpdir, 'mod.py'))
sys.path.insert(0, tmpdir)
try:
def fun():
import mod
self.trace_function(fun)
self.assert_trace(('c_call', (abs, [-2], {})),
('c_return', 2))
finally:
shutil.rmtree(tmpdir)
def test_handles_methods(self):
class Class:
def method(self, x):
return abs(x)
def fun():
global return_value
return_value = c = Class()
c.method(-1)
self.trace_function(fun)
self.assert_trace(('c_call', (Class, [], {})),
('c_return', return_value),
('c_call', (abs, [-1], {})),
('c_return', 1))
class TestRewriteFunction:
def test_handles_functions_with_free_variables(self):
x = 1
def fun():
return x + 1
rewrite_function(fun)
assert_equal(fun(), 2)
def test_handles_bound_methods(self):
class Class:
def method(self, x):
return x + 1
meth = Class().method
rewrite_function(meth)
assert_equal(meth(1), 2)
class TestImportSupportWithOtherModules(TestBytecodeTracer):
def test_support_with_pickle(self):
self.btracer.setup()
self.btracer.teardown()
# This can raise any number of exceptions.
#
# Under Python 2.3 with imputil it will raise
# PicklingError: Can't pickle <class 'pythoscope.store.CodeTree'>: attribute lookup pythoscope.store.CodeTree failed
#
# Under Python 2.6 with imputil it will raise
# TypeError: _import_hook() takes at most 5 arguments (6 given)
cPickle.dumps(CodeTree(None), cPickle.HIGHEST_PROTOCOL)