In an effort to separate intentional arithmetic wrap-around from
unexpected wrap-around, we need to refactor places that depend on this
kind of math. One of the most common code patterns of this is:

        VAR + value < VAR

Notably, this is considered "undefined behavior" for signed and pointer
types, which the kernel works around by using the -fno-strict-overflow
option in the build[1] (which used to just be -fwrapv). Regardless, we
want to get the kernel source to the position where we can meaningfully
instrument arithmetic wrap-around conditions and catch them when they
are unexpected, regardless of whether they are signed[2], unsigned[3],
or pointer[4] types.

Refactor open-coded unsigned wrap-around addition test to use
check_add_overflow(), retaining the result for later usage (which removes
the redundant open-coded addition). This paves the way to enabling the
wrap-around sanitizer in the future.

Link: https://git.kernel.org/linus/68df3755e383e6fecf2354a67b08f92f18536594 [1]
Link: https://github.com/KSPP/linux/issues/26 [2]
Link: https://github.com/KSPP/linux/issues/27 [3]
Link: https://github.com/KSPP/linux/issues/344 [4]
Cc: Chris Mason <c...@fb.com>
Cc: Josef Bacik <jo...@toxicpanda.com>
Cc: David Sterba <dste...@suse.com>
Cc: linux-btrfs@vger.kernel.org
Signed-off-by: Kees Cook <keesc...@chromium.org>
---
 fs/btrfs/extent_map.c | 6 ++++--
 fs/btrfs/extent_map.h | 6 ++++--
 2 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/fs/btrfs/extent_map.c b/fs/btrfs/extent_map.c
index b61099bf97a8..29a649507857 100644
--- a/fs/btrfs/extent_map.c
+++ b/fs/btrfs/extent_map.c
@@ -73,9 +73,11 @@ void free_extent_map(struct extent_map *em)
 /* Do the math around the end of an extent, handling wrapping. */
 static u64 range_end(u64 start, u64 len)
 {
-       if (start + len < start)
+       u64 sum;
+
+       if (check_add_overflow(start, len, &sum))
                return (u64)-1;
-       return start + len;
+       return sum;
 }
 
 static int tree_insert(struct rb_root_cached *root, struct extent_map *em)
diff --git a/fs/btrfs/extent_map.h b/fs/btrfs/extent_map.h
index e380fc08bbe4..3c4a6b977662 100644
--- a/fs/btrfs/extent_map.h
+++ b/fs/btrfs/extent_map.h
@@ -108,9 +108,11 @@ static inline int extent_map_in_tree(const struct 
extent_map *em)
 
 static inline u64 extent_map_end(const struct extent_map *em)
 {
-       if (em->start + em->len < em->start)
+       u64 sum;
+
+       if (check_add_overflow(em->start, em->len, &sum))
                return (u64)-1;
-       return em->start + em->len;
+       return sum;
 }
 
 void extent_map_tree_init(struct extent_map_tree *tree);
-- 
2.34.1


Reply via email to