From 8f465dfd10f8186873be0c38e226bcf380be16ba Mon Sep 17 00:00:00 2001 From: Alessandro Gatti Date: Thu, 19 Sep 2024 20:29:00 +0200 Subject: [PATCH] unix/modffi: Restrict uint32_t values to 32 bits. This commit clears the upper 32 bits of returned `uint32_t` values, which are handled as `unsigned int`s by the MicroPython runtime and thus could be extended to 64 bits on some platforms. RV64 holds 32-bit values as signed integers when held in registers, but the code handling the FFI unsigned int case did not take this into account. That introduced test failures when a 32-bit value had its most significant bit set, as when performing the value extension from 32 to 64 bits, the upper half of the value would be filled with ones. On 32 bit platforms this change should be converted to a no-op, and on other 64 bit platforms that aren't RISC-V it shouldn't hurt as the value being manipulated is expected to only hold valid bits in its lower half. Signed-off-by: Alessandro Gatti --- ports/unix/modffi.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ports/unix/modffi.c b/ports/unix/modffi.c index dc3ed4dc7..b469e932e 100644 --- a/ports/unix/modffi.c +++ b/ports/unix/modffi.c @@ -191,9 +191,12 @@ static mp_obj_t return_ffi_value(ffi_union_t *val, char type) { case 'i': case 'l': return mp_obj_new_int((ffi_sarg)val->ffi); + case 'I': + // On RV64, 32-bit values are stored as signed integers inside the + // holding register. + return mp_obj_new_int_from_uint(val->ffi & 0xFFFFFFFF); case 'B': case 'H': - case 'I': case 'L': return mp_obj_new_int_from_uint(val->ffi); case 'q':