Improve Malloc Failure Test
[openssl.git] / crypto / mem.c
1 /*
2  * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 "internal/e_os.h"
11 #include "internal/cryptlib.h"
12 #include "crypto/cryptlib.h"
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <limits.h>
16 #include <openssl/crypto.h>
17
18 /*
19  * the following pointers may be changed as long as 'allow_customize' is set
20  */
21 static int allow_customize = 1;
22 static CRYPTO_malloc_fn malloc_impl = CRYPTO_malloc;
23 static CRYPTO_realloc_fn realloc_impl = CRYPTO_realloc;
24 static CRYPTO_free_fn free_impl = CRYPTO_free;
25
26 #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE)
27 # include "internal/tsan_assist.h"
28
29 # ifdef TSAN_REQUIRES_LOCKING
30 #  define INCREMENT(x) /* empty */
31 #  define LOAD(x) 0
32 # else  /* TSAN_REQUIRES_LOCKING */
33 static TSAN_QUALIFIER int malloc_count;
34 static TSAN_QUALIFIER int realloc_count;
35 static TSAN_QUALIFIER int free_count;
36
37 #  define INCREMENT(x) tsan_counter(&(x))
38 #  define LOAD(x)      tsan_load(&x)
39 # endif /* TSAN_REQUIRES_LOCKING */
40
41 static char *md_failstring;
42 static long md_count;
43 static int md_fail_percent = 0;
44 static int md_tracefd = -1;
45
46 static void parseit(void);
47 static int shouldfail(void);
48
49 # define FAILTEST() if (shouldfail()) return NULL
50
51 #else
52
53 # define INCREMENT(x) /* empty */
54 # define FAILTEST() /* empty */
55 #endif
56
57 int CRYPTO_set_mem_functions(CRYPTO_malloc_fn malloc_fn,
58                              CRYPTO_realloc_fn realloc_fn,
59                              CRYPTO_free_fn free_fn)
60 {
61     if (!allow_customize)
62         return 0;
63     if (malloc_fn != NULL)
64         malloc_impl = malloc_fn;
65     if (realloc_fn != NULL)
66         realloc_impl = realloc_fn;
67     if (free_fn != NULL)
68         free_impl = free_fn;
69     return 1;
70 }
71
72 void CRYPTO_get_mem_functions(CRYPTO_malloc_fn *malloc_fn,
73                               CRYPTO_realloc_fn *realloc_fn,
74                               CRYPTO_free_fn *free_fn)
75 {
76     if (malloc_fn != NULL)
77         *malloc_fn = malloc_impl;
78     if (realloc_fn != NULL)
79         *realloc_fn = realloc_impl;
80     if (free_fn != NULL)
81         *free_fn = free_impl;
82 }
83
84 #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE)
85 void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount)
86 {
87     if (mcount != NULL)
88         *mcount = LOAD(malloc_count);
89     if (rcount != NULL)
90         *rcount = LOAD(realloc_count);
91     if (fcount != NULL)
92         *fcount = LOAD(free_count);
93 }
94
95 /*
96  * Parse a "malloc failure spec" string.  This likes like a set of fields
97  * separated by semicolons.  Each field has a count and an optional failure
98  * percentage.  For example:
99  *          100@0;100@25;0@0
100  *    or    100;100@25;0
101  * This means 100 mallocs succeed, then next 100 fail 25% of the time, and
102  * all remaining (count is zero) succeed.
103  * The failure percentge can have 2 digits after the comma.  For example:
104  *          0@0.01
105  * This means 0.01% of all allocations will fail.
106  */
107 static void parseit(void)
108 {
109     char *semi = strchr(md_failstring, ';');
110     char *atsign;
111
112     if (semi != NULL)
113         *semi++ = '\0';
114
115     /* Get the count (atol will stop at the @ if there), and percentage */
116     md_count = atol(md_failstring);
117     atsign = strchr(md_failstring, '@');
118     md_fail_percent = atsign == NULL ? 0 : (int)(atof(atsign + 1) * 100 + 0.5);
119
120     if (semi != NULL)
121         md_failstring = semi;
122 }
123
124 /*
125  * Windows doesn't have random(), but it has rand()
126  * Some rand() implementations aren't good, but we're not
127  * dealing with secure randomness here.
128  */
129 # ifdef _WIN32
130 #  define random() rand()
131 # endif
132 /*
133  * See if the current malloc should fail.
134  */
135 static int shouldfail(void)
136 {
137     int roll = (int)(random() % 10000);
138     int shoulditfail = roll < md_fail_percent;
139 # ifndef _WIN32
140 /* suppressed on Windows as POSIX-like file descriptors are non-inheritable */
141     int len;
142     char buff[80];
143
144     if (md_tracefd > 0) {
145         BIO_snprintf(buff, sizeof(buff),
146                      "%c C%ld %%%d R%d\n",
147                      shoulditfail ? '-' : '+', md_count, md_fail_percent, roll);
148         len = strlen(buff);
149         if (write(md_tracefd, buff, len) != len)
150             perror("shouldfail write failed");
151     }
152 # endif
153
154     if (md_count) {
155         /* If we used up this one, go to the next. */
156         if (--md_count == 0)
157             parseit();
158     }
159
160     return shoulditfail;
161 }
162
163 void ossl_malloc_setup_failures(void)
164 {
165     const char *cp = getenv("OPENSSL_MALLOC_FAILURES");
166
167     if (cp != NULL && (md_failstring = strdup(cp)) != NULL)
168         parseit();
169     if ((cp = getenv("OPENSSL_MALLOC_FD")) != NULL)
170         md_tracefd = atoi(cp);
171     if ((cp = getenv("OPENSSL_MALLOC_SEED")) != NULL)
172         srandom(atoi(cp));
173 }
174 #endif
175
176 void *CRYPTO_malloc(size_t num, const char *file, int line)
177 {
178     void *ptr;
179
180     INCREMENT(malloc_count);
181     if (malloc_impl != CRYPTO_malloc) {
182         ptr = malloc_impl(num, file, line);
183         if (ptr != NULL || num == 0)
184             return ptr;
185         goto err;
186     }
187
188     if (num == 0)
189         return NULL;
190
191     FAILTEST();
192     if (allow_customize) {
193         /*
194          * Disallow customization after the first allocation. We only set this
195          * if necessary to avoid a store to the same cache line on every
196          * allocation.
197          */
198         allow_customize = 0;
199     }
200
201     ptr = malloc(num);
202     if (ptr != NULL)
203         return ptr;
204  err:
205     /*
206      * ossl_err_get_state_int() in err.c uses CRYPTO_zalloc(num, NULL, 0) for
207      * ERR_STATE allocation. Prevent mem alloc error loop while reporting error.
208      */
209     if (file != NULL || line != 0) {
210         ERR_new();
211         ERR_set_debug(file, line, NULL);
212         ERR_set_error(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE, NULL);
213     }
214     return NULL;
215 }
216
217 void *CRYPTO_zalloc(size_t num, const char *file, int line)
218 {
219     void *ret;
220
221     ret = CRYPTO_malloc(num, file, line);
222     if (ret != NULL)
223         memset(ret, 0, num);
224
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 != CRYPTO_realloc)
232         return realloc_impl(str, num, file, line);
233
234     if (str == NULL)
235         return CRYPTO_malloc(num, file, line);
236
237     if (num == 0) {
238         CRYPTO_free(str, file, line);
239         return NULL;
240     }
241
242     FAILTEST();
243     return realloc(str, num);
244 }
245
246 void *CRYPTO_clear_realloc(void *str, size_t old_len, size_t num,
247                            const char *file, int line)
248 {
249     void *ret = NULL;
250
251     if (str == NULL)
252         return CRYPTO_malloc(num, file, line);
253
254     if (num == 0) {
255         CRYPTO_clear_free(str, old_len, file, line);
256         return NULL;
257     }
258
259     /* Can't shrink the buffer since memcpy below copies |old_len| bytes. */
260     if (num < old_len) {
261         OPENSSL_cleanse((char*)str + num, old_len - num);
262         return str;
263     }
264
265     ret = CRYPTO_malloc(num, file, line);
266     if (ret != NULL) {
267         memcpy(ret, str, old_len);
268         CRYPTO_clear_free(str, old_len, file, line);
269     }
270     return ret;
271 }
272
273 void CRYPTO_free(void *str, const char *file, int line)
274 {
275     INCREMENT(free_count);
276     if (free_impl != CRYPTO_free) {
277         free_impl(str, file, line);
278         return;
279     }
280
281     free(str);
282 }
283
284 void CRYPTO_clear_free(void *str, size_t num, const char *file, int line)
285 {
286     if (str == NULL)
287         return;
288     if (num)
289         OPENSSL_cleanse(str, num);
290     CRYPTO_free(str, file, line);
291 }
292
293 #if !defined(OPENSSL_NO_CRYPTO_MDEBUG)
294
295 # ifndef OPENSSL_NO_DEPRECATED_3_0
296 int CRYPTO_mem_ctrl(int mode)
297 {
298     (void)mode;
299     return -1;
300 }
301
302 int CRYPTO_set_mem_debug(int flag)
303 {
304     (void)flag;
305     return -1;
306 }
307
308 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
309 {
310     (void)info; (void)file; (void)line;
311     return 0;
312 }
313
314 int CRYPTO_mem_debug_pop(void)
315 {
316     return 0;
317 }
318
319 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int flag,
320                              const char *file, int line)
321 {
322     (void)addr; (void)num; (void)flag; (void)file; (void)line;
323 }
324
325 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num, int flag,
326                               const char *file, int line)
327 {
328     (void)addr1; (void)addr2; (void)num; (void)flag; (void)file; (void)line;
329 }
330
331 void CRYPTO_mem_debug_free(void *addr, int flag,
332                            const char *file, int line)
333 {
334     (void)addr; (void)flag; (void)file; (void)line;
335 }
336
337 int CRYPTO_mem_leaks(BIO *b)
338 {
339     (void)b;
340     return -1;
341 }
342
343 #  ifndef OPENSSL_NO_STDIO
344 int CRYPTO_mem_leaks_fp(FILE *fp)
345 {
346     (void)fp;
347     return -1;
348 }
349 #  endif
350
351 int CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u),
352                         void *u)
353 {
354     (void)cb; (void)u;
355     return -1;
356 }
357
358 # endif
359
360 #endif