commit 9817f61535da145c316a4bb5861ed913bc16b4cf
parent 022be48b38a5286cd9845f8397d8e491df80af31
Author: sin <sin@2f30.org>
Date: Tue, 26 Feb 2019 11:10:48 +0000
Implement helpers for overflow detection
Diffstat:
3 files changed, 20 insertions(+), 7 deletions(-)
diff --git a/dedup.c b/dedup.c
@@ -4,7 +4,6 @@
#include <err.h>
#include <fcntl.h>
-#include <limits.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
@@ -136,16 +135,15 @@ free_snap(struct snapshot *snap)
static struct snapshot *
grow_snap(struct snapshot *snap, uint64_t nr_blk_descs)
{
- size_t size, mul;
+ size_t size;
- if (nr_blk_descs > SIZE_MAX / sizeof(snap->blk_desc[0]))
+ if (mul_overflow(nr_blk_descs, sizeof(snap->blk_desc[0])))
errx(1, "grow_snap: overflow");
- mul = nr_blk_descs * sizeof(snap->blk_desc[0]);
+ size = nr_blk_descs * sizeof(snap->blk_desc[0]);
- size = sizeof(*snap);
- if (size > SIZE_MAX - mul)
+ if (add_overflow(size, sizeof(*snap)))
errx(1, "grow_snap: overflow");
- size += mul;
+ size += sizeof(*snap);
snap = realloc(snap, size);
if (snap == NULL)
diff --git a/dedup.h b/dedup.h
@@ -96,3 +96,5 @@ void str2bin(char *s, uint8_t *d);
off_t xlseek(int fd, off_t offset, int whence);
ssize_t xread(int fd, void *buf, size_t nbytes);
ssize_t xwrite(int fd, const void *buf, size_t nbytes);
+int mul_overflow(size_t a, size_t b);
+int add_overflow(size_t a, size_t b);
diff --git a/utils.c b/utils.c
@@ -1,6 +1,7 @@
#include <sys/types.h>
#include <err.h>
+#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
@@ -65,3 +66,15 @@ xwrite(int fd, const void *buf, size_t nbytes)
}
return total;
}
+
+int
+mul_overflow(size_t a, size_t b)
+{
+ return a > SIZE_MAX / b;
+}
+
+int
+add_overflow(size_t a, size_t b)
+{
+ return a > SIZE_MAX - b;
+}