Skip to content

Commit 922f81d

Browse files
Arrowanadpgeorge
authored andcommitted
extmod/machine_mem: Only allow integers in machine.memX subscript.
Prior to this change machine.mem32['foo'] (or using any other non-integer subscript) could result in a fault due to 'foo' being interpreted as an integer. And when writing code it's hard to tell if the fault is due to a bad subscript type, or an integer subscript that specifies an invalid memory address. The type of the object used in the subscript is now tested to be an integer by using mp_obj_get_int_truncated instead of mp_obj_int_get_truncated. The performance hit of this change is minimal, and machine.memX objects are more for convenience than performance (there are many other ways to read/write memory in a faster way), Fixes issue micropython#6588.
1 parent 8a917ad commit 922f81d

File tree

4 files changed

+26
-2
lines changed

4 files changed

+26
-2
lines changed

extmod/machine_mem.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040

4141
#if !defined(MICROPY_MACHINE_MEM_GET_READ_ADDR) || !defined(MICROPY_MACHINE_MEM_GET_WRITE_ADDR)
4242
STATIC uintptr_t machine_mem_get_addr(mp_obj_t addr_o, uint align) {
43-
uintptr_t addr = mp_obj_int_get_truncated(addr_o);
43+
uintptr_t addr = mp_obj_get_int_truncated(addr_o);
4444
if ((addr & (align - 1)) != 0) {
4545
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("address %08x is not aligned to %d bytes"), addr, align);
4646
}

ports/unix/modmachine.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
#if MICROPY_PY_MACHINE
4848

4949
uintptr_t mod_machine_mem_get_addr(mp_obj_t addr_o, uint align) {
50-
uintptr_t addr = mp_obj_int_get_truncated(addr_o);
50+
uintptr_t addr = mp_obj_get_int_truncated(addr_o);
5151
if ((addr & (align - 1)) != 0) {
5252
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("address %08x is not aligned to %d bytes"), addr, align);
5353
}

tests/extmod/machine1.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,23 @@
2626
del machine.mem8[0]
2727
except TypeError:
2828
print("TypeError")
29+
30+
try:
31+
machine.mem8[0:1]
32+
except TypeError:
33+
print("TypeError")
34+
35+
try:
36+
machine.mem8[0:1] = 10
37+
except TypeError:
38+
print("TypeError")
39+
40+
try:
41+
machine.mem8["hello"]
42+
except TypeError:
43+
print("TypeError")
44+
45+
try:
46+
machine.mem8["hello"] = 10
47+
except TypeError:
48+
print("TypeError")

tests/extmod/machine1.py.exp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,7 @@
22
ValueError
33
ValueError
44
TypeError
5+
TypeError
6+
TypeError
7+
TypeError
8+
TypeError

0 commit comments

Comments
 (0)