Skip to content

Commit b308bf1

Browse files
committed
Merge branch 'maint'
* maint: compat: helper for detecting unsigned overflow
2 parents 1a9fe45 + 1368f65 commit b308bf1

File tree

4 files changed

+11
-4
lines changed

4 files changed

+11
-4
lines changed

git-compat-util.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@
3131
#define maximum_signed_value_of_type(a) \
3232
(INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
3333

34+
#define maximum_unsigned_value_of_type(a) \
35+
(UINTMAX_MAX >> (bitsizeof(uintmax_t) - bitsizeof(a)))
36+
3437
/*
3538
* Signed integer overflow is undefined in C, so here's a helper macro
3639
* to detect if the sum of two integers will overflow.
@@ -40,6 +43,9 @@
4043
#define signed_add_overflows(a, b) \
4144
((b) > maximum_signed_value_of_type(a) - (a))
4245

46+
#define unsigned_add_overflows(a, b) \
47+
((b) > maximum_unsigned_value_of_type(a) - (a))
48+
4349
#ifdef __GNUC__
4450
#define TYPEOF(x) (__typeof__(x))
4551
#else

patch-delta.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ void *patch_delta(const void *src_buf, unsigned long src_size,
4848
if (cmd & 0x20) cp_size |= (*data++ << 8);
4949
if (cmd & 0x40) cp_size |= (*data++ << 16);
5050
if (cp_size == 0) cp_size = 0x10000;
51-
if (cp_off + cp_size < cp_size ||
51+
if (unsigned_add_overflows(cp_off, cp_size) ||
5252
cp_off + cp_size > src_size ||
5353
cp_size > size)
5454
break;

strbuf.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,8 @@ void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
6363

6464
void strbuf_grow(struct strbuf *sb, size_t extra)
6565
{
66-
if (sb->len + extra + 1 <= sb->len)
66+
if (unsigned_add_overflows(extra, 1) ||
67+
unsigned_add_overflows(sb->len, extra + 1))
6768
die("you want to use way too much memory");
6869
if (!sb->alloc)
6970
sb->buf = NULL;
@@ -152,7 +153,7 @@ int strbuf_cmp(const struct strbuf *a, const struct strbuf *b)
152153
void strbuf_splice(struct strbuf *sb, size_t pos, size_t len,
153154
const void *data, size_t dlen)
154155
{
155-
if (pos + len < pos)
156+
if (unsigned_add_overflows(pos, len))
156157
die("you want to use way too much memory");
157158
if (pos > sb->len)
158159
die("`pos' is too far after the end of the buffer");

wrapper.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ void *xmalloc(size_t size)
5353
void *xmallocz(size_t size)
5454
{
5555
void *ret;
56-
if (size + 1 < size)
56+
if (unsigned_add_overflows(size, 1))
5757
die("Data too large to fit into virtual memory space.");
5858
ret = xmalloc(size + 1);
5959
((char*)ret)[size] = 0;

0 commit comments

Comments
 (0)