Skip to content

Commit 4d3f42d

Browse files
committed
gh-143236: fix _PyEval_LoadName has use-after-free issue
1 parent cf6758f commit 4d3f42d

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

Lib/test/test_frame.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,31 @@ class C:
177177
self.clear_traceback_frames(exc.__traceback__)
178178
self.assertIs(None, wr())
179179

180+
@support.cpython_only
181+
def test_frame_clear_during_load_name(self):
182+
def get_frame():
183+
try:
184+
raise RuntimeError
185+
except RuntimeError as e:
186+
return e.__traceback__.tb_frame
187+
188+
frame = get_frame()
189+
190+
class Fuse(str):
191+
cleared = False
192+
__hash__ = str.__hash__
193+
def __eq__(self, other):
194+
if not Fuse.cleared and other == "boom":
195+
Fuse.cleared = True
196+
Fuse.frame.clear()
197+
return False
198+
return super().__eq__(other)
199+
200+
Fuse.frame = frame
201+
frame.f_locals[Fuse("boom")] = 0
202+
with self.assertRaises(NameError):
203+
exec("boom", {}, frame.f_locals)
204+
180205

181206
class FrameAttrsTest(unittest.TestCase):
182207

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a bug in :mod:`ceval` where the load name has use-after-free bug.

Python/ceval.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4061,9 +4061,17 @@ _PyEval_LoadName(PyThreadState *tstate, _PyInterpreterFrame *frame, PyObject *na
40614061
"no locals found");
40624062
return NULL;
40634063
}
4064-
if (PyMapping_GetOptionalItem(frame->f_locals, name, &value) < 0) {
4064+
4065+
PyObject *locals = frame->f_locals;
4066+
Py_INCREF(locals);
4067+
4068+
if (PyMapping_GetOptionalItem(locals, name, &value) < 0) {
4069+
Py_DECREF(locals);
40654070
return NULL;
40664071
}
4072+
4073+
Py_DECREF(locals);
4074+
40674075
if (value != NULL) {
40684076
return value;
40694077
}

0 commit comments

Comments
 (0)