aboutsummaryrefslogtreecommitdiff
path: root/include
diff options
context:
space:
mode:
authorDag-Erling Smørgrav <des@FreeBSD.org>2023-09-07 06:14:54 +0000
committerDag-Erling Smørgrav <des@FreeBSD.org>2023-09-07 06:40:14 +0000
commite6615b10347caf67f5bc12c9a8e30b8ddd9860ae (patch)
treed426c1c434062d934c8b511fd0e146589ddf0b22 /include
parent12b1c1e3fb446021a881d9815465137843fca50b (diff)
downloadsrc-e6615b10347caf67f5bc12c9a8e30b8ddd9860ae.tar.gz
src-e6615b10347caf67f5bc12c9a8e30b8ddd9860ae.zip
include: Implement N2867.
This adds macros for checked addition, subtraction, and multiplication with semantics similar to the builtins gcc and clang have had for years. Reviewed by: kib, emaste Differential Revision: https://reviews.freebsd.org/D41734
Diffstat (limited to 'include')
-rw-r--r--include/Makefile2
-rw-r--r--include/stdckdint.h40
2 files changed, 41 insertions, 1 deletions
diff --git a/include/Makefile b/include/Makefile
index 1d7651216cf9..bc1cfd96dfc9 100644
--- a/include/Makefile
+++ b/include/Makefile
@@ -30,7 +30,7 @@ INCS= a.out.h ar.h assert.h bitstring.h byteswap.h \
pthread_np.h pwd.h ranlib.h readpassphrase.h regex.h \
res_update.h resolv.h runetype.h sched.h \
search.h semaphore.h setjmp.h \
- signal.h spawn.h stab.h stdalign.h stdbool.h stddef.h \
+ signal.h spawn.h stab.h stdalign.h stdbool.h stdckdint.h stddef.h \
stdnoreturn.h stdio.h stdlib.h string.h stringlist.h \
strings.h sysexits.h tar.h termios.h tgmath.h \
time.h timeconv.h timers.h ttyent.h \
diff --git a/include/stdckdint.h b/include/stdckdint.h
new file mode 100644
index 000000000000..af3074dded89
--- /dev/null
+++ b/include/stdckdint.h
@@ -0,0 +1,40 @@
+/*-
+ * Copyright (c) 2023 Dag-Erling Smørgrav
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#ifndef __STDC_VERSION_STDCKDINT_H__
+#define __STDC_VERSION_STDCKDINT_H__ 202311L
+
+#include <sys/cdefs.h>
+
+#if __BSD_VISIBLE || __ISO_C_VISIBLE >= 2023
+
+#if __GNUC_PREREQ__(5, 1) || __has_builtin(__builtin_add_overflow)
+#define ckd_add(result, a, b) \
+ (_Bool)__builtin_add_overflow((a), (b), (result))
+#else
+#define ckd_add(result, a, b) \
+ _Static_assert(0, "checked addition not supported")
+#endif
+
+#if __GNUC_PREREQ__(5, 1) || __has_builtin(__builtin_sub_overflow)
+#define ckd_sub(result, a, b) \
+ (_Bool)__builtin_sub_overflow((a), (b), (result))
+#else
+#define ckd_sub(result, a, b) \
+ _Static_assert(0, "checked subtraction not supported")
+#endif
+
+#if __GNUC_PREREQ__(5, 1) || __has_builtin(__builtin_mul_overflow)
+#define ckd_mul(result, a, b) \
+ (_Bool)__builtin_mul_overflow((a), (b), (result))
+#else
+#define ckd_mul(result, a, b) \
+ _Static_assert(0, "checked multiplication not supported")
+#endif
+
+#endif
+
+#endif