Skip to content

Fix struct.pack with padding bytes #4620

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 3 commits into from
Apr 20, 2021
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
6 changes: 1 addition & 5 deletions py/binary.c
Original file line number Diff line number Diff line change
Expand Up @@ -371,11 +371,7 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte **
}
}

if (val_type == 'x') {
memset(p, 0, 1);
} else {
mp_binary_set_int(MIN((size_t)size, sizeof(val)), struct_type == '>', p, val);
}
mp_binary_set_int(MIN((size_t)size, sizeof(val)), struct_type == '>', p, val);
}

void mp_binary_set_val_array(char typecode, void *p, mp_uint_t index, mp_obj_t val_in) {
Expand Down
6 changes: 4 additions & 2 deletions py/modstruct.c
Original file line number Diff line number Diff line change
Expand Up @@ -214,9 +214,11 @@ STATIC void struct_pack_into_internal(mp_obj_t fmt_in, byte *p, size_t n_args, c
p += cnt;
} else {
while (cnt--) {
mp_binary_set_val(fmt_type, *fmt, args[i], &p);
// Pad bytes don't have a corresponding argument.
if (*fmt != 'x') {
if (*fmt == 'x') {
mp_binary_set_val(fmt_type, *fmt, MP_OBJ_NEW_SMALL_INT(0), &p);
} else {
mp_binary_set_val(fmt_type, *fmt, args[i], &p);
i++;
}
}
Expand Down
6 changes: 4 additions & 2 deletions shared-module/struct/__init__.c
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,11 @@ void shared_modules_struct_pack_into(mp_obj_t fmt_in, byte *p, byte *end_p, size
p += sz;
} else {
while (sz--) {
mp_binary_set_val(fmt_type, *fmt, args[i], &p);
// Pad bytes don't have a corresponding argument.
if (*fmt != 'x') {
if (*fmt == 'x') {
mp_binary_set_val(fmt_type, *fmt, MP_OBJ_NEW_SMALL_INT(0), &p);
} else {
mp_binary_set_val(fmt_type, *fmt, args[i], &p);
i++;
}
}
Expand Down
2 changes: 2 additions & 0 deletions tests/basics/struct1.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,5 @@

# check padding bytes
print(struct.pack("xb", 3))
# Make sure pack doesn't reuse a larger value and error
print(struct.pack("xH", 0x100))