Skip to content

Commit 5b3b3f5

Browse files
committed
gh-143635: Fix crash in _Py_typing_type_repr
1 parent aa8578d commit 5b3b3f5

2 files changed

Lines changed: 41 additions & 1 deletion

File tree

Lib/test/test_genericalias.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,43 @@ class MyGeneric:
244244
self.assertEndsWith(repr(MyGeneric[[]]), 'MyGeneric[[]]')
245245
self.assertEndsWith(repr(MyGeneric[[int, str]]), 'MyGeneric[[int, str]]')
246246

247+
def test_evil_repr1(self):
248+
# gh-143635
249+
class Zap:
250+
def __init__(self, container):
251+
self.container = container
252+
def __getattr__(self, name):
253+
if name == "__origin__":
254+
self.container.clear()
255+
return None
256+
if name == "__args__":
257+
return ()
258+
raise AttributeError
259+
260+
params = []
261+
params.append(Zap(params))
262+
alias = type(list[int])(list, (params,))
263+
repr_str = repr(alias)
264+
self.assertTrue(repr_str.startswith("list[["), repr_str)
265+
266+
def test_evil_repr2(self):
267+
class Zap:
268+
def __init__(self, container):
269+
self.container = container
270+
def __getattr__(self, name):
271+
if name == "__qualname__":
272+
self.container.clear()
273+
return "abcd"
274+
if name == "__module__":
275+
return None
276+
raise AttributeError
277+
278+
params = []
279+
params.append(Zap(params))
280+
alias = type(list[int])(list, (params,))
281+
repr_str = repr(alias)
282+
self.assertTrue(repr_str.startswith("list[["), repr_str)
283+
247284
def test_exposed_type(self):
248285
import types
249286
a = types.GenericAlias(list, int)

Objects/typevarobject.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,13 +270,14 @@ _Py_typing_type_repr(PyUnicodeWriter *writer, PyObject *p)
270270
if (p == Py_Ellipsis) {
271271
// The Ellipsis object
272272
r = PyUnicode_FromString("...");
273-
goto exit;
273+
goto cleanup;
274274
}
275275

276276
if (p == (PyObject *)&_PyNone_Type) {
277277
return PyUnicodeWriter_WriteASCII(writer, "None", 4);
278278
}
279279

280+
Py_INCREF(p); // gh-143635
280281
if ((rc = PyObject_HasAttrWithError(p, &_Py_ID(__origin__))) > 0 &&
281282
(rc = PyObject_HasAttrWithError(p, &_Py_ID(__args__))) > 0)
282283
{
@@ -316,6 +317,8 @@ _Py_typing_type_repr(PyUnicodeWriter *writer, PyObject *p)
316317
use_repr:
317318
r = PyObject_Repr(p);
318319
exit:
320+
Py_DECREF(p); // gh-143635
321+
cleanup:
319322
Py_XDECREF(qualname);
320323
Py_XDECREF(module);
321324
if (r == NULL) {

0 commit comments

Comments
 (0)