Debian Codegraph @

lib-python/3/test/libregrtest/refleak.py

raw symbols SCIP
1 import sys
2 import warnings
3 from inspect import isabstract
4 from typing import Any
5
6 from test import support
7 from test.support import os_helper
8
9 from .runtests import HuntRefleak
10 from .utils import clear_caches
11
12 try:
13 from _abc import _get_dump
14 except ImportError:
15 import weakref
16
17 def _get_dump(cls):
18 # Reimplement _get_dump() for pure-Python implementation of
19 # the abc module (Lib/_py_abc.py)
20 registry_weakrefs = set(weakref.ref(obj) for obj in cls._abc_registry)
21 return (registry_weakrefs, cls._abc_cache,
22 cls._abc_negative_cache, cls._abc_negative_cache_version)
23
24
25 def runtest_refleak(test_name, test_func,
26 hunt_refleak: HuntRefleak,
27 quiet: bool):
28 """Run a test multiple times, looking for reference leaks.
29
30 Returns:
31 False if the test didn't leak references; True if we detected refleaks.
32 """
33 # This code is hackish and inelegant, but it seems to do the job.
34 import copyreg
35 import collections.abc
36
37 if not hasattr(sys, 'gettotalrefcount'):
38 raise Exception("Tracking reference leaks requires a debug build "
39 "of Python")
40
41 # Avoid false positives due to various caches
42 # filling slowly with random data:
43 warm_caches()
44
45 # Save current values for dash_R_cleanup() to restore.
46 fs = warnings.filters[:]
47 ps = copyreg.dispatch_table.copy()
48 pic = sys.path_importer_cache.copy()
49 zdc: dict[str, Any] | None
50 try:
51 import zipimport
52 except ImportError:
53 zdc = None # Run unmodified on platforms without zipimport support
54 else:
55 # private attribute that mypy doesn't know about:
56 zdc = zipimport._zip_directory_cache.copy() # type: ignore[attr-defined]
57 abcs = {}
58 for abc in [getattr(collections.abc, a) for a in collections.abc.__all__]:
59 if not isabstract(abc):
60 continue
61 for obj in abc.__subclasses__() + [abc]:
62 abcs[obj] = _get_dump(obj)[0]
63
64 # bpo-31217: Integer pool to get a single integer object for the same
65 # value. The pool is used to prevent false alarm when checking for memory
66 # block leaks. Fill the pool with values in -1000..1000 which are the most
67 # common (reference, memory block, file descriptor) differences.
68 int_pool = {value: value for value in range(-1000, 1000)}
69 def get_pooled_int(value):
70 return int_pool.setdefault(value, value)
71
72 warmups = hunt_refleak.warmups
73 runs = hunt_refleak.runs
74 filename = hunt_refleak.filename
75 repcount = warmups + runs
76
77 # Pre-allocate to ensure that the loop doesn't allocate anything new
78 rep_range = list(range(repcount))
79 rc_deltas = [0] * repcount
80 alloc_deltas = [0] * repcount
81 fd_deltas = [0] * repcount
82 getallocatedblocks = sys.getallocatedblocks
83 gettotalrefcount = sys.gettotalrefcount
84 fd_count = os_helper.fd_count
85 # initialize variables to make pyflakes quiet
86 rc_before = alloc_before = fd_before = 0
87
88 if not quiet:
89 print("beginning", repcount, "repetitions. Showing number of leaks "
90 "(. for 0 or less, X for 10 or more)",
91 file=sys.stderr)
92 numbers = ("1234567890"*(repcount//10 + 1))[:repcount]
93 numbers = numbers[:warmups] + ':' + numbers[warmups:]
94 print(numbers, file=sys.stderr, flush=True)
95
96 results = None
97 dash_R_cleanup(fs, ps, pic, zdc, abcs)
98 support.gc_collect()
99
100 for i in rep_range:
101 results = test_func()
102
103 dash_R_cleanup(fs, ps, pic, zdc, abcs)
104 support.gc_collect()
105
106 # Read memory statistics immediately after the garbage collection.
107 alloc_after = getallocatedblocks()
108 rc_after = gettotalrefcount()
109 fd_after = fd_count()
110
111 rc_deltas[i] = get_pooled_int(rc_after - rc_before)
112 alloc_deltas[i] = get_pooled_int(alloc_after - alloc_before)
113 fd_deltas[i] = get_pooled_int(fd_after - fd_before)
114
115 if not quiet:
116 # use max, not sum, so total_leaks is one of the pooled ints
117 total_leaks = max(rc_deltas[i], alloc_deltas[i], fd_deltas[i])
118 if total_leaks <= 0:
119 symbol = '.'
120 elif total_leaks < 10:
121 symbol = (
122 '.', '1', '2', '3', '4', '5', '6', '7', '8', '9',
123 )[total_leaks]
124 else:
125 symbol = 'X'
126 if i == warmups:
127 print(' ', end='', file=sys.stderr, flush=True)
128 print(symbol, end='', file=sys.stderr, flush=True)
129 del total_leaks
130 del symbol
131
132 alloc_before = alloc_after
133 rc_before = rc_after
134 fd_before = fd_after
135
136 if not quiet:
137 print(file=sys.stderr)
138
139 # These checkers return False on success, True on failure
140 def check_rc_deltas(deltas):
141 # Checker for reference counters and memory blocks.
142 #
143 # bpo-30776: Try to ignore false positives:
144 #
145 # [3, 0, 0]
146 # [0, 1, 0]
147 # [8, -8, 1]
148 #
149 # Expected leaks:
150 #
151 # [5, 5, 6]
152 # [10, 1, 1]
153 return all(delta >= 1 for delta in deltas)
154
155 def check_fd_deltas(deltas):
156 return any(deltas)
157
158 failed = False
159 for deltas, item_name, checker in [
160 (rc_deltas, 'references', check_rc_deltas),
161 (alloc_deltas, 'memory blocks', check_rc_deltas),
162 (fd_deltas, 'file descriptors', check_fd_deltas)
163 ]:
164 # ignore warmup runs
165 deltas = deltas[warmups:]
166 failing = checker(deltas)
167 suspicious = any(deltas)
168 if failing or suspicious:
169 msg = '%s leaked %s %s, sum=%s' % (
170 test_name, deltas, item_name, sum(deltas))
171 print(msg, end='', file=sys.stderr)
172 if failing:
173 print(file=sys.stderr, flush=True)
174 with open(filename, "a", encoding="utf-8") as refrep:
175 print(msg, file=refrep)
176 refrep.flush()
177 failed = True
178 else:
179 print(' (this is fine)', file=sys.stderr, flush=True)
180 return (failed, results)
181
182
183 def dash_R_cleanup(fs, ps, pic, zdc, abcs):
184 import copyreg
185 import collections.abc
186
187 # Restore some original values.
188 warnings.filters[:] = fs
189 copyreg.dispatch_table.clear()
190 copyreg.dispatch_table.update(ps)
191 sys.path_importer_cache.clear()
192 sys.path_importer_cache.update(pic)
193 try:
194 import zipimport
195 except ImportError:
196 pass # Run unmodified on platforms without zipimport support
197 else:
198 zipimport._zip_directory_cache.clear()
199 zipimport._zip_directory_cache.update(zdc)
200
201 # Clear ABC registries, restoring previously saved ABC registries.
202 # ignore deprecation warning for collections.abc.ByteString
203 abs_classes = [getattr(collections.abc, a) for a in collections.abc.__all__]
204 abs_classes = filter(isabstract, abs_classes)
205 for abc in abs_classes:
206 for obj in abc.__subclasses__() + [abc]:
207 for ref in abcs.get(obj, set()):
208 if ref() is not None:
209 obj.register(ref())
210 obj._abc_caches_clear()
211
212 # Clear caches
213 clear_caches()
214
215 # Clear type cache at the end: previous function calls can modify types
216 sys._clear_type_cache()
217
218
219 def warm_caches():
220 # char cache
221 s = bytes(range(256))
222 for i in range(256):
223 s[i:i+1]
224 # unicode cache
225 [chr(i) for i in range(256)]
226 # int cache
227 list(range(-5, 257))