Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Lib/test/test_capi/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,17 @@ class DictSubtype(dict): ...
self.assertIs(type(d), DictSubtype)
self.assertEqual(d, DictSubtype({}))

# instance dict that still has inline values
class A: ...
a = A()
a.x = 1
f = as_frozendict(a.__dict__)
a.x = 2
self.assertEqual(f, frozendict(x=1))
self.assertEqual(vars(a), {'x': 2})
del a
self.assertEqual(f, frozendict(x=1))

for wrong_input in (frozendict(), [], None):
with self.subTest(wrong_input=wrong_input):
with self.assertRaises(SystemError):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a crash in :c:func:`PyDict_AsFrozenDictAndClear` when called on an
instance :attr:`~object.__dict__` that still uses inline values.
40 changes: 30 additions & 10 deletions Objects/dictobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -8662,33 +8662,48 @@ frozendict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return d;
}

static void
static int
transfer_keys_and_values_lock_held(PyObject *res, PyObject *dict)
{
PyDictObject *new = (PyDictObject *)res;
PyDictObject *old = (PyDictObject *)dict;
assert(can_modify_dict(old));

// Fast path: do nothing on an empty dict:
if (old->ma_keys == Py_EMPTY_KEYS) {
return;
return 0;
}

Py_ssize_t used = old->ma_used;
PyDictKeysObject *keys = old->ma_keys;
PyDictValues *values = old->ma_values;

// Clear the old dict keys and values, but do not decref them:
clear_common(old);
set_keys(old, Py_EMPTY_KEYS);
set_values(old, NULL);
ASSERT_CONSISTENT(old);
if (values && values->embedded) {
// values are inline in the object, copy them and clear the object's copy
PyDictValues *v = values;
values = copy_values(v);
if (!values) {
PyErr_NoMemory();
return -1;
}
dictkeys_incref(keys);
clear_common(old);
for (Py_ssize_t i = 0; i < keys->dk_nentries; i++) {
FT_ATOMIC_STORE_PTR_RELEASE(v->values[i], NULL);
}
FT_ATOMIC_STORE_UINT8_RELEASE(v->size, 0);
}
else {
clear_common(old);
set_keys(old, Py_EMPTY_KEYS);
set_values(old, NULL);
ASSERT_CONSISTENT(old);
}

// Transfer keys and values from dict to frozendict:
new->ma_used = used;
new->ma_keys = keys;
new->ma_values = values;
ASSERT_CONSISTENT(new);
return 0;
}

PyObject *
Expand All @@ -8704,9 +8719,14 @@ PyDict_AsFrozenDictAndClear(PyObject *dict)
return NULL;
}

int err;
Py_BEGIN_CRITICAL_SECTION(dict);
transfer_keys_and_values_lock_held(res, dict);
err = transfer_keys_and_values_lock_held(res, dict);
Py_END_CRITICAL_SECTION();
if (err < 0) {
Py_DECREF(res);
return NULL;
}

_PyObject_GC_TRACK(res);
assert(_PyFrozenDictObject_CAST(res)->ma_hash == -1);
Expand Down
Loading