Skip to content

Commit 4e46908

Browse files
committed
py/objstr: Protect against creating bytes(n) with n negative.
Prior to this patch uPy (on a 32-bit arch) would have severe issues when calling bytes(-1): such a call would call vstr_init_len(vstr, -1) which would then +1 on the len and call vstr_init(vstr, 0), which would then round this up and allocate a small amount of memory for the vstr. The bytes constructor would then attempt to zero out all this memory, thinking it had allocated 2^32-1 bytes.
1 parent 165aab1 commit 4e46908

2 files changed

Lines changed: 10 additions & 1 deletion

File tree

py/objstr.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,10 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size
223223
}
224224

225225
if (MP_OBJ_IS_SMALL_INT(args[0])) {
226-
uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
226+
mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[0]);
227+
if (len < 0) {
228+
mp_raise_ValueError(NULL);
229+
}
227230
vstr_t vstr;
228231
vstr_init_len(&vstr, len);
229232
memset(vstr.buf, 0, len);

tests/basics/bytes.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,9 @@
5656
print(bytes([128, 255]))
5757
# For sequence of unknown len
5858
print(bytes(iter([128, 255])))
59+
60+
# Shouldn't be able to make bytes with negative length
61+
try:
62+
bytes(-1)
63+
except ValueError:
64+
print('ValueError')

0 commit comments

Comments
 (0)