Skip to content

bpo-30245: possible overflow when organize struct.pack_into error message #1682

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 10 commits into from
Jun 2, 2017
Merged
Show file tree
Hide file tree
Changes from 4 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
11 changes: 11 additions & 0 deletions Lib/test/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,17 @@ def test_boundary_error_message_with_negative_offset(self):
'offset -11 out of range for 10-byte buffer'):
struct.pack_into('<B', byte_list, -11, 123)

def test_boundary_error_message_with_large_offset(self):
# Test overflows cause by large offset and value size (issue 30245)
regex = (
"pack_into requires a buffer of at least " + str(sys.maxsize + 4) +
" bytes for packing 4 bytes at offset " + str(sys.maxsize) +
" \(actual buffer size is 10\)"
Copy link
Member

Choose a reason for hiding this comment

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

Use raw string literals. Compiling "\(" emits a deprecation warning.

You also could use classic string formatting, string's format() method, or f-string expression for composing this string.

)

with self.assertRaisesRegex(struct.error, regex):
struct.pack_into('<I', bytearray(10), sys.maxsize, 1)

def test_issue29802(self):
# When the second argument of struct.unpack() was of wrong type
# the Struct object was decrefed twice and the reference to
Expand Down
8 changes: 6 additions & 2 deletions Modules/_struct.c
Original file line number Diff line number Diff line change
Expand Up @@ -1929,11 +1929,15 @@ s_pack_into(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames

/* Check boundaries */
if ((buffer.len - offset) < soself->s_size) {

Copy link
Member

Choose a reason for hiding this comment

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

Please remove these empty lines. They look distracting.

assert(offset >= 0);
assert(soself->s_size >= 0);

PyErr_Format(StructError,
"pack_into requires a buffer of at least %zd bytes for "
"pack_into requires a buffer of at least %zu bytes for "
"packing %zd bytes at offset %zd "
"(actual buffer size is %zd)",
soself->s_size + offset,
(size_t)soself->s_size + (size_t)offset,
soself->s_size,
offset,
buffer.len);
Expand Down