[PATCH v6 2/2] tools/nolibc: fix up size inflate regression

From: Zhangjin Wu
Date: Fri Aug 11 2023 - 17:52:16 EST


As reported and suggested by Willy, the inline __sysret() helper
introduces three types of conversions and increases the size:

(1) the "unsigned long" argument to __sysret() forces a sign extension
from all sys_* functions that used to return 'int'

(2) the comparison with the error range now has to be performed on a
'unsigned long' instead of an 'int'

(3) the return value from __sysret() is a 'long' (note, a signed long)
which then has to be turned back to an 'int' before being returned by the
caller to satisfy the caller's prototype.

To fix up this, firstly, let's use macro instead of inline function to
preserves the input type and avoids these useless conversions (1), (3).

Secondly, since all of the sys_* functions have been converted to return
integer, now, it is able to remove comparison to a 'unsigned long'
-MAX_ERRNO (2) and restore the simple sign comparison as before.

Suggested-by: Willy Tarreau <w@xxxxxx>
Link: https://lore.kernel.org/lkml/20230806095846.GB10627@xxxxxx/
Signed-off-by: Zhangjin Wu <falcon@xxxxxxxxxxx>
---
tools/include/nolibc/sys.h | 27 ++++++++++-----------------
1 file changed, 10 insertions(+), 17 deletions(-)

diff --git a/tools/include/nolibc/sys.h b/tools/include/nolibc/sys.h
index a28e7fbff448..e0b68d3532b6 100644
--- a/tools/include/nolibc/sys.h
+++ b/tools/include/nolibc/sys.h
@@ -27,23 +27,16 @@
#include "errno.h"
#include "types.h"

-
-/* Syscall return helper for library routines, set errno as -ret when ret is in
- * range of [-MAX_ERRNO, -1]
- *
- * Note, No official reference states the errno range here aligns with musl
- * (src/internal/syscall_ret.c) and glibc (sysdeps/unix/sysv/linux/sysdep.h)
- */
-
-static __inline__ __attribute__((unused, always_inline))
-long __sysret(unsigned long ret)
-{
- if (ret >= (unsigned long)-MAX_ERRNO) {
- SET_ERRNO(-(long)ret);
- return -1;
- }
- return ret;
-}
+/* Syscall return helper, set errno as -ret when ret < 0 */
+#define __sysret(arg) \
+({ \
+ __typeof__(arg) __ret = (arg); \
+ if (__ret < 0) { \
+ SET_ERRNO(-__ret); \
+ __ret = -1L; \
+ } \
+ __ret; \
+})

/* Functions in this file only describe syscalls. They're declared static so
* that the compiler usually decides to inline them while still being allowed
--
2.25.1