py/binary: Change internal bytearray typecode from 0 to 1.

The value of 0 can't be used because otherwise mp_binary_get_size will let
a null byte through as the type code (intepreted as byterray).  This can
lead to invalid type-specifier strings being let through without an error
in the struct module, and even buffer overruns.
This commit is contained in:
Damien George 2017-08-17 16:16:11 +10:00
parent e4ab404780
commit 025e5f2b33
2 changed files with 30 additions and 2 deletions

View File

@ -29,8 +29,9 @@
#include "py/obj.h" #include "py/obj.h"
// Use special typecode to differentiate repr() of bytearray vs array.array('B') // Use special typecode to differentiate repr() of bytearray vs array.array('B')
// (underlyingly they're same). // (underlyingly they're same). Can't use 0 here because that's used to detect
#define BYTEARRAY_TYPECODE 0 // type-specification errors due to end-of-string.
#define BYTEARRAY_TYPECODE 1
size_t mp_binary_get_size(char struct_type, char val_type, mp_uint_t *palign); size_t mp_binary_get_size(char struct_type, char val_type, mp_uint_t *palign);
mp_obj_t mp_binary_get_val_array(char typecode, void *p, mp_uint_t index); mp_obj_t mp_binary_get_val_array(char typecode, void *p, mp_uint_t index);

View File

@ -40,3 +40,30 @@ try:
struct.calcsize('0z') struct.calcsize('0z')
except: except:
print('Exception') print('Exception')
# check that a count without a type specifier raises an exception
try:
struct.calcsize('1')
except:
print('Exception')
try:
struct.pack('1')
except:
print('Exception')
try:
struct.pack_into('1', bytearray(4), 0, 'xx')
except:
print('Exception')
try:
struct.unpack('1', 'xx')
except:
print('Exception')
try:
struct.unpack_from('1', 'xx')
except:
print('Exception')