Skip to content

Commit

Permalink
py/binary: mp_binary_get_size: Raise error on unsupported typecodes.
Browse files Browse the repository at this point in the history
Previouly, we had errors checked in callers, which led to duplicate code
or missing checks in some places.
  • Loading branch information
Paul Sokolovsky committed Jan 17, 2017
1 parent 5e80c53 commit af90461
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 7 deletions.
6 changes: 6 additions & 0 deletions py/binary.c
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
#include "py/binary.h"
#include "py/smallint.h"
#include "py/objint.h"
#include "py/runtime.h"

// Helpers to work with binary-encoded data

Expand Down Expand Up @@ -100,6 +101,11 @@ size_t mp_binary_get_size(char struct_type, char val_type, mp_uint_t *palign) {
}
}
}

if (size == 0) {
mp_raise_ValueError("bad typecode");
}

if (palign != NULL) {
*palign = align;
}
Expand Down
3 changes: 0 additions & 3 deletions py/modstruct.c
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,6 @@ STATIC mp_obj_t struct_calcsize(mp_obj_t fmt_in) {
} else {
mp_uint_t align;
size_t sz = mp_binary_get_size(fmt_type, *fmt, &align);
if (sz == 0) {
mp_raise_ValueError("unsupported format");
}
while (cnt--) {
// Apply alignment
size = (size + align - 1) & ~(align - 1);
Expand Down
3 changes: 0 additions & 3 deletions py/objarray.c
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,6 @@ STATIC void array_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t
#if MICROPY_PY_BUILTINS_BYTEARRAY || MICROPY_PY_ARRAY
STATIC mp_obj_array_t *array_new(char typecode, mp_uint_t n) {
int typecode_size = mp_binary_get_size('@', typecode, NULL);
if (typecode_size == 0) {
mp_raise_msg(&mp_type_ValueError, "bad typecode");
}
mp_obj_array_t *o = m_new_obj(mp_obj_array_t);
#if MICROPY_PY_BUILTINS_BYTEARRAY && MICROPY_PY_ARRAY
o->base.type = (typecode == BYTEARRAY_TYPECODE) ? &mp_type_bytearray : &mp_type_array;
Expand Down
12 changes: 11 additions & 1 deletion tests/basics/struct2.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,17 @@
print(struct.unpack('<0s1s0H2H', b'01234'))
print(struct.pack('<0s1s0H2H', b'abc', b'abc', 258, 515))

# check that zero of an unknown type raises an exception
# check that unknown types raise an exception
try:
struct.unpack('z', b'1')
except:
print('Exception')

try:
struct.pack('z', (b'1',))
except:
print('Exception')

try:
struct.calcsize('0z')
except:
Expand Down

0 comments on commit af90461

Please sign in to comment.