Skip to content

Crash in UnicodeError.__str__ with attributes have custom __str__ #128974

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
picnixz opened this issue Jan 18, 2025 · 0 comments
Closed

Crash in UnicodeError.__str__ with attributes have custom __str__ #128974

picnixz opened this issue Jan 18, 2025 · 0 comments
Assignees
Labels
interpreter-core (Objects, Python, Grammar, and Parser dirs) topic-unicode type-crash A hard crash of the interpreter, possibly with a core dump

Comments

@picnixz
Copy link
Member

picnixz commented Jan 18, 2025

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

@picnixz picnixz added interpreter-core (Objects, Python, Grammar, and Parser dirs) type-crash A hard crash of the interpreter, possibly with a core dump labels Jan 18, 2025
@picnixz picnixz self-assigned this Jan 18, 2025
picnixz added a commit that referenced this issue Mar 1, 2025
…e-effects (#128975)

Fix some crashes when (custom) attributes of `UnicodeError` objects implement `object.__str__` with side-effects.
@picnixz picnixz closed this as completed Mar 1, 2025
seehwan pushed a commit to seehwan/cpython that referenced this issue Apr 16, 2025
…ve side-effects (python#128975)

Fix some crashes when (custom) attributes of `UnicodeError` objects implement `object.__str__` with side-effects.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
interpreter-core (Objects, Python, Grammar, and Parser dirs) topic-unicode type-crash A hard crash of the interpreter, possibly with a core dump
Projects
None yet
Development

No branches or pull requests

1 participant