From e6615b10347caf67f5bc12c9a8e30b8ddd9860ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= Date: Thu, 7 Sep 2023 06:14:54 +0000 Subject: 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 --- include/Makefile | 2 +- include/stdckdint.h | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 include/stdckdint.h (limited to 'include') 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 + +#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 -- cgit v1.2.3