Skip to content

Commit 6da8d7c

Browse files
committed
Fix assertion failures in mp_obj_new_type
Fixes the following assertion failures when the arguments to type() were not of valid types: micropython: ../../py/objtype.c:984: mp_obj_new_type: Assertion `MP_OBJ_IS_TYPE(bases_tuple, &mp_type_tuple)' failed. micropython: ../../py/objtype.c:994: mp_obj_new_type: Assertion `MP_OBJ_IS_TYPE(items[i], &mp_type_type)' failed. e.g., when making calls like type("", (), 3) type("", 3, {})
1 parent a55988a commit 6da8d7c

2 files changed

Lines changed: 31 additions & 3 deletions

File tree

py/objtype.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -981,8 +981,14 @@ const mp_obj_type_t mp_type_type = {
981981
};
982982

983983
mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) {
984-
assert(MP_OBJ_IS_TYPE(bases_tuple, &mp_type_tuple)); // MicroPython restriction, for now
985-
assert(MP_OBJ_IS_TYPE(locals_dict, &mp_type_dict)); // MicroPython restriction, for now
984+
if(!MP_OBJ_IS_TYPE(bases_tuple, &mp_type_tuple)) {
985+
// MicroPython restriction, for now
986+
mp_raise_TypeError("type() argument 2 must be tuple");
987+
}
988+
if(!MP_OBJ_IS_TYPE(locals_dict, &mp_type_dict)) {
989+
// MicroPython restriction, for now
990+
mp_raise_TypeError("type() argument 3 must be dict");
991+
}
986992

987993
// TODO might need to make a copy of locals_dict; at least that's how CPython does it
988994

@@ -991,7 +997,9 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict)
991997
mp_obj_t *items;
992998
mp_obj_tuple_get(bases_tuple, &len, &items);
993999
for (size_t i = 0; i < len; i++) {
994-
assert(MP_OBJ_IS_TYPE(items[i], &mp_type_type));
1000+
if(!MP_OBJ_IS_TYPE(items[i], &mp_type_type)) {
1001+
mp_raise_TypeError("type is not an acceptable base type");
1002+
}
9951003
mp_obj_type_t *t = MP_OBJ_TO_PTR(items[i]);
9961004
// TODO: Verify with CPy, tested on function type
9971005
if (t->make_new == NULL) {

tests/basics/types3.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
try:
2+
type('abc', None, None)
3+
except TypeError:
4+
print(True)
5+
else:
6+
print(False)
7+
8+
try:
9+
type('abc', (), None)
10+
except TypeError:
11+
print(True)
12+
else:
13+
print(False)
14+
15+
try:
16+
type('abc', (1,), {})
17+
except TypeError:
18+
print(True)
19+
else:
20+
print(False)

0 commit comments

Comments
 (0)