[PATCH] newlib: riscv: Remove undefined behavior in strlen()
Kito Cheng
kito.cheng@gmail.com
Mon Jun 2 08:29:48 GMT 2025
Pushed, thanks :)
On Fri, May 30, 2025 at 11:01 AM Eric Salem <ericsalem@gmail.com> wrote:
>
> Pointer arithmetic overflow is undefined behavior, so use a signed type
> to avoid it.
>
> Signed-off-by: Eric Salem <ericsalem@gmail.com>
> ---
> While strlen() has worked this way since the beginning, it's better to
> not depend on compilers not changing the behavior when optimizing. Clang
> will take advantage of this:
> https://releases.llvm.org/20.1.0/tools/clang/docs/ReleaseNotes.html#potentially-breaking-changes
>
> newlib/libc/machine/riscv/strlen.c | 5 ++++-
> 1 file changed, 4 insertions(+), 1 deletion(-)
>
> diff --git a/newlib/libc/machine/riscv/strlen.c b/newlib/libc/machine/riscv/strlen.c
> index 9f1be1b0e70e..8ab5ce53737a 100644
> --- a/newlib/libc/machine/riscv/strlen.c
> +++ b/newlib/libc/machine/riscv/strlen.c
> @@ -9,6 +9,7 @@
> http://www.opensource.org/licenses.
> */
>
> +#include <sys/types.h>
> #include <string.h>
> #include <stdint.h>
> #include "rv_string.h"
> @@ -38,7 +39,9 @@ size_t strlen(const char *str)
> asm volatile ("" : "+r"(ps)); /* prevent "optimization" */
>
> str = (const char *)ps;
> - size_t ret = str - start, sp = sizeof (*ps);
> +
> + size_t ret = str - start;
> + ssize_t sp = sizeof (*ps);
>
> #if __riscv_zbb
> psval = ~__LIBC_RISCV_ZBB_ORC_B(psval);
> --
> 2.49.0
>
More information about the Newlib
mailing list