summaryrefslogtreecommitdiff
path: root/include/linux/overflow.h
diff options
context:
space:
mode:
authorKees Cook <keescook@chromium.org>2024-01-26 22:09:50 -0800
committerKees Cook <keescook@chromium.org>2024-02-29 13:38:01 -0800
commit08d45ee84bb2650e237e150caca87cc4ded9b3e2 (patch)
tree0f0474672597c717e276bcd41242f7d50535aa9c /include/linux/overflow.h
parentd70de8054c58d7bd9a4654c9f4797d29fa46d545 (diff)
downloadlwn-08d45ee84bb2650e237e150caca87cc4ded9b3e2.tar.gz
lwn-08d45ee84bb2650e237e150caca87cc4ded9b3e2.zip
overflow: Introduce wrapping_assign_add() and wrapping_assign_sub()
This allows replacements of the idioms "var += offset" and "var -= offset" with the wrapping_assign_add() and wrapping_assign_sub() helpers respectively. They will avoid wrap-around sanitizer instrumentation. Add to the selftests to validate behavior and lack of side-effects. Reviewed-by: Marco Elver <elver@google.com> Acked-by: Mark Rutland <mark.rutland@arm.com> Signed-off-by: Kees Cook <keescook@chromium.org>
Diffstat (limited to 'include/linux/overflow.h')
-rw-r--r--include/linux/overflow.h32
1 files changed, 32 insertions, 0 deletions
diff --git a/include/linux/overflow.h b/include/linux/overflow.h
index d3ff8e2bec29..dede374832c9 100644
--- a/include/linux/overflow.h
+++ b/include/linux/overflow.h
@@ -82,6 +82,22 @@ static inline bool __must_check __must_check_overflow(bool overflow)
})
/**
+ * wrapping_assign_add() - Intentionally perform a wrapping increment assignment
+ * @var: variable to be incremented
+ * @offset: amount to add
+ *
+ * Increments @var by @offset with wrap-around. Returns the resulting
+ * value of @var. Will not trip any wrap-around sanitizers.
+ *
+ * Returns the new value of @var.
+ */
+#define wrapping_assign_add(var, offset) \
+ ({ \
+ typeof(var) *__ptr = &(var); \
+ *__ptr = wrapping_add(typeof(var), *__ptr, offset); \
+ })
+
+/**
* check_sub_overflow() - Calculate subtraction with overflow checking
* @a: minuend; value to subtract from
* @b: subtrahend; value to subtract from @a
@@ -112,6 +128,22 @@ static inline bool __must_check __must_check_overflow(bool overflow)
})
/**
+ * wrapping_assign_sub() - Intentionally perform a wrapping decrement assign
+ * @var: variable to be decremented
+ * @offset: amount to subtract
+ *
+ * Decrements @var by @offset with wrap-around. Returns the resulting
+ * value of @var. Will not trip any wrap-around sanitizers.
+ *
+ * Returns the new value of @var.
+ */
+#define wrapping_assign_sub(var, offset) \
+ ({ \
+ typeof(var) *__ptr = &(var); \
+ *__ptr = wrapping_sub(typeof(var), *__ptr, offset); \
+ })
+
+/**
* check_mul_overflow() - Calculate multiplication with overflow checking
* @a: first factor
* @b: second factor