Add CRYPTO_get_alloc_counts.
[openssl.git] / crypto / mem.c
1 /*
2  * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "e_os.h"
11 #include "internal/cryptlib.h"
12 #include "internal/cryptlib_int.h"
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <limits.h>
16 #include <openssl/crypto.h>
17 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
18 # include <execinfo.h>
19 #endif
20
21 /*
22  * the following pointers may be changed as long as 'allow_customize' is set
23  */
24 static int allow_customize = 1;
25
26 static void *(*malloc_impl)(size_t, const char *, int)
27     = CRYPTO_malloc;
28 static void *(*realloc_impl)(void *, size_t, const char *, int)
29     = CRYPTO_realloc;
30 static void (*free_impl)(void *, const char *, int)
31     = CRYPTO_free;
32
33 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
34 static int malloc_count;
35 static int realloc_count;
36 static int free_count;
37 static int dummy;
38
39 # define INCREMENT(x) CRYPTO_atomic_add(&x, 1, &dummy, memdbg_lock)
40 # define GET(ret, val) CRYPTO_atomic_read(&val, ret, memdbg_lock)
41
42 static char *md_failstring;
43 static long md_count;
44 static int md_fail_percent = 0;
45 static int md_tracefd = -1;
46 static int call_malloc_debug = 1;
47
48 static void parseit(void);
49 static int shouldfail(void);
50
51 # define FAILTEST() if (shouldfail()) return NULL
52
53 #else
54 static int call_malloc_debug = 0;
55
56 # define INCREMENT(x) /* empty */
57 # define FAILTEST() /* empty */
58 #endif
59
60 int CRYPTO_set_mem_functions(
61         void *(*m)(size_t, const char *, int),
62         void *(*r)(void *, size_t, const char *, int),
63         void (*f)(void *, const char *, int))
64 {
65     if (!allow_customize)
66         return 0;
67     if (m)
68         malloc_impl = m;
69     if (r)
70         realloc_impl = r;
71     if (f)
72         free_impl = f;
73     return 1;
74 }
75
76 int CRYPTO_set_mem_debug(int flag)
77 {
78     if (!allow_customize)
79         return 0;
80     call_malloc_debug = flag;
81     return 1;
82 }
83
84 void CRYPTO_get_mem_functions(
85         void *(**m)(size_t, const char *, int),
86         void *(**r)(void *, size_t, const char *, int),
87         void (**f)(void *, const char *, int))
88 {
89     if (m != NULL)
90         *m = malloc_impl;
91     if (r != NULL)
92         *r = realloc_impl;
93     if (f != NULL)
94         *f = free_impl;
95 }
96
97 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
98 void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount)
99 {
100     if (mcount != NULL)
101         GET(mcount, malloc_count);
102     if (rcount != NULL)
103         GET(rcount, realloc_count);
104     if (fcount != NULL)
105         GET(fcount, free_count);
106 }
107
108 /*
109  * Parse a "malloc failure spec" string.  This likes like a set of fields
110  * separated by semicolons.  Each field has a count and an optional failure
111  * percentage.  For example:
112  *          100@0;100@25;0@0
113  *    or    100;100@25;0
114  * This means 100 mallocs succeed, then next 100 fail 25% of the time, and
115  * all remaining (count is zero) succeed.
116  */
117 static void parseit(void)
118 {
119     char *semi = strchr(md_failstring, ';');
120     char *atsign;
121
122     if (semi != NULL)
123         *semi++ = '\0';
124
125     /* Get the count (atol will stop at the @ if there), and percentage */
126     md_count = atol(md_failstring);
127     atsign = strchr(md_failstring, '@');
128     md_fail_percent = atsign == NULL ? 0 : atoi(atsign + 1);
129
130     if (semi != NULL)
131         md_failstring = semi;
132 }
133
134 /*
135  * Windows doesn't have random(), but it has rand()
136  * Some rand() implementations aren't good, but we're not
137  * dealing with secure randomness here.
138  */
139 #ifdef _WIN32
140 # define random() rand()
141 #endif
142 /*
143  * See if the current malloc should fail.
144  */
145 static int shouldfail(void)
146 {
147     int roll = (int)(random() % 100);
148     int shoulditfail = roll < md_fail_percent;
149     int len;
150     char buff[80];
151
152     if (md_tracefd > 0) {
153         BIO_snprintf(buff, sizeof(buff),
154                      "%c C%ld %%%d R%d\n",
155                      shoulditfail ? '-' : '+', md_count, md_fail_percent, roll);
156         len = strlen(buff);
157         if (write(md_tracefd, buff, len) != len)
158             perror("shouldfail write failed");
159 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
160         if (shoulditfail) {
161             void *addrs[30];
162             int num = backtrace(addrs, OSSL_NELEM(addrs));
163
164             backtrace_symbols_fd(addrs, num, md_tracefd);
165         }
166 #endif
167     }
168
169     if (md_count) {
170         /* If we used up this one, go to the next. */
171         if (--md_count == 0)
172             parseit();
173     }
174
175     return shoulditfail;
176 }
177
178 void ossl_malloc_setup_failures(void)
179 {
180     const char *cp = getenv("OPENSSL_MALLOC_FAILURES");
181
182     if (cp != NULL && (md_failstring = strdup(cp)) != NULL)
183         parseit();
184     if ((cp = getenv("OPENSSL_MALLOC_FD")) != NULL)
185         md_tracefd = atoi(cp);
186 }
187 #endif
188
189 void *CRYPTO_malloc(size_t num, const char *file, int line)
190 {
191     void *ret = NULL;
192
193     INCREMENT(malloc_count);
194     if (malloc_impl != NULL && malloc_impl != CRYPTO_malloc)
195         return malloc_impl(num, file, line);
196
197     if (num == 0)
198         return NULL;
199
200     FAILTEST();
201     allow_customize = 0;
202 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
203     if (call_malloc_debug) {
204         CRYPTO_mem_debug_malloc(NULL, num, 0, file, line);
205         ret = malloc(num);
206         CRYPTO_mem_debug_malloc(ret, num, 1, file, line);
207     } else {
208         ret = malloc(num);
209     }
210 #else
211     (void)(file); (void)(line);
212     ret = malloc(num);
213 #endif
214
215     return ret;
216 }
217
218 void *CRYPTO_zalloc(size_t num, const char *file, int line)
219 {
220     void *ret = CRYPTO_malloc(num, file, line);
221
222     FAILTEST();
223     if (ret != NULL)
224         memset(ret, 0, num);
225     return ret;
226 }
227
228 void *CRYPTO_realloc(void *str, size_t num, const char *file, int line)
229 {
230     INCREMENT(realloc_count);
231     if (realloc_impl != NULL && realloc_impl != &CRYPTO_realloc)
232         return realloc_impl(str, num, file, line);
233
234     FAILTEST();
235     if (str == NULL)
236         return CRYPTO_malloc(num, file, line);
237
238     if (num == 0) {
239         CRYPTO_free(str, file, line);
240         return NULL;
241     }
242
243     allow_customize = 0;
244 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
245     if (call_malloc_debug) {
246         void *ret;
247         CRYPTO_mem_debug_realloc(str, NULL, num, 0, file, line);
248         ret = realloc(str, num);
249         CRYPTO_mem_debug_realloc(str, ret, num, 1, file, line);
250         return ret;
251     }
252 #else
253     (void)(file); (void)(line);
254 #endif
255     return realloc(str, num);
256
257 }
258
259 void *CRYPTO_clear_realloc(void *str, size_t old_len, size_t num,
260                            const char *file, int line)
261 {
262     void *ret = NULL;
263
264     if (str == NULL)
265         return CRYPTO_malloc(num, file, line);
266
267     if (num == 0) {
268         CRYPTO_clear_free(str, old_len, file, line);
269         return NULL;
270     }
271
272     /* Can't shrink the buffer since memcpy below copies |old_len| bytes. */
273     if (num < old_len) {
274         OPENSSL_cleanse((char*)str + num, old_len - num);
275         return str;
276     }
277
278     ret = CRYPTO_malloc(num, file, line);
279     if (ret != NULL) {
280         memcpy(ret, str, old_len);
281         CRYPTO_clear_free(str, old_len, file, line);
282     }
283     return ret;
284 }
285
286 void CRYPTO_free(void *str, const char *file, int line)
287 {
288     INCREMENT(free_count);
289     if (free_impl != NULL && free_impl != &CRYPTO_free) {
290         free_impl(str, file, line);
291         return;
292     }
293
294 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
295     if (call_malloc_debug) {
296         CRYPTO_mem_debug_free(str, 0, file, line);
297         free(str);
298         CRYPTO_mem_debug_free(str, 1, file, line);
299     } else {
300         free(str);
301     }
302 #else
303     free(str);
304 #endif
305 }
306
307 void CRYPTO_clear_free(void *str, size_t num, const char *file, int line)
308 {
309     if (str == NULL)
310         return;
311     if (num)
312         OPENSSL_cleanse(str, num);
313     CRYPTO_free(str, file, line);
314 }