Skip to content

Commit b45c8c1

Browse files
committed
py/objtype: Check and prevent delete/store on a fixed locals map.
Note that the check for elem!=NULL is removed for the MP_MAP_LOOKUP_ADD_IF_NOT_FOUND case because mp_map_lookup will always return non-NULL for such a case.
1 parent cc92c05 commit b45c8c1

3 files changed

Lines changed: 20 additions & 6 deletions

File tree

py/objtype.c

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -975,21 +975,21 @@ STATIC void type_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
975975
if (self->locals_dict != NULL) {
976976
assert(self->locals_dict->base.type == &mp_type_dict); // MicroPython restriction, for now
977977
mp_map_t *locals_map = &self->locals_dict->map;
978+
if (locals_map->is_fixed) {
979+
// can't apply delete/store to a fixed map
980+
return;
981+
}
978982
if (dest[1] == MP_OBJ_NULL) {
979983
// delete attribute
980984
mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP_REMOVE_IF_FOUND);
981-
// note that locals_map may be in ROM, so remove will fail in that case
982985
if (elem != NULL) {
983986
dest[0] = MP_OBJ_NULL; // indicate success
984987
}
985988
} else {
986989
// store attribute
987990
mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
988-
// note that locals_map may be in ROM, so add will fail in that case
989-
if (elem != NULL) {
990-
elem->value = dest[1];
991-
dest[0] = MP_OBJ_NULL; // indicate success
992-
}
991+
elem->value = dest[1];
992+
dest[0] = MP_OBJ_NULL; // indicate success
993993
}
994994
}
995995
}

tests/basics/del_attr.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,10 @@ def f():
3030
del c.x
3131
except AttributeError:
3232
print("AttributeError")
33+
34+
# try to del an attribute of a built-in class
35+
try:
36+
del int.to_bytes
37+
except (AttributeError, TypeError):
38+
# uPy raises AttributeError, CPython raises TypeError
39+
print('AttributeError/TypeError')

tests/basics/setattr1.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,10 @@ def __init__(self):
1616
setattr(a, b'var3', 1)
1717
except TypeError:
1818
print('TypeError')
19+
20+
# try setattr on a built-in function
21+
try:
22+
setattr(int, 'to_bytes', 1)
23+
except (AttributeError, TypeError):
24+
# uPy raises AttributeError, CPython raises TypeError
25+
print('AttributeError/TypeError')

0 commit comments

Comments
 (0)