Debian Codegraph @

pypy/interpreter/test/apptest_with_leak.py

raw symbols SCIP
1 """Isolate the nested try/except+reraise sys.exc_info leak."""
2 import sys
3
4
5 def _clear():
6 # Force sys.exc_info to None before each test since apptest runs may have
7 # leaked state from pypy's own startup.
8 try:
9 raise Exception
10 except Exception:
11 pass
12 # Now sys.exc_info should be None if POP_EXCEPT works. If this itself
13 # leaks, the simplest case leaks.
14
15
16 def test_0_simplest_clear():
17 _clear()
18 # If the basic try/except/pass does not restore, EVERYTHING leaks.
19 assert sys.exc_info() == (None, None, None), sys.exc_info()
20
21
22 def test_E_nested_bare_except():
23 _clear()
24 try:
25 try:
26 raise ImportError("original")
27 except ImportError:
28 raise ValueError("new")
29 except ValueError:
30 pass
31 assert sys.exc_info() == (None, None, None), sys.exc_info()
32
33
34 def test_F_nested_as_name():
35 _clear()
36 try:
37 try:
38 raise ImportError("original")
39 except ImportError as e:
40 raise ValueError(str(e))
41 except ValueError:
42 pass
43 assert sys.exc_info() == (None, None, None), sys.exc_info()
44
45
46 def test_G_flat_try_except_pass():
47 _clear()
48 try:
49 raise ImportError("single")
50 except ImportError:
51 pass
52 assert sys.exc_info() == (None, None, None), sys.exc_info()
53
54
55 def test_inner_with_exit_raises_suppressed_by_outer():
56 # Inner CM's __exit__ raises; try/except doesn't match;
57 # outer CM's __exit__ suppresses. Nothing should escape.
58 class InnerCM:
59 def __enter__(self): return None
60 def __exit__(self, *args):
61 raise OSError("Cannot close")
62
63 class OuterCM:
64 def __init__(self): self.exited_with = None
65 def __enter__(self): return None
66 def __exit__(self, *args):
67 self.exited_with = args[0]
68 return True # suppress
69
70 outer = OuterCM()
71 with outer:
72 try:
73 with InnerCM():
74 raise AttributeError("body error")
75 except IsADirectoryError:
76 pass
77 assert outer.exited_with is OSError, outer.exited_with
78
79
80 def test_shutil_pattern():
81 # Reproduce the shutil.copyfile failure.
82 # Multiple early returns inside the inner with cause duplicate_exits_without_lineno
83 # to copy the with-exit code, which confuses the linear exception table scan and
84 # leaves the fallback path (copyfileobj) with no exception table coverage.
85 # Structure mirrors shutil.copyfile:
86 # outer with (suppresses) -> try/except -> inner with (raises in __exit__)
87 # -> fast paths with early returns -> fallback that raises via None return
88 class InnerCM:
89 def __enter__(self):
90 return None # intentional -- fallback body raises AttributeError
91 def __exit__(self, exc_type, exc_val, exc_tb):
92 if exc_type is not None:
93 raise OSError("dest close failed")
94 return False
95
96 class OuterCM:
97 exited_with = 'not called'
98 def __enter__(self): return self
99 def __exit__(self, exc_type, exc_val, exc_tb):
100 self.exited_with = exc_type
101 return True # suppress everything
102
103 class GiveupOnFastCopy(Exception):
104 pass
105
106 def copyfile(use_fast1, use_fast2):
107 result = []
108 outer = OuterCM()
109 with outer:
110 try:
111 with InnerCM() as f:
112 if use_fast1:
113 try:
114 result.append('fast1')
115 return result
116 except GiveupOnFastCopy:
117 pass
118 elif use_fast2:
119 try:
120 result.append('fast2')
121 return result
122 except GiveupOnFastCopy:
123 pass
124 # fallback: f is None, raises AttributeError
125 result.append(f.read)
126 except IsADirectoryError:
127 pass
128 return outer
129
130 import dis
131 dis.dis(copyfile)
132
133 # Fast paths exit normally -- outer/inner __exit__(None,None,None) not raising.
134 assert copyfile(True, False) == ['fast1']
135 assert copyfile(False, True) == ['fast2']
136
137 # Fallback path: f.read raises AttributeError, inner __exit__ raises OSError,
138 # outer __exit__ should suppress OSError and copyfile returns outer.
139 outer_result = copyfile(False, False)
140 assert isinstance(outer_result, OuterCM), outer_result
141 assert outer_result.exited_with is OSError, repr(outer_result.exited_with)
142
143
144 def test_lru_cache_style_with_lock_exception():
145 # Reproduces WITH_EXCEPT_START crash: a wrapper using 'with lock:' around a
146 # cache lookup where the wrapped function raises between the two with-blocks.
147 import dis
148 from _thread import RLock
149
150 def make_cached(user_function):
151 cache = {}
152 lock = RLock()
153
154 def wrapper(*args):
155 key = args
156 with lock:
157 if key in cache:
158 return cache[key]
159 result = user_function(*args)
160 with lock:
161 cache[key] = result
162 return result
163
164 return wrapper
165
166 @make_cached
167 def func(i):
168 return 'abc'[i]
169
170 dis.dis(func) # dis the wrapper to aid debugging
171
172 assert func(0) == 'a'
173 try:
174 func(15)
175 except IndexError:
176 pass
177 else:
178 assert False, "expected IndexError"
179
180
181 def test_lru_cache_exception_no_context():
182 # test_functools.TestLRU.test_lru_with_exceptions: exception raised between
183 # the two 'with lock:' blocks must not gain __context__ from lock cleanup.
184 import dis
185 from _thread import RLock
186
187 def make_cached(user_function):
188 cache = {}
189 lock = RLock()
190
191 def wrapper(*args):
192 key = args
193 with lock:
194 if key in cache:
195 return cache[key]
196 result = user_function(*args)
197 with lock:
198 cache[key] = result
199 return result
200
201 return wrapper
202
203 @make_cached
204 def func(i):
205 return 'abc'[i]
206
207 print("\n=== apptest double-with wrapper dis ===")
208 dis.dis(func)
209
210 assert func(0) == 'a'
211
212 try:
213 func(15)
214 except IndexError as e:
215 assert e.__context__ is None, repr(e.__context__)
216 else:
217 assert False, "expected IndexError"
218
219 # failed call must not be cached
220 try:
221 func(15)
222 except IndexError:
223 pass
224 else:
225 assert False, "expected IndexError on second call"
226
227
228 def test_except_pass_around_lru_style_exception():
229 # typing.py inner() pattern: try: return cached(...) except TypeError: pass
230 # then raise ValueError. The ValueError must have no __context__ from the
231 # suppressed TypeError caught inside the two-with-lock wrapper.
232 import dis
233 from _thread import RLock
234
235 def make_cached(user_function):
236 cache = {}
237 lock = RLock()
238
239 def wrapper(*args):
240 key = args
241 with lock:
242 if key in cache:
243 return cache[key]
244 result = user_function(*args)
245 with lock:
246 cache[key] = result
247 return result
248
249 return wrapper
250
251 @make_cached
252 def cached(x):
253 if x < 0:
254 raise TypeError("bad arg")
255 return x
256
257 def inner(x):
258 try:
259 return cached(x)
260 except TypeError:
261 pass
262 raise ValueError("fallback error")
263
264 print("\n=== apptest cached wrapper dis ===")
265 dis.dis(cached)
266 print("\n=== apptest inner dis ===")
267 dis.dis(inner)
268
269 try:
270 inner(-1)
271 except ValueError as e:
272 assert e.__context__ is None, repr(e.__context__)
273 except TypeError:
274 assert False, "TypeError should have been caught by inner"
275 else:
276 assert False, "expected ValueError"