Re: [PATCH] lib: sbi: Add runtime stack overrun detection

Andreas Schwab
2025-11-18T09:25:33Z

On Nov 18 2025, Bo Gan wrote:

> Hi Xiang,
>
> On 11/17/25 20:19, Xiang W wrote:
>> + if (sp < stack_start || sp > stack_end) {
>> + /* Reset SP to output error messages */
>> + asm volatile("mv sp, %0"::"r"(stack_end));
>
> I don't think it's safe to switch stack in C function. I know you want
> to avoid re-entrant, but do it in C function is way too risky. Better
> have an asm wapper over this function and do it before invoking the C
> portion.

The GCC docs makes this explicitly undefined:

Another restriction is that the clobber list should not contain the
stack pointer register. This is because the compiler requires the value
of the stack pointer to be the same after an 'asm' statement as it was
on entry to the statement. However, previous versions of GCC did not
enforce this rule and allowed the stack pointer to appear in the list,
with unclear semantics. This behavior is deprecated and listing the
stack pointer may become an error in future versions of GCC.

--
Andreas Schwab, SUSE Labs, schwab@suse.de
GPG Key fingerprint = 0196 BAD8 1CE9 1970 F4BE 1748 E4D4 88E3 0EEA B9D7
"And now for something completely different."