Fix stack extension bug causing HardFault

This patch fixes a bug in the stack extension logic that could cause a HardFault on certain configurations when the stack is reallocated to a new address.

## Background

When the mruby VM's stack runs out, stack_extend_alloc() calls mrb_realloc to grow it.
If reallocation moves the block to a new address, envadjust() adjusts all ci->stack pointers to point into the new allocation.

## The bug

The bug happened under the configuration below:

- MRB_INT64 on MRB_32BIT (`sizeof(mrb_value) == 16` because MRB_NO_BOXING is now mandatory)
- Allocator with 8-byte alignment (eg. PICORB_ALLOC_ALIGN=8 in PicoRuby for Raspi Pico)

The delta was computed via mrb_value* pointer subtraction:

```c
ptrdiff_t delta = newbase - oldbase;  // units of sizeof(mrb_value)
```

If :
- Old address: 0x2004c508
- New address: 0x2004c510 (8-byte difference)

The pointer subtraction truncated: 8 / 16 = 0.
envadjust() was misleaded as `delta == 0` and returned early without adjusting any ci->stack pointers.
The stbase was updated to the new address, but all stack pointers still pointed 8 bytes before it.
Every register access was shifted, reading garbage, ultimately causing a HardFault.

## The fix

Byte-level char* calculation instead of mrb_value* calculation:

```c
ptrdiff_t off = (char*)newbase - (char*)oldbase;
// ...
ci->stack = (mrb_value*)((char*)ci->stack + off);
```

This ensures the adjustment is exact regardless of sizeof(mrb_value) and allocator alignment.
This commit is contained in:
HASUMI Hitoshi
2026-03-30 16:00:41 +09:00
parent b7e3743130
commit d95ebe4a23
+15 -5
View File
@@ -134,19 +134,29 @@ static inline void
envadjust(mrb_state *mrb, mrb_value *oldbase, mrb_value *newbase)
{
mrb_callinfo *ci = mrb->c->cibase;
ptrdiff_t delta = newbase - oldbase;
/*
* Byte-level calculation to avoid truncation when allocator alignment is
* smaller than sizeof(mrb_value).
* eg: MRB_NO_BOXING + MRB_INT64 with MRB_32BIT => sizeof(mrb_value)=16
* And when memory allocator's alignment is 8 bytes
* Pointer subtraction on mrb_value* would truncate (8/16 -> 0).
* So, we use char* for pointer calculation to get the correct offset in bytes,
* then apply that offset to mrb_value* pointers.
*/
ptrdiff_t off = (char *)newbase - (char *)oldbase;
if (delta == 0) return;
if (off == 0) return;
while (ci <= mrb->c->ci) {
struct REnv *e = mrb_vm_ci_env(ci);
mrb_value *new_stack = (mrb_value *)((char *)ci->stack + off);
if (e) {
mrb_assert(e->cxt == mrb->c && MRB_ENV_ONSTACK_P(e));
mrb_assert(e->stack == ci->stack);
e->stack += delta;
e->stack = new_stack;
}
ci->stack += delta;
ci->stack = new_stack;
ci++;
}
}