Skip to content

gh-121860: Fix crash when materializing managed dict #121866

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 16, 2024
Merged
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
18 changes: 18 additions & 0 deletions Lib/test/test_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,24 @@ class Foo:
f.a = 3
self.assertEqual(f.a, 3)

def test_rematerialize_object_dict(self):
# gh-121860: rematerializing an object's managed dictionary after it
# had been deleted caused a crash.
class Foo: pass
f = Foo()
f.__dict__["attr"] = 1
del f.__dict__

# Using a str subclass is a way to trigger the re-materialization
class StrSubclass(str): pass
self.assertFalse(hasattr(f, StrSubclass("attr")))

# Changing the __class__ also triggers the re-materialization
class Bar: pass
f.__class__ = Bar
self.assertIsInstance(f, Bar)
self.assertEqual(f.__dict__, {})

def test_store_attr_type_cache(self):
"""Verifies that the type cache doesn't provide a value which is
inconsistent from the dict."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix crash when rematerializing a managed dictionary after it was deleted.
17 changes: 12 additions & 5 deletions Objects/dictobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -6683,13 +6683,20 @@ _PyObject_MaterializeManagedDict_LockHeld(PyObject *obj)
{
ASSERT_WORLD_STOPPED_OR_OBJ_LOCKED(obj);

PyDictValues *values = _PyObject_InlineValues(obj);
PyInterpreterState *interp = _PyInterpreterState_GET();
PyDictKeysObject *keys = CACHED_KEYS(Py_TYPE(obj));
OBJECT_STAT_INC(dict_materialized_on_request);
PyDictObject *dict = make_dict_from_instance_attributes(interp, keys, values);

PyDictValues *values = _PyObject_InlineValues(obj);
PyDictObject *dict;
if (values->valid) {
PyInterpreterState *interp = _PyInterpreterState_GET();
PyDictKeysObject *keys = CACHED_KEYS(Py_TYPE(obj));
dict = make_dict_from_instance_attributes(interp, keys, values);
}
else {
dict = (PyDictObject *)PyDict_New();
}
FT_ATOMIC_STORE_PTR_RELEASE(_PyObject_ManagedDictPointer(obj)->dict,
(PyDictObject *)dict);
dict);
return dict;
}

Expand Down
Loading