Hand-written in assembly in libc, setjmp+longjmp

I don’t understand the argument for avoiding the use of “naked”. The functions in question are already basically “naked” functions: they assume the compiler won’t insert any instructions (except a couple instructions in specific places to deal with the return value). You aren’t actually gaining anything by avoiding use of the “naked” attribute; you’re just making the code more fragile in case some compiler flag makes the compiler generate different code.

For comparison, this is roughly what longjmp looks like with naked:

__attribute((naked))
void longjmp(__jmp_buf * buf, int val) {
asm("lw ra, %0(a0)"::"i"(offsetof(__jmp_buf, __pc)));
asm("lw s0, %0(a0)"::"i"(offsetof(__jmp_buf, __regs[0])));
[...]
asm("seqz a0, a1");
asm("add a0, a0, a1");
asm("ret");
}

This only requires minor syntax changes to the current implementation, generates exactly the same code, and avoids the undefined behavior.

2 Likes