|
96 | 96 | #define unsigned_add_overflows(a, b) \
|
97 | 97 | ((b) > maximum_unsigned_value_of_type(a) - (a))
|
98 | 98 |
|
| 99 | +/* |
| 100 | + * Returns true if the multiplication of "a" and "b" will |
| 101 | + * overflow. The types of "a" and "b" must match and must be unsigned. |
| 102 | + * Note that this macro evaluates "a" twice! |
| 103 | + */ |
| 104 | +#define unsigned_mult_overflows(a, b) \ |
| 105 | + ((a) && (b) > maximum_unsigned_value_of_type(a) / (a)) |
| 106 | + |
99 | 107 | #ifdef __GNUC__
|
100 | 108 | #define TYPEOF(x) (__typeof__(x))
|
101 | 109 | #else
|
@@ -698,6 +706,32 @@ extern void release_pack_memory(size_t);
|
698 | 706 | typedef void (*try_to_free_t)(size_t);
|
699 | 707 | extern try_to_free_t set_try_to_free_routine(try_to_free_t);
|
700 | 708 |
|
| 709 | +static inline size_t st_add(size_t a, size_t b) |
| 710 | +{ |
| 711 | + if (unsigned_add_overflows(a, b)) |
| 712 | + die("size_t overflow: %"PRIuMAX" + %"PRIuMAX, |
| 713 | + (uintmax_t)a, (uintmax_t)b); |
| 714 | + return a + b; |
| 715 | +} |
| 716 | +#define st_add3(a,b,c) st_add((a),st_add((b),(c))) |
| 717 | +#define st_add4(a,b,c,d) st_add((a),st_add3((b),(c),(d))) |
| 718 | + |
| 719 | +static inline size_t st_mult(size_t a, size_t b) |
| 720 | +{ |
| 721 | + if (unsigned_mult_overflows(a, b)) |
| 722 | + die("size_t overflow: %"PRIuMAX" * %"PRIuMAX, |
| 723 | + (uintmax_t)a, (uintmax_t)b); |
| 724 | + return a * b; |
| 725 | +} |
| 726 | + |
| 727 | +static inline size_t st_sub(size_t a, size_t b) |
| 728 | +{ |
| 729 | + if (a < b) |
| 730 | + die("size_t underflow: %"PRIuMAX" - %"PRIuMAX, |
| 731 | + (uintmax_t)a, (uintmax_t)b); |
| 732 | + return a - b; |
| 733 | +} |
| 734 | + |
701 | 735 | #ifdef HAVE_ALLOCA_H
|
702 | 736 | # include <alloca.h>
|
703 | 737 | # define xalloca(size) (alloca(size))
|
|
0 commit comments