Skip to content
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

ceval.c's GETITEM should have asserts, not set exceptions #96518

Merged
merged 2 commits into from Sep 4, 2022

Conversation

sweeneyde
Copy link
Member

@sweeneyde sweeneyde commented Sep 2, 2022

Before this change: the following segfaults at Py_INCREF(value) in LOAD_CONST:

>>> f = lambda: 42
>>> f.__code__ = f.__code__.replace(co_consts=())
>>> f()

This is because PyTuple_GetItem raises and returns NULL, which is never checked for.

After the change:

>>> f = lambda: 42
>>> f.__code__ = f.__code__.replace(co_consts=())
>>> f()
Assertion failed: i < PyTuple_GET_SIZE(v), file C:\Users\sween\Source\Repos\cpython2\cpython\Python\ceval.c, line 740

Also, PyTuple_GET_ITEM already casts.

This is a change that only applies in debug mode to malformed code, so skipping issue/news.

@sweeneyde sweeneyde added skip issue skip news interpreter-core Interpreter core (Objects, Python, Grammar, and Parser dirs) labels Sep 2, 2022
@sweeneyde sweeneyde requested a review from markshannon as a code owner Sep 2, 2022
Copy link
Contributor

@kumaraditya303 kumaraditya303 left a comment

LGTM, assertion failure is better than segfault.

#define GETITEM(v, i) PyTuple_GetItem((v), (i))
static inline PyObject *
GETITEM(PyObject *v, Py_ssize_t i) {
assert(i >= 0);
Copy link
Contributor

@rhettinger rhettinger Sep 4, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps add assertions for the other two tests in PyTuple_GetItem():


assert(PyTuple_Check(v);
assert(Py_REFCNT(v) == 1);

Copy link
Member Author

@sweeneyde sweeneyde Sep 4, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added PyTuple_Check to be explicit, though I believe the macros do that in debug mode regardless.

It looks like the refcount assertion would only be for PyTuple_SetItem().

@rhettinger
Copy link
Contributor

rhettinger commented Sep 4, 2022

This looks like a nice improvement.

@sweeneyde sweeneyde merged commit ac18665 into python:main Sep 4, 2022
12 checks passed
@sweeneyde sweeneyde deleted the GETITEM branch Sep 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
interpreter-core Interpreter core (Objects, Python, Grammar, and Parser dirs) skip issue skip news
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants