@matheusbsbs / matheus-bagliano / commits / c03c83152d
Fork 0

do not depend on signed integer overflow

Signed integer overflow is not defined in C, so do not depend on it. This fixes a problem with GCC 4.4.0 and -O3 where the optimizer would consider "consumed_bytes > consumed_bytes + bytes" as a constant expression, and never execute the die()-call. Signed-off-by: Erik Faye-Lund <kusmabite@gmail.com> Acked-by: Nicolas Pitre <nico@fluxnic.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Erik Faye-Lund committed Oct 5, 2010 at 09:24 UTC c03c83152d6ce6fa5ae49a8698da5fc25a53127f
4 files changed +15 -3
builtin/index-pack.c
+1 -1
@@ -161,7 +161,7 @@ static void use(int bytes)
161 input_offset += bytes;
162
163 /* make sure off_t is sufficiently large not to wrap */
164 - if (consumed_bytes > consumed_bytes + bytes)
164 + if (signed_add_overflows(consumed_bytes, bytes))
165 die("pack too large for current definition of off_t");
166 consumed_bytes += bytes;
167 }
builtin/pack-objects.c
+1 -1
@@ -431,7 +431,7 @@ static int write_one(struct sha1file *f,
431 written_list[nr_written++] = &e->idx;
432
433 /* make sure off_t is sufficiently large not to wrap */
434 - if (*offset > *offset + size)
434 + if (signed_add_overflows(*offset, size))
435 die("pack too large for current definition of off_t");
436 *offset += size;
437 return 1;
builtin/unpack-objects.c
+1 -1
@@ -83,7 +83,7 @@ static void use(int bytes)
83 offset += bytes;
84
85 /* make sure off_t is sufficiently large not to wrap */
86 - if (consumed_bytes > consumed_bytes + bytes)
86 + if (signed_add_overflows(consumed_bytes, bytes))
87 die("pack too large for current definition of off_t");
88 consumed_bytes += bytes;
89 }
git-compat-util.h
+12
@@ -28,6 +28,18 @@
28 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
29 #define bitsizeof(x) (CHAR_BIT * sizeof(x))
30
31 +#define maximum_signed_value_of_type(a) \
32 + (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
33 +
34 +/*
35 + * Signed integer overflow is undefined in C, so here's a helper macro
36 + * to detect if the sum of two integers will overflow.
37 + *
38 + * Requires: a >= 0, typeof(a) equals typeof(b)
39 + */
40 +#define signed_add_overflows(a, b) \
41 + ((b) > maximum_signed_value_of_type(a) - (a))
42 +
43 #ifdef __GNUC__
44 #define TYPEOF(x) (__typeof__(x))
45 #else