2 * PuTTY's memory allocation wrappers.
5 #ifdef ALLOCATION_ALIGNMENT
6 /* Before we include standard headers, define _ISOC11_SOURCE so that
7 * we get the declaration of aligned_alloc(). */
19 void *safemalloc(size_t factor1
, size_t factor2
, size_t addend
)
21 if (factor1
> SIZE_MAX
/ factor2
)
23 size_t product
= factor1
* factor2
;
25 if (addend
> SIZE_MAX
)
27 if (product
> SIZE_MAX
- addend
)
29 size_t size
= product
+ addend
;
36 p
= minefield_c_malloc(size
);
37 #elif defined ALLOCATION_ALIGNMENT
38 p
= aligned_alloc(ALLOCATION_ALIGNMENT
, size
);
52 void *saferealloc(void *ptr
, size_t n
, size_t size
)
56 if (n
> INT_MAX
/ size
) {
62 p
= minefield_c_malloc(size
);
63 #elif defined ALLOCATION_ALIGNMENT
64 p
= aligned_alloc(ALLOCATION_ALIGNMENT
, size
);
70 p
= minefield_c_realloc(ptr
, size
);
72 p
= realloc(ptr
, size
);
83 void safefree(void *ptr
)
87 minefield_c_free(ptr
);
94 void *safegrowarray(void *ptr
, size_t *allocated
, size_t eltsize
,
95 size_t oldlen
, size_t extralen
, bool secret
)
97 /* The largest value we can safely multiply by eltsize */
99 size_t maxsize
= (~(size_t)0) / eltsize
;
101 size_t oldsize
= *allocated
;
103 /* Range-check the input values */
104 assert(oldsize
<= maxsize
);
105 assert(oldlen
<= maxsize
);
106 assert(extralen
<= maxsize
- oldlen
);
108 /* If the size is already enough, don't bother doing anything! */
109 if (oldsize
> oldlen
+ extralen
)
112 /* Find out how much we need to grow the array by. */
113 size_t increment
= (oldlen
+ extralen
) - oldsize
;
115 /* Invent a new size. We want to grow the array by at least
116 * 'increment' elements; by at least a fixed number of bytes (to
117 * get things started when sizes are small); and by some constant
118 * factor of its old size (to avoid repeated calls to this
119 * function taking quadratic time overall). */
120 if (increment
< 256 / eltsize
)
121 increment
= 256 / eltsize
;
122 if (increment
< oldsize
/ 16)
123 increment
= oldsize
/ 16;
125 /* But we also can't grow beyond maxsize. */
126 size_t maxincr
= maxsize
- oldsize
;
127 if (increment
> maxincr
)
130 size_t newsize
= oldsize
+ increment
;
133 toret
= safemalloc(newsize
, eltsize
, 0);
135 memcpy(toret
, ptr
, oldsize
* eltsize
);
136 smemclr(ptr
, oldsize
* eltsize
);
140 toret
= saferealloc(ptr
, newsize
, eltsize
);
142 *allocated
= newsize
;