Skip to content

bpo-28866: Invalidate type cache on every setattr #13117

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

Closed
Closed
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
1 change: 1 addition & 0 deletions Include/object.h
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ PyAPI_FUNC(PyObject *) PyType_GenericAlloc(struct _typeobject *, Py_ssize_t);
PyAPI_FUNC(PyObject *) PyType_GenericNew(struct _typeobject *,
PyObject *, PyObject *);
PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
PyAPI_FUNC(void) PyType_InvalidateCache(PyObject *, PyObject *);
PyAPI_FUNC(void) PyType_Modified(struct _typeobject *);

/* Generic operations on objects */
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Invalidating method cache of PyType even when the tp_setattro does not use
PyType one, to avoid a segfault.
2 changes: 2 additions & 0 deletions Objects/object.c
Original file line number Diff line number Diff line change
Expand Up @@ -1038,6 +1038,8 @@ PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)

PyUnicode_InternInPlace(&name);
if (tp->tp_setattro != NULL) {
if (PyType_CheckExact(v))
PyType_InvalidateCache(v, name);
err = (*tp->tp_setattro)(v, name, value);
Py_DECREF(name);
return err;
Expand Down
19 changes: 19 additions & 0 deletions Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,25 @@ PyType_ClearCache(void)
return cur_version_tag;
}

void
PyType_InvalidateCache(PyObject *type, PyObject *name)
{
unsigned int h;
PyTypeObject *t;

t = (PyTypeObject *)type;
if (MCACHE_CACHEABLE_NAME(name) &&
PyType_HasFeature(t, Py_TPFLAGS_VALID_VERSION_TAG)) {
h = MCACHE_HASH_METHOD(t, name);
method_cache[h].version = 0;
if (method_cache[h].name != Py_None) {
Py_INCREF(Py_None);
Py_XSETREF(method_cache[h].name, Py_None);
}
method_cache[h].value = NULL;
}
}

void
_PyType_Fini(void)
{
Expand Down