Skip to content

Commit 6e68559

Browse files
authored
[3.12] gh-123083: Fix a potential use-after-free in ``STORE_ATTR_WITH… (#123237)
[3.12] gh-123083: Fix a potential use-after-free in ``STORE_ATTR_WITH_HINT`` (gh-123092) (cherry picked from commit 297f2e0)
1 parent fbbde4d commit 6e68559

File tree

4 files changed

+224
-203
lines changed

4 files changed

+224
-203
lines changed

Lib/test/test_dict.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1476,6 +1476,24 @@ def test_dict_items_result_gc_reversed(self):
14761476
gc.collect()
14771477
self.assertTrue(gc.is_tracked(next(it)))
14781478

1479+
def test_store_evilattr(self):
1480+
class EvilAttr:
1481+
def __init__(self, d):
1482+
self.d = d
1483+
1484+
def __del__(self):
1485+
if 'attr' in self.d:
1486+
del self.d['attr']
1487+
gc.collect()
1488+
1489+
class Obj:
1490+
pass
1491+
1492+
obj = Obj()
1493+
obj.__dict__ = {}
1494+
for _ in range(10):
1495+
obj.attr = EvilAttr(obj.__dict__)
1496+
14791497
def test_str_nonstr(self):
14801498
# cpython uses a different lookup function if the dict only contains
14811499
# `str` keys. Make sure the unoptimized path is used when a non-`str`
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a potential use-after-free in ``STORE_ATTR_WITH_HINT``.

Python/bytecodes.c

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1999,14 +1999,15 @@ dummy_func(
19991999
new_version = _PyDict_NotifyEvent(tstate->interp, PyDict_EVENT_MODIFIED, dict, name, value);
20002000
ep->me_value = value;
20012001
}
2002-
Py_DECREF(old_value);
2003-
STAT_INC(STORE_ATTR, hit);
20042002
/* Ensure dict is GC tracked if it needs to be */
20052003
if (!_PyObject_GC_IS_TRACKED(dict) && _PyObject_GC_MAY_BE_TRACKED(value)) {
20062004
_PyObject_GC_TRACK(dict);
20072005
}
2008-
/* PEP 509 */
2009-
dict->ma_version_tag = new_version;
2006+
dict->ma_version_tag = new_version; // PEP 509
2007+
// old_value should be DECREFed after GC track checking is done, if not, it could raise a segmentation fault,
2008+
// when dict only holds the strong reference to value in ep->me_value.
2009+
Py_DECREF(old_value);
2010+
STAT_INC(STORE_ATTR, hit);
20102011
Py_DECREF(owner);
20112012
}
20122013

0 commit comments

Comments
 (0)