Skip to content

Commit 674b83a

Browse files
committed
gh-161767: Fix crash in PyDict_AsFrozenDictAndClear on embedded values
1 parent 910a92b commit 674b83a

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

‎Lib/test/test_capi/test_dict.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,11 +635,42 @@ class DictSubtype(dict): ...
635635
self.assertIs(type(d), DictSubtype)
636636
self.assertEqual(d, DictSubtype({}))
637637

638+
# non str keys:
639+
d = {1: 'a', 2: 'b', 3: 'c', None: 'f'}
640+
f = as_frozendict(d)
641+
self.assertIs(type(f), frozendict)
642+
self.assertEqual(f, frozendict({1: 'a', 2: 'b', 3: 'c', None: 'f'}))
643+
self.assertIs(type(d), dict)
644+
self.assertEqual(d, {})
645+
646+
d = DictSubtype({1: 'a', 2: 'b', 3: 'c', None: 'f'})
647+
f = as_frozendict(d)
648+
self.assertIs(type(f), frozendict)
649+
self.assertEqual(f, frozendict({1: 'a', 2: 'b', 3: 'c', None: 'f'}))
650+
self.assertIs(type(d), DictSubtype)
651+
self.assertEqual(d, DictSubtype({}))
652+
653+
# wrong inputs:
638654
for wrong_input in (frozendict(), [], None):
639655
with self.subTest(wrong_input=wrong_input):
640656
with self.assertRaises(SystemError):
641657
as_frozendict(wrong_input)
642658

659+
# gh-161767: check embedded values
660+
class Regular: ...
661+
662+
for klass in (Regular, _testcapi.ManagedDictType):
663+
with self.subTest(klass=klass):
664+
instance = klass()
665+
instance.key = 'value'
666+
with self.assertRaisesRegex(ValueError, 'embedded values'):
667+
as_frozendict(instance.__dict__)
668+
669+
self.assertEqual(instance.__dict__, {'key': 'value'})
670+
# Both of these actions were needed to cause a crash:
671+
instance.other = 'new'
672+
del instance # must not crash
673+
643674
def test_frozendict_check(self):
644675
# Test PyFrozenDict_Check()
645676
check = _testcapi.frozendict_check

‎Objects/dictobject.c‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8700,6 +8700,13 @@ PyDict_AsFrozenDictAndClear(PyObject *dict)
87008700
return NULL;
87018701
}
87028702

8703+
PyDictObject *ma = (PyDictObject*)dict;
8704+
if (ma->ma_values && ma->ma_values->embedded) {
8705+
PyErr_SetString(PyExc_ValueError,
8706+
"can't convert dict with embedded values");
8707+
return NULL;
8708+
}
8709+
87038710
PyObject *res = frozendict_new_untracked(&PyFrozenDict_Type);
87048711
if (res == NULL) {
87058712
return NULL;

0 commit comments

Comments
 (0)