Skip to content

Commit 14230cd

Browse files
authored
[3.13] gh-130851: Only intern constants of types generated by the compiler (GH-130901) (#130953)
The free-threading build interns and immortalizes most constants generated by the bytecode compiler. However, users can construct their own code objects with arbitrary constants. We should not intern or immortalize these objects if they are not of a type that we know how to handle. This change fixes a reference leak failure in the recently added `test_code.test_unusual_constants` test. It also addresses a potential crash that could occur when attempting to destroy an immortalized object during interpreter shutdown. (cherry picked from commit 12db452)
1 parent 597a953 commit 14230cd

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

Objects/codeobject.c

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,38 @@ should_intern_string(PyObject *o)
132132

133133
#ifdef Py_GIL_DISABLED
134134
static PyObject *intern_one_constant(PyObject *op);
135+
136+
// gh-130851: In the free threading build, we intern and immortalize most
137+
// constants, except code objects. However, users can generate code objects
138+
// with arbitrary co_consts. We don't want to immortalize or intern unexpected
139+
// constants or tuples/sets containing unexpected constants.
140+
static int
141+
should_immortalize_constant(PyObject *v)
142+
{
143+
// Only immortalize containers if we've already immortalized all their
144+
// elements.
145+
if (PyTuple_CheckExact(v)) {
146+
for (Py_ssize_t i = PyTuple_GET_SIZE(v); --i >= 0; ) {
147+
if (!_Py_IsImmortal(PyTuple_GET_ITEM(v, i))) {
148+
return 0;
149+
}
150+
}
151+
return 1;
152+
}
153+
else if (PyFrozenSet_CheckExact(v)) {
154+
PyObject *item;
155+
Py_hash_t hash;
156+
Py_ssize_t pos = 0;
157+
while (_PySet_NextEntry(v, &pos, &item, &hash)) {
158+
if (!_Py_IsImmortal(item)) {
159+
return 0;
160+
}
161+
}
162+
return 1;
163+
}
164+
return (PyLong_CheckExact(v) || PyFloat_CheckExact(v) ||
165+
PyComplex_Check(v) || PyBytes_CheckExact(v));
166+
}
135167
#endif
136168

137169
static int
@@ -240,8 +272,8 @@ intern_constants(PyObject *tuple, int *modified)
240272
// we are also immortalizing objects that use deferred reference
241273
// counting.
242274
PyThreadState *tstate = PyThreadState_GET();
243-
if (!_Py_IsImmortal(v) && !PyCode_Check(v) &&
244-
!PyUnicode_CheckExact(v) &&
275+
if (!_Py_IsImmortal(v) && !PyUnicode_CheckExact(v) &&
276+
should_immortalize_constant(v) &&
245277
_Py_atomic_load_int(&tstate->interp->gc.immortalize) >= 0)
246278
{
247279
PyObject *interned = intern_one_constant(v);

0 commit comments

Comments
 (0)