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
Prev Previous commit
Next Next commit
Also apply the fix to lu_longlong
  • Loading branch information
mdickinson committed Sep 10, 2022
commit 8efefd8b5c91312c574ae1996052f45d7387e86a
6 changes: 5 additions & 1 deletion Lib/test/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -729,7 +729,11 @@ def test_issue45034_signed(self):
def test_long_long_unpack_undefined_behaviour(self):
# Regression test for python/cpython#96735.
self.assertEqual(
struct.unpack('!q', b'\xff\xff\xff\xff\xff\xff\xff\xff'),
struct.unpack('<q', b'\xff\xff\xff\xff\xff\xff\xff\xff'),
(-1,)
)
self.assertEqual(
struct.unpack('>q', b'\xff\xff\xff\xff\xff\xff\xff\xff'),
(-1,)
)

Expand Down
15 changes: 9 additions & 6 deletions Modules/_struct.c
Original file line number Diff line number Diff line change
Expand Up @@ -1059,16 +1059,19 @@ lu_uint(_structmodulestate *state, const char *p, const formatdef *f)
static PyObject *
lu_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[--i];
} 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