Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

tools/nolibc: add abs() and friends

This is used in various selftests and will be handy when integrating
those with nolibc.

Signed-off-by: Thomas Weißschuh <thomas.weissschuh@linutronix.de>
Acked-by: Willy Tarreau <w@1wt.eu>
Link: https://lore.kernel.org/r/20250428-nolibc-misc-v2-6-3c043eeab06c@linutronix.de
Signed-off-by: Thomas Weißschuh <linux@weissschuh.net>

authored by

Thomas Weißschuh and committed by
Thomas Weißschuh
bf5e8a78 801f020b

+53
+1
tools/include/nolibc/Makefile
··· 35 35 fcntl.h \ 36 36 getopt.h \ 37 37 limits.h \ 38 + math.h \ 38 39 nolibc.h \ 39 40 poll.h \ 40 41 signal.h \
+31
tools/include/nolibc/math.h
··· 1 + /* SPDX-License-Identifier: LGPL-2.1 OR MIT */ 2 + /* 3 + * math definitions for NOLIBC 4 + * Copyright (C) 2025 Thomas Weißschuh <thomas.weissschuh@linutronix.de> 5 + */ 6 + 7 + /* make sure to include all global symbols */ 8 + #include "nolibc.h" 9 + 10 + #ifndef _NOLIBC_SYS_MATH_H 11 + #define _NOLIBC_SYS_MATH_H 12 + 13 + static __inline__ 14 + double fabs(double x) 15 + { 16 + return x >= 0 ? x : -x; 17 + } 18 + 19 + static __inline__ 20 + float fabsf(float x) 21 + { 22 + return x >= 0 ? x : -x; 23 + } 24 + 25 + static __inline__ 26 + long double fabsl(long double x) 27 + { 28 + return x >= 0 ? x : -x; 29 + } 30 + 31 + #endif /* _NOLIBC_SYS_MATH_H */
+1
tools/include/nolibc/nolibc.h
··· 116 116 #include "fcntl.h" 117 117 #include "getopt.h" 118 118 #include "poll.h" 119 + #include "math.h" 119 120 120 121 /* Used by programs to avoid std includes */ 121 122 #define NOLIBC
+18
tools/include/nolibc/stdlib.h
··· 32 32 * As much as possible, please keep functions alphabetically sorted. 33 33 */ 34 34 35 + static __inline__ 36 + int abs(int j) 37 + { 38 + return j >= 0 ? j : -j; 39 + } 40 + 41 + static __inline__ 42 + long labs(long j) 43 + { 44 + return j >= 0 ? j : -j; 45 + } 46 + 47 + static __inline__ 48 + long long llabs(long long j) 49 + { 50 + return j >= 0 ? j : -j; 51 + } 52 + 35 53 /* must be exported, as it's used by libgcc for various divide functions */ 36 54 void abort(void); 37 55 __attribute__((weak,unused,noreturn,section(".text.nolibc_abort")))
+2
tools/testing/selftests/nolibc/nolibc-test.c
··· 1318 1318 CASE_TEST(tolower_noop); EXPECT_EQ(1, tolower('a'), 'a'); break; 1319 1319 CASE_TEST(toupper); EXPECT_EQ(1, toupper('a'), 'A'); break; 1320 1320 CASE_TEST(toupper_noop); EXPECT_EQ(1, toupper('A'), 'A'); break; 1321 + CASE_TEST(abs); EXPECT_EQ(1, abs(-10), 10); break; 1322 + CASE_TEST(abs_noop); EXPECT_EQ(1, abs(10), 10); break; 1321 1323 1322 1324 case __LINE__: 1323 1325 return ret; /* must be last */