8000 gh-96735: Fix undefined behaviour in struct unpacking functions by mdickinson · Pull Request #96739 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-96735: Fix undefined behaviour in struct unpacking functions #96739

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

Merged
Next Next commit
Fix undefined behaviour in bu_ulonglong
  • Loading branch information
mdickinson committed Sep 10, 2022
commit 22fdce61d61a6b68f84c3e6e263de2860429ccea
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix undefined behaviour in :func:`struct.unpack`.
15 changes: 9 additions & 6 deletions Modules/_struct.c
Original file line number Diff line number Diff line change
Expand Up @@ -835,16 +835,19 @@ bu_uint(_structmodulestate *state, const char *p, const formatdef *f)
static PyObject *
bu_longlong(_structmodulestate *state, const char *p, const formatdef *f)
{
long long x = 0;
Py_ssize_t i = f->size;
unsigned long long x = 0;

/* This function is only ever used in the case f->size == 8. */
assert(f->size == 8);
Py_ssize_t i = 8;
const unsigned char *bytes = (const unsigned char *)p;
do {
x = (x<<8) | *bytes++;
} while (--i > 0);
/* Extend the sign bit. */
if (SIZEOF_LONG_LONG > f->size)
x |= -(x & ((long long)1 << ((8 * f->size) - 1)));
return PyLong_FromLongLong(x);

/* Extend sign, avoiding implementation-defined or undefined behaviour. */
return PyLong_FromLongLong(x & 0x8000000000000000 ?
-1 - (long long)(0xFFFFFFFFFFFFFFFF - x) : (long long)x);
}

static PyObject *
Expand Down
0