picnixz · GitHub

Crash report

What happened?

class Evil(str):
    def __str__(self):
        del exc.object
        return 'evil'
exc = UnicodeEncodeError(Evil(), "object", 0, 0, Evil())
str(exc)

results in Segmentation fault (core dumped). Another possibility for a crash:

class Evil(str):
    def __str__(self):
        del exc.object
        return 'evil'
exc = UnicodeEncodeError(Evil(), "object", 0, 0, Evil())
str(exc)

results in

python: ./Include/cpython/unicodeobject.h:286: PyUnicode_GET_LENGTH: Assertion `PyUnicode_Check(op)' failed.
Aborted (core dumped)

The segmentation fault is quite easy to fix:

reason_str = PyObject_Str(exc->reason);
if (reason_str == NULL) {
    goto done;
}
encoding_str = PyObject_Str(exc->encoding);
if (encoding_str == NULL) {
    goto done;
}
Py_ssize_t len = PyUnicode_GET_LENGTH(exc->object);

It occurs in PyUnicode_GET_LENGTH(exc->object);. And the reason is that PyObject_Str(...) may call artrbitary code.

I have a PR ready that I will post soon.

See #128975 (comment) for the rationale of not backporting it.

CPython versions tested on:

CPython main branch

Linked PRs

Read the original on github.com ↗