Debian Codegraph @

rpython/tool/leakfinder.py

raw symbols SCIP
1 import sys, gc
2 try:
3 import cStringIO
4 except ImportError as e:
5 if sys.version_info.major > 2:
6 raise RuntimeError('use python 2 to run tests')
7 raise
8 import traceback
9
10 # Track allocations to detect memory leaks.
11 # So far, this is used for lltype.malloc(flavor='raw').
12 TRACK_ALLOCATIONS = False
13 ALLOCATED = {}
14
15 class MallocMismatch(Exception):
16 def __str__(self):
17 dict = self.args[0]
18 dict2 = {}
19 for obj, traceback in dict.items():
20 traceback = traceback.splitlines()
21 if len(traceback) > 8:
22 traceback = [' ...'] + traceback[-6:]
23 traceback = '\n'.join(traceback)
24 dict2.setdefault(traceback, [])
25 dict2[traceback].append(obj)
26 lines = ['{']
27 for traceback, objs in dict2.items():
28 lines.append('')
29 for obj in objs:
30 lines.append('%s:' % (obj,))
31 lines.append(traceback)
32 lines.append('}')
33 return '\n'.join(lines)
34
35 def start_tracking_allocations():
36 global TRACK_ALLOCATIONS
37 if TRACK_ALLOCATIONS:
38 result = ALLOCATED.copy() # nested start
39 else:
40 result = None
41 TRACK_ALLOCATIONS = True
42 ALLOCATED.clear()
43 return result
44
45 def stop_tracking_allocations(check, prev=None, do_collection=gc.collect):
46 global TRACK_ALLOCATIONS
47 assert TRACK_ALLOCATIONS
48 for i in range(5):
49 if not ALLOCATED:
50 break
51 do_collection()
52 result = ALLOCATED.copy()
53 ALLOCATED.clear()
54 if prev is None:
55 TRACK_ALLOCATIONS = False
56 else:
57 ALLOCATED.update(prev)
58 if check and result:
59 raise MallocMismatch(result)
60 return result
61
62 def remember_malloc(obj, framedepth=1):
63 if TRACK_ALLOCATIONS:
64 frame = sys._getframe(framedepth)
65 sio = cStringIO.StringIO()
66 traceback.print_stack(frame, limit=10, file=sio)
67 tb = sio.getvalue()
68 ALLOCATED[obj] = tb
69
70 def remember_free(obj):
71 if TRACK_ALLOCATIONS:
72 if obj not in ALLOCATED:
73 # rehashing is needed because some objects' hash may change
74 # e.g. when lltype objects are turned into <C object>
75 items = ALLOCATED.items()
76 ALLOCATED.clear()
77 ALLOCATED.update(items)
78 del ALLOCATED[obj]