[Bug 268684] [PATCH] riscv libc: fix longjmp with 0 value

From: <bugzilla-noreply_at_freebsd.org>
Date: Sat, 31 Dec 2022 19:38:25 UTC
https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=268684

            Bug ID: 268684
           Summary: [PATCH] riscv libc: fix longjmp with 0 value
           Product: Base System
           Version: CURRENT
          Hardware: riscv
                OS: Any
            Status: New
          Severity: Affects Many People
          Priority: ---
         Component: riscv
          Assignee: riscv@FreeBSD.org
          Reporter: alois+freebsd@aloisklink.com

Created attachment 239166
  --> https://bugs.freebsd.org/bugzilla/attachment.cgi?id=239166&action=edit
`git format-patch` patch file

On RISC-V, calling `longjmp(x, 0);` makes `setjmp(x)` return 0, which normally
causes an infinite loop, and is against the ISO C standard for setjmp/longjmp. 

Instead, using a value of 0 should make `setjmp` return 1:

> The `longjmp` function cannot cause the `setjmp` macro to return the
> value 0; if `val` is 0, the `setjmp` macro returns the value 1.
>
> _Taken from ยง7.13.2.1.4 of the C99 spec_

See https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=268521 for my similar
patch for arm64 libc. That patch also has a test-case that I used to test this
RISC-V implementation.

---

I think I've actually managed to beat the compiler in this patch.

Both GCC and Clang do something like the following at `-Os`:

```Assembly
        mv      a0,a1
        bne     a1,zero,.L2
        li      a0,1
.L2:
        ret
```

It took a while of scouring the RISC-V ISA spec (it's my first time using
RISC-V assembly), but I found a method that doesn't use branching and has less
one less instruction!

-- 
You are receiving this mail because:
You are the assignee for the bug.