Skip to content

gh-130317: Fix strict aliasing in PyFloat_Pack8() #133150

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
merged 2 commits into from
Apr 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions Modules/_testcapi/float.c
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,11 @@ _testcapi_float_set_snan(PyObject *module, PyObject *obj)
uint64_t v;
memcpy(&v, &d, 8);
v &= ~(1ULL << 51); /* make sNaN */
memcpy(&d, &v, 8);
return PyFloat_FromDouble(d);

// gh-130317: memcpy() is needed to preserve the sNaN flag on x86 (32-bit)
PyObject *res = PyFloat_FromDouble(0.0);
memcpy(&((PyFloatObject *)res)->ob_fval, &v, 8);
return res;
}

static PyMethodDef test_methods[] = {
Expand Down
14 changes: 7 additions & 7 deletions Objects/floatobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2197,12 +2197,10 @@ PyFloat_Pack4(double x, char *data, int le)

memcpy(&v, &x, 8);
if ((v & (1ULL << 51)) == 0) {
union float_val {
float f;
uint32_t u32;
} *py = (union float_val *)&y;

py->u32 &= ~(1 << 22); /* make sNaN */
uint32_t u32;
memcpy(&u32, &y, 4);
u32 &= ~(1 << 22); /* make sNaN */
memcpy(&y, &u32, 4);
}
}

Expand Down Expand Up @@ -2340,7 +2338,9 @@ PyFloat_Pack8(double x, char *data, int le)
return -1;
}
else {
const unsigned char *s = (unsigned char*)&x;
unsigned char as_bytes[8];
memcpy(as_bytes, &x, 8);
const unsigned char *s = as_bytes;
int i, incr = 1;

if ((double_format == ieee_little_endian_format && !le)
Expand Down
Loading