Skip to content

Commit cc09ac8

Browse files
committed
address review: ensure buffer unmodified on overflow
1 parent 33ab0fd commit cc09ac8

2 files changed

Lines changed: 17 additions & 4 deletions

File tree

‎Lib/test/test_struct.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -426,13 +426,20 @@ def test_705836(self):
426426

427427
def test_float_complex_overflow(self):
428428
for value in (
429-
1e300, # big real
430-
1e300j, # big imag
429+
1e300 + 0.5j, # big real
430+
1.5 + 1e300j, # big imag
431431
):
432432
for format in (">Zf", "<Zf", "Zf"):
433433
with self.subTest(value=value, format=format):
434434
self.assertRaises(OverflowError, struct.pack, format, value)
435435

436+
ba = bytearray(8)
437+
try:
438+
struct.Struct(format).pack_into(ba, 0, value)
439+
assert False
440+
except OverflowError:
441+
self.assertEqual(ba, bytearray(8))
442+
436443
def test_1530559(self):
437444
for code, byteorder in iter_integer_formats():
438445
format = byteorder + code

‎Modules/_struct.c‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -797,12 +797,18 @@ np_float_complex(_structmodulestate *state, char *p, PyObject *v,
797797
return -1;
798798
}
799799

800-
int ret = PyFloat_Pack4(c.real, p, PY_LITTLE_ENDIAN);
800+
char tmp[8];
801+
int ret = PyFloat_Pack4(c.real, tmp, PY_LITTLE_ENDIAN);
801802

802803
if (ret) {
803804
return ret;
804805
}
805-
return PyFloat_Pack4(c.imag, p + sizeof(float), PY_LITTLE_ENDIAN);
806+
ret = PyFloat_Pack4(c.imag, tmp + 4, PY_LITTLE_ENDIAN);
807+
if (ret) {
808+
return ret;
809+
}
810+
memcpy(p, tmp, 8);
811+
return ret;
806812
}
807813

808814
static int

0 commit comments

Comments
 (0)