Skip to content

Commit

Permalink
GH-113462: Limit the number of versions that a single class can use. (G…
Browse files Browse the repository at this point in the history
  • Loading branch information
markshannon authored Feb 5, 2024
1 parent 87cd20a commit 992446d
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions Include/cpython/object.h
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ struct _typeobject {

/* bitset of which type-watchers care about this type */
unsigned char tp_watched;
uint16_t tp_versions_used;
};

/* This struct is used by the specializer
Expand Down
13 changes: 13 additions & 0 deletions Lib/test/test_type_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,19 @@ class C:

_clear_type_cache()

def test_per_class_limit(self):
class C:
x = 0

type_assign_version(C)
orig_version = type_get_version(C)
for i in range(1001):
C.x = i
type_assign_version(C)

new_version = type_get_version(C)
self.assertEqual(new_version, 0)


@support.cpython_only
class TypeCacheWithSpecializationTests(unittest.TestCase):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Limit the number of versions that a single class can use. Prevents a few
wayward classes using up all the version numbers.
7 changes: 6 additions & 1 deletion Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -908,6 +908,8 @@ type_mro_modified(PyTypeObject *type, PyObject *bases) {
}
}

#define MAX_VERSIONS_PER_CLASS 1000

static int
assign_version_tag(PyInterpreterState *interp, PyTypeObject *type)
{
Expand All @@ -922,7 +924,10 @@ assign_version_tag(PyInterpreterState *interp, PyTypeObject *type)
if (!_PyType_HasFeature(type, Py_TPFLAGS_READY)) {
return 0;
}

if (type->tp_versions_used >= MAX_VERSIONS_PER_CLASS) {
return 0;
}
type->tp_versions_used++;
if (type->tp_flags & Py_TPFLAGS_IMMUTABLETYPE) {
/* static types */
if (NEXT_GLOBAL_VERSION_TAG > _Py_MAX_GLOBAL_TYPE_VERSION_TAG) {
Expand Down

0 comments on commit 992446d

Please sign in to comment.