Skip to content

gh-140868: Don't rely on undefined left shift behavior in assert#140869

Merged
DinoV merged 1 commit into
python:mainfrom
DinoV:undefined_behavior
Nov 1, 2025
Merged

gh-140868: Don't rely on undefined left shift behavior in assert#140869
DinoV merged 1 commit into
python:mainfrom
DinoV:undefined_behavior

Conversation

@DinoV
Copy link
Copy Markdown
Contributor

@DinoV DinoV commented Nov 1, 2025

This assert https://github.com/python/cpython/blob/main/Include/internal/pycore_stackref.h#L406 contains a left shift of a potentially negative value which is undefined behavior. The non-assert line does a uintptr_t cast to avoid the undefined behavior. Replicate that in the assert and then cast the final value back to intptr_t.

PyStackRef_TagInt(intptr_t i)
{
assert(Py_ARITHMETIC_RIGHT_SHIFT(intptr_t, (i << Py_TAGGED_SHIFT), Py_TAGGED_SHIFT) == i);
assert(Py_ARITHMETIC_RIGHT_SHIFT(intptr_t, (intptr_t)(((uintptr_t)i) << Py_TAGGED_SHIFT),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice catch! 👍

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

All I did was run the build in our default settings at work! 😀

@DinoV DinoV merged commit b155414 into python:main Nov 1, 2025
52 checks passed
StanFromIreland pushed a commit to StanFromIreland/cpython that referenced this pull request Dec 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants