1 /*
2  * by Scarlett. public domain.
3  * replacements for w3m's allocation macros which add overflow
4  * detection and concentrate the macros in one file
5  */
6 #ifndef W3_ALLOC_H
7 #define W3_ALLOC_H
8 #include <gc.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <limits.h>
12 
13 static inline size_t
z_mult_no_oflow_(size_t n,size_t size)14 z_mult_no_oflow_(size_t n, size_t size)
15 {
16 	if (size != 0 && n > ULONG_MAX / size) {
17 		fprintf(stderr,
18 		    "w3m: overflow in malloc, %lu*%lu\n", (unsigned long)n, (unsigned long)size);
19 		exit(1);
20 	}
21 	return n * size;
22 }
23 
24 #define New(type) \
25 	(GC_MALLOC(sizeof(type)))
26 
27 #define NewAtom(type) \
28 	(GC_MALLOC_ATOMIC(sizeof(type)))
29 
30 #define New_N(type, n) \
31 	(GC_MALLOC(z_mult_no_oflow_((n), sizeof(type))))
32 
33 #define NewAtom_N(type, n) \
34 	(GC_MALLOC_ATOMIC(z_mult_no_oflow_((n), sizeof(type))))
35 
36 #define New_Reuse(type, ptr, n) \
37 	(GC_REALLOC((ptr), z_mult_no_oflow_((n), sizeof(type))))
38 
39 #endif /* W3_ALLOC_H */
40