[PATCH 1/4] tools/nolibc: unistd.h: add __syscall() and __syscall_ret() helpers

From: Zhangjin Wu
Date: Sun Jun 04 2023 - 01:35:33 EST


most of the library routines share the same code model, let's add some
macros to simplify the coding and shrink the code lines too.

One added for syscall return, one added for syscall call, both of them
can get the typeof 'return value' automatically.

To get the return type of syscalls, __auto_type is better than typeof(),
but it is not supported by the old compilers (before 2013, see [1]), so,
use typeof() here.

[1]: https://gcc.gnu.org/legacy-ml/gcc-patches/2013-11/msg01378.html

Signed-off-by: Zhangjin Wu <falcon@xxxxxxxxxxx>
---
tools/include/nolibc/sys.h | 15 +++++++++++++++
1 file changed, 15 insertions(+)

diff --git a/tools/include/nolibc/sys.h b/tools/include/nolibc/sys.h
index 1d6f33f58629..937a8578e3d4 100644
--- a/tools/include/nolibc/sys.h
+++ b/tools/include/nolibc/sys.h
@@ -28,6 +28,21 @@
#include "errno.h"
#include "types.h"

+/* Syscall call and return helpers */
+#define __syscall_ret(ret) \
+({ \
+ if (ret < 0) { \
+ SET_ERRNO(-ret); \
+ ret = (typeof(ret))-1; \
+ } \
+ ret; \
+})
+
+#define __syscall(name, ...) \
+({ \
+ typeof(sys_##name(__VA_ARGS__)) ret = sys_##name(__VA_ARGS__); \
+ __syscall_ret(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