Skip to content

Commit 05b13fd

Browse files
jeplerdpgeorge
authored andcommitted
py/objtype: Fix assertion failures in mp_obj_new_type by checking types.
Fixes assertion failures when the arguments to type() were not of valid types, e.g., when making calls like: type("", (), 3) type("", 3, {})
1 parent a1acbad commit 05b13fd

2 files changed

Lines changed: 28 additions & 3 deletions

File tree

py/objtype.c

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1005,8 +1005,13 @@ const mp_obj_type_t mp_type_type = {
10051005
};
10061006

10071007
mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) {
1008-
assert(MP_OBJ_IS_TYPE(bases_tuple, &mp_type_tuple)); // MicroPython restriction, for now
1009-
assert(MP_OBJ_IS_TYPE(locals_dict, &mp_type_dict)); // MicroPython restriction, for now
1008+
// Verify input objects have expected type
1009+
if (!MP_OBJ_IS_TYPE(bases_tuple, &mp_type_tuple)) {
1010+
mp_raise_TypeError(NULL);
1011+
}
1012+
if (!MP_OBJ_IS_TYPE(locals_dict, &mp_type_dict)) {
1013+
mp_raise_TypeError(NULL);
1014+
}
10101015

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

@@ -1015,7 +1020,9 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict)
10151020
mp_obj_t *bases_items;
10161021
mp_obj_tuple_get(bases_tuple, &bases_len, &bases_items);
10171022
for (size_t i = 0; i < bases_len; i++) {
1018-
assert(MP_OBJ_IS_TYPE(bases_items[i], &mp_type_type));
1023+
if (!MP_OBJ_IS_TYPE(bases_items[i], &mp_type_type)) {
1024+
mp_raise_TypeError(NULL);
1025+
}
10191026
mp_obj_type_t *t = MP_OBJ_TO_PTR(bases_items[i]);
10201027
// TODO: Verify with CPy, tested on function type
10211028
if (t->make_new == NULL) {

tests/basics/builtin_type.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,21 @@
1111
type(1, 2)
1212
except TypeError:
1313
print('TypeError')
14+
15+
# second arg should be a tuple
16+
try:
17+
type('abc', None, None)
18+
except TypeError:
19+
print('TypeError')
20+
21+
# third arg should be a dict
22+
try:
23+
type('abc', (), None)
24+
except TypeError:
25+
print('TypeError')
26+
27+
# elements of second arg (the bases) should be types
28+
try:
29+
type('abc', (1,), {})
30+
except TypeError:
31+
print('TypeError')

0 commit comments

Comments
 (0)