Coverage Report

Created: 2025-06-13 06:56

/src/openssl/crypto/mem.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 1995-2024 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_failbuf[CRYPTO_MEM_CHECK_MAX_FS + 1];
42
static char *md_failstring = NULL;
43
static long md_count;
44
static int md_fail_percent = 0;
45
static int md_tracefd = -1;
46
47
static void parseit(void);
48
static int shouldfail(void);
49
50
# define FAILTEST() if (shouldfail()) return NULL
51
52
#else
53
54
# define INCREMENT(x) /* empty */
55
# define FAILTEST() /* empty */
56
#endif
57
58
int CRYPTO_set_mem_functions(CRYPTO_malloc_fn malloc_fn,
59
                             CRYPTO_realloc_fn realloc_fn,
60
                             CRYPTO_free_fn free_fn)
61
0
{
62
0
    if (!allow_customize)
63
0
        return 0;
64
0
    if (malloc_fn != NULL)
65
0
        malloc_impl = malloc_fn;
66
0
    if (realloc_fn != NULL)
67
0
        realloc_impl = realloc_fn;
68
0
    if (free_fn != NULL)
69
0
        free_impl = free_fn;
70
0
    return 1;
71
0
}
72
73
void CRYPTO_get_mem_functions(CRYPTO_malloc_fn *malloc_fn,
74
                              CRYPTO_realloc_fn *realloc_fn,
75
                              CRYPTO_free_fn *free_fn)
76
0
{
77
0
    if (malloc_fn != NULL)
78
0
        *malloc_fn = malloc_impl;
79
0
    if (realloc_fn != NULL)
80
0
        *realloc_fn = realloc_impl;
81
0
    if (free_fn != NULL)
82
0
        *free_fn = free_impl;
83
0
}
84
85
#if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE)
86
void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount)
87
{
88
    if (mcount != NULL)
89
        *mcount = LOAD(malloc_count);
90
    if (rcount != NULL)
91
        *rcount = LOAD(realloc_count);
92
    if (fcount != NULL)
93
        *fcount = LOAD(free_count);
94
}
95
96
/*
97
 * Parse a "malloc failure spec" string.  This likes like a set of fields
98
 * separated by semicolons.  Each field has a count and an optional failure
99
 * percentage.  For example:
100
 *          100@0;100@25;0@0
101
 *    or    100;100@25;0
102
 * This means 100 mallocs succeed, then next 100 fail 25% of the time, and
103
 * all remaining (count is zero) succeed.
104
 * The failure percentge can have 2 digits after the comma.  For example:
105
 *          0@0.01
106
 * This means 0.01% of all allocations will fail.
107
 */
108
static void parseit(void)
109
{
110
    char *semi = strchr(md_failstring, ';');
111
    char *atsign;
112
113
    if (semi != NULL)
114
        *semi++ = '\0';
115
116
    /* Get the count (atol will stop at the @ if there), and percentage */
117
    md_count = atol(md_failstring);
118
    atsign = strchr(md_failstring, '@');
119
    md_fail_percent = atsign == NULL ? 0 : (int)(atof(atsign + 1) * 100 + 0.5);
120
121
    if (semi != NULL)
122
        md_failstring = semi;
123
}
124
125
/*
126
 * Windows doesn't have random() and srandom(), but it has rand() and srand().
127
 * Some rand() implementations aren't good, but we're not
128
 * dealing with secure randomness here.
129
 */
130
# ifdef _WIN32
131
#  define random() rand()
132
#  define srandom(seed) srand(seed)
133
# endif
134
/*
135
 * See if the current malloc should fail.
136
 */
137
static int shouldfail(void)
138
{
139
    int roll = (int)(random() % 10000);
140
    int shoulditfail = roll < md_fail_percent;
141
# ifndef _WIN32
142
/* suppressed on Windows as POSIX-like file descriptors are non-inheritable */
143
    int len;
144
    char buff[80];
145
146
    if (md_tracefd > 0) {
147
        BIO_snprintf(buff, sizeof(buff),
148
                     "%c C%ld %%%d R%d\n",
149
                     shoulditfail ? '-' : '+', md_count, md_fail_percent, roll);
150
        len = strlen(buff);
151
        if (write(md_tracefd, buff, len) != len)
152
            perror("shouldfail write failed");
153
    }
154
# endif
155
156
    if (md_count) {
157
        /* If we used up this one, go to the next. */
158
        if (--md_count == 0)
159
            parseit();
160
    }
161
162
    return shoulditfail;
163
}
164
165
void ossl_malloc_setup_failures(void)
166
{
167
    const char *cp = getenv("OPENSSL_MALLOC_FAILURES");
168
    size_t cplen = 0;
169
170
    if (cp != NULL) {
171
        /* if the value is too long we'll just ignore it */
172
        cplen = strlen(cp);
173
        if (cplen <= CRYPTO_MEM_CHECK_MAX_FS) {
174
            strncpy(md_failbuf, cp, CRYPTO_MEM_CHECK_MAX_FS);
175
            md_failstring = md_failbuf;
176
            parseit();
177
        }
178
    }
179
    if ((cp = getenv("OPENSSL_MALLOC_FD")) != NULL)
180
        md_tracefd = atoi(cp);
181
    if ((cp = getenv("OPENSSL_MALLOC_SEED")) != NULL)
182
        srandom(atoi(cp));
183
}
184
#endif
185
186
void *CRYPTO_malloc(size_t num, const char *file, int line)
187
479k
{
188
479k
    void *ptr;
189
190
479k
    INCREMENT(malloc_count);
191
479k
    if (malloc_impl != CRYPTO_malloc) {
192
0
        ptr = malloc_impl(num, file, line);
193
0
        if (ptr != NULL || num == 0)
194
0
            return ptr;
195
0
        goto err;
196
0
    }
197
198
479k
    if (num == 0)
199
0
        return NULL;
200
201
479k
    FAILTEST();
202
479k
    if (allow_customize) {
203
        /*
204
         * Disallow customization after the first allocation. We only set this
205
         * if necessary to avoid a store to the same cache line on every
206
         * allocation.
207
         */
208
2
        allow_customize = 0;
209
2
    }
210
211
479k
    ptr = malloc(num);
212
479k
    if (ptr != NULL)
213
479k
        return ptr;
214
0
 err:
215
    /*
216
     * ossl_err_get_state_int() in err.c uses CRYPTO_zalloc(num, NULL, 0) for
217
     * ERR_STATE allocation. Prevent mem alloc error loop while reporting error.
218
     */
219
0
    if (file != NULL || line != 0) {
220
0
        ERR_new();
221
0
        ERR_set_debug(file, line, NULL);
222
0
        ERR_set_error(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE, NULL);
223
0
    }
224
0
    return NULL;
225
479k
}
226
227
void *CRYPTO_zalloc(size_t num, const char *file, int line)
228
133k
{
229
133k
    void *ret;
230
231
133k
    ret = CRYPTO_malloc(num, file, line);
232
133k
    if (ret != NULL)
233
133k
        memset(ret, 0, num);
234
235
133k
    return ret;
236
133k
}
237
238
void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr,
239
                           const char *file, int line)
240
4
{
241
4
    void *ret;
242
243
4
    *freeptr = NULL;
244
245
#if defined(OPENSSL_SMALL_FOOTPRINT)
246
    ret = freeptr = NULL;
247
    return ret;
248
#endif
249
250
    /* Allow non-malloc() allocations as long as no malloc_impl is provided. */
251
4
    if (malloc_impl == CRYPTO_malloc) {
252
4
#if defined(_BSD_SOURCE) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
253
4
        if (posix_memalign(&ret, alignment, num))
254
0
            return NULL;
255
4
        *freeptr = ret;
256
4
        return ret;
257
#elif defined(_ISOC11_SOURCE)
258
        ret = *freeptr = aligned_alloc(alignment, num);
259
        return ret;
260
#endif
261
4
    }
262
263
    /* we have to do this the hard way */
264
265
    /*
266
     * Note: Windows supports an _aligned_malloc call, but we choose
267
     * not to use it here, because allocations from that function
268
     * require that they be freed via _aligned_free.  Given that
269
     * we can't differentiate plain malloc blocks from blocks obtained
270
     * via _aligned_malloc, just avoid its use entirely
271
     */
272
273
    /*
274
     * Step 1: Allocate an amount of memory that is <alignment>
275
     * bytes bigger than requested
276
     */
277
0
    *freeptr = CRYPTO_malloc(num + alignment, file, line);
278
0
    if (*freeptr == NULL)
279
0
        return NULL;
280
281
    /*
282
     * Step 2: Add <alignment - 1> bytes to the pointer
283
     * This will cross the alignment boundary that is
284
     * requested
285
     */
286
0
    ret = (void *)((char *)*freeptr + (alignment - 1));
287
288
    /*
289
     * Step 3: Use the alignment as a mask to translate the
290
     * least significant bits of the allocation at the alignment
291
     * boundary to 0.  ret now holds a pointer to the memory
292
     * buffer at the requested alignment
293
     * NOTE: It is a documented requirement that alignment be a
294
     * power of 2, which is what allows this to work
295
     */
296
0
    ret = (void *)((uintptr_t)ret & (uintptr_t)(~(alignment - 1)));
297
0
    return ret;
298
0
}
299
300
void *CRYPTO_realloc(void *str, size_t num, const char *file, int line)
301
101k
{
302
101k
    INCREMENT(realloc_count);
303
101k
    if (realloc_impl != CRYPTO_realloc)
304
0
        return realloc_impl(str, num, file, line);
305
306
101k
    if (str == NULL)
307
81.9k
        return CRYPTO_malloc(num, file, line);
308
309
19.6k
    if (num == 0) {
310
0
        CRYPTO_free(str, file, line);
311
0
        return NULL;
312
0
    }
313
314
19.6k
    FAILTEST();
315
19.6k
    return realloc(str, num);
316
19.6k
}
317
318
void *CRYPTO_clear_realloc(void *str, size_t old_len, size_t num,
319
                           const char *file, int line)
320
7.53k
{
321
7.53k
    void *ret = NULL;
322
323
7.53k
    if (str == NULL)
324
2.99k
        return CRYPTO_malloc(num, file, line);
325
326
4.54k
    if (num == 0) {
327
0
        CRYPTO_clear_free(str, old_len, file, line);
328
0
        return NULL;
329
0
    }
330
331
    /* Can't shrink the buffer since memcpy below copies |old_len| bytes. */
332
4.54k
    if (num < old_len) {
333
0
        OPENSSL_cleanse((char*)str + num, old_len - num);
334
0
        return str;
335
0
    }
336
337
4.54k
    ret = CRYPTO_malloc(num, file, line);
338
4.54k
    if (ret != NULL) {
339
4.54k
        memcpy(ret, str, old_len);
340
4.54k
        CRYPTO_clear_free(str, old_len, file, line);
341
4.54k
    }
342
4.54k
    return ret;
343
4.54k
}
344
345
void CRYPTO_free(void *str, const char *file, int line)
346
681k
{
347
681k
    INCREMENT(free_count);
348
681k
    if (free_impl != CRYPTO_free) {
349
0
        free_impl(str, file, line);
350
0
        return;
351
0
    }
352
353
681k
    free(str);
354
681k
}
355
356
void CRYPTO_clear_free(void *str, size_t num, const char *file, int line)
357
10.8k
{
358
10.8k
    if (str == NULL)
359
0
        return;
360
10.8k
    if (num)
361
10.8k
        OPENSSL_cleanse(str, num);
362
10.8k
    CRYPTO_free(str, file, line);
363
10.8k
}
364
365
#if !defined(OPENSSL_NO_CRYPTO_MDEBUG)
366
367
# ifndef OPENSSL_NO_DEPRECATED_3_0
368
int CRYPTO_mem_ctrl(int mode)
369
{
370
    (void)mode;
371
    return -1;
372
}
373
374
int CRYPTO_set_mem_debug(int flag)
375
{
376
    (void)flag;
377
    return -1;
378
}
379
380
int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
381
{
382
    (void)info; (void)file; (void)line;
383
    return 0;
384
}
385
386
int CRYPTO_mem_debug_pop(void)
387
{
388
    return 0;
389
}
390
391
void CRYPTO_mem_debug_malloc(void *addr, size_t num, int flag,
392
                             const char *file, int line)
393
{
394
    (void)addr; (void)num; (void)flag; (void)file; (void)line;
395
}
396
397
void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num, int flag,
398
                              const char *file, int line)
399
{
400
    (void)addr1; (void)addr2; (void)num; (void)flag; (void)file; (void)line;
401
}
402
403
void CRYPTO_mem_debug_free(void *addr, int flag,
404
                           const char *file, int line)
405
{
406
    (void)addr; (void)flag; (void)file; (void)line;
407
}
408
409
int CRYPTO_mem_leaks(BIO *b)
410
{
411
    (void)b;
412
    return -1;
413
}
414
415
#  ifndef OPENSSL_NO_STDIO
416
int CRYPTO_mem_leaks_fp(FILE *fp)
417
{
418
    (void)fp;
419
    return -1;
420
}
421
#  endif
422
423
int CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u),
424
                        void *u)
425
{
426
    (void)cb; (void)u;
427
    return -1;
428
}
429
430
# endif
431
432
#endif