Coverage Report

Created: 2026-10-31 07:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-sp-math/wolfcrypt/src/memory.c
Line
Count
Source
1
/* memory.c
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
/* inhibit "#undef current" in linuxkm_wc_port.h, included from wc_port.h,
23
 * because needed in linuxkm_memory.c, included below.
24
 */
25
#ifdef WOLFSSL_LINUXKM
26
    #define WOLFSSL_LINUXKM_NEED_LINUX_CURRENT
27
#endif
28
29
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
30
31
#ifdef NO_INLINE
32
    #include <wolfssl/wolfcrypt/misc.h>
33
#else
34
    #define WOLFSSL_MISC_INCLUDED
35
    #include <wolfcrypt/src/misc.c>
36
#endif
37
38
/*
39
Possible memory options:
40
 * NO_WOLFSSL_MEMORY:               Disables wolf memory callback support. When not defined settings.h defines USE_WOLFSSL_MEMORY.
41
 * WOLFSSL_STATIC_MEMORY:           Turns on the use of static memory buffers and functions.
42
                                        This allows for using static memory instead of dynamic.
43
 * WOLFSSL_STATIC_MEMORY_LEAN:      Requires WOLFSSL_STATIC_MEMORY be defined.
44
 *                                  Uses smaller type sizes for structs
45
 *                                  requiring that memory pool sizes be less
46
 *                                  then 65k and limits features available like
47
 *                                  IO buffers to reduce footprint size.
48
 * WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK:
49
 *                                  Enables option to register a debugging
50
 *                                  callback function, useful for
51
 *                                  WOLFSSL_STATIC_MEMORY builds where XMALLOC
52
 *                                  and XFREE are not user defined.
53
 * WOLFSSL_STATIC_ALIGN:            Define defaults to 16 to indicate static memory alignment.
54
 * HAVE_IO_POOL:                    Enables use of static thread safe memory pool for input/output buffers.
55
 * XMALLOC_OVERRIDE:                Allows override of the XMALLOC, XFREE and XREALLOC macros.
56
 * XMALLOC_USER:                    Allows custom XMALLOC, XFREE and XREALLOC functions to be defined.
57
 * WOLFSSL_NO_MALLOC:               Disables the fall-back case to use STDIO malloc/free when no callbacks are set.
58
 * WOLFSSL_TRACK_MEMORY:            Enables memory tracking for total stats and list of allocated memory.
59
 * WOLFSSL_DEBUG_MEMORY:            Enables extra function and line number args for memory callbacks.
60
 * WOLFSSL_DEBUG_MEMORY_PRINT:      Enables printing of each malloc/free.
61
 * WOLFSSL_MALLOC_CHECK:            Reports malloc or alignment failure using WOLFSSL_STATIC_ALIGN
62
 * WOLFSSL_FORCE_MALLOC_FAIL_TEST:  Used for internal testing to induce random malloc failures.
63
 * WOLFSSL_HEAP_TEST:               Used for internal testing of heap hint
64
 * WOLFSSL_MEM_FAIL_COUNT:          Fail memory allocation at a count from
65
 *                                  environment variable: MEM_FAIL_CNT.
66
 */
67
68
#ifdef WOLFSSL_ZEPHYR
69
#undef realloc
70
void *z_realloc(void *ptr, size_t size)
71
{
72
    if (ptr == NULL)
73
        ptr = malloc(size); /* native heap */
74
    else
75
        ptr = realloc(ptr, size); /* native heap */
76
77
    return ptr;
78
}
79
#define realloc z_realloc
80
#endif
81
82
#ifdef USE_WOLFSSL_MEMORY
83
84
#include <wolfssl/wolfcrypt/memory.h>
85
86
#if defined(WOLFSSL_DEBUG_MEMORY) && defined(WOLFSSL_DEBUG_MEMORY_PRINT)
87
#include <stdio.h>
88
#endif
89
90
#ifdef WOLFSSL_FORCE_MALLOC_FAIL_TEST
91
    static int gMemFailCountSeed;
92
    static int gMemFailCount;
93
    void wolfSSL_SetMemFailCount(int memFailCount)
94
    {
95
        if (gMemFailCountSeed == 0) {
96
            gMemFailCountSeed = memFailCount;
97
            gMemFailCount = memFailCount;
98
        }
99
    }
100
#endif
101
#if defined(WOLFSSL_MALLOC_CHECK) || defined(WOLFSSL_TRACK_MEMORY_FULL) || \
102
                                                     defined(WOLFSSL_MEMORY_LOG)
103
    #include <stdio.h>
104
#endif
105
106
107
/* Set these to default values initially. */
108
static wolfSSL_Malloc_cb  malloc_function = NULL;
109
static wolfSSL_Free_cb    free_function = NULL;
110
static wolfSSL_Realloc_cb realloc_function = NULL;
111
112
int wolfSSL_SetAllocators(wolfSSL_Malloc_cb  mf,
113
                          wolfSSL_Free_cb    ff,
114
                          wolfSSL_Realloc_cb rf)
115
36
{
116
36
    malloc_function = mf;
117
36
    free_function = ff;
118
36
    realloc_function = rf;
119
36
    return 0;
120
36
}
121
122
int wolfSSL_GetAllocators(wolfSSL_Malloc_cb*  mf,
123
                          wolfSSL_Free_cb*    ff,
124
                          wolfSSL_Realloc_cb* rf)
125
0
{
126
0
    if (mf) *mf = malloc_function;
127
0
    if (ff) *ff = free_function;
128
0
    if (rf) *rf = realloc_function;
129
0
    return 0;
130
0
}
131
132
#ifdef WOLFSSL_MEM_FAIL_COUNT
133
static wolfSSL_Mutex memFailMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(memFailMutex);
134
int mem_fail_allocs = 0;
135
int mem_fail_frees = 0;
136
int mem_fail_cnt = 0;
137
138
void wc_MemFailCount_Init(void)
139
{
140
    char* cnt;
141
#ifndef WOLFSSL_MUTEX_INITIALIZER
142
    wc_InitMutex(&memFailMutex);
143
#endif
144
    cnt = getenv("MEM_FAIL_CNT");
145
    if (cnt != NULL) {
146
        fprintf(stderr, "MemFailCount At: %d\n", mem_fail_cnt);
147
        mem_fail_cnt = atoi(cnt);
148
    }
149
}
150
static int wc_MemFailCount_AllocMem(void)
151
{
152
    int ret = 1;
153
154
    wc_LockMutex(&memFailMutex);
155
    if ((mem_fail_cnt > 0) && (mem_fail_cnt <= mem_fail_allocs + 1)) {
156
        ret = 0;
157
    }
158
    else {
159
        mem_fail_allocs++;
160
    }
161
    wc_UnLockMutex(&memFailMutex);
162
163
    return ret;
164
}
165
/* An allocation was counted by wc_MemFailCount_AllocMem() above, but the
166
 * underlying allocator then returned NULL (a caller-installed failing
167
 * allocator via wolfSSL_SetAllocators(), or a genuine out-of-memory). No
168
 * block exists to be freed, so undo the count to keep Total (allocs)
169
 * balanced with Frees. */
170
static void wc_MemFailCount_AllocFailed(void)
171
{
172
    wc_LockMutex(&memFailMutex);
173
    if (mem_fail_allocs > 0) {
174
        mem_fail_allocs--;
175
    }
176
    wc_UnLockMutex(&memFailMutex);
177
}
178
static void wc_MemFailCount_FreeMem(void)
179
{
180
    wc_LockMutex(&memFailMutex);
181
    mem_fail_frees++;
182
    wc_UnLockMutex(&memFailMutex);
183
}
184
void wc_MemFailCount_Free(void)
185
{
186
#ifndef WOLFSSL_MUTEX_INITIALIZER
187
    wc_FreeMutex(&memFailMutex);
188
#endif
189
    fprintf(stderr, "MemFailCount Total: %d\n", mem_fail_allocs);
190
    fprintf(stderr, "MemFailCount Frees: %d\n", mem_fail_frees);
191
}
192
#endif
193
194
#ifndef WOLFSSL_STATIC_MEMORY
195
#ifdef WOLFSSL_CHECK_MEM_ZERO
196
197
#ifndef WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN
198
/* Number of entries in table of addresses to check. */
199
#define WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN    256
200
#endif
201
202
/* Alignment to maintain when adding length to allocated pointer.
203
 * Intel x64 wants to use aligned loads of XMM registers.
204
 */
205
#define MEM_ALIGN       16
206
207
/* An address that is meant to be all zeros for its length. */
208
typedef struct MemZero {
209
    /* Name of address to check. */
210
    const char* name;
211
    /* Address to check. */
212
    const void* addr;
213
    /* Length of data that must be zero. */
214
    size_t len;
215
} MemZero;
216
217
/* List of addresses to check. */
218
static MemZero memZero[WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN];
219
/* Next index to place address at.
220
 * -1 indicates uninitialized.
221
 * If nextIdx is equal to WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN then all entries
222
 * have been used.
223
 */
224
static int nextIdx = -1;
225
/* Mutex to protect modifying list of addresses to check. */
226
static wolfSSL_Mutex zeroMutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(zeroMutex);
227
228
/* Initialize the table of addresses and the mutex.
229
 */
230
void wc_MemZero_Init(void)
231
{
232
    /* Clear the table to more easily see what is valid. */
233
    XMEMSET(memZero, 0, sizeof(memZero));
234
    /* Initialize mutex. */
235
#ifndef WOLFSSL_MUTEX_INITIALIZER
236
    wc_InitMutex(&zeroMutex);
237
#endif
238
    /* Next index is first entry. */
239
    nextIdx = 0;
240
}
241
242
/* Free the mutex and check we have not any uncheck addresses.
243
 */
244
void wc_MemZero_Free(void)
245
{
246
    /* Free mutex. */
247
#ifndef WOLFSSL_MUTEX_INITIALIZER
248
    wc_FreeMutex(&zeroMutex);
249
#endif
250
    /* Make sure we checked all addresses. */
251
    if (nextIdx > 0) {
252
        int i;
253
        fprintf(stderr, "[MEM_ZERO] Unseen: %d\n", nextIdx);
254
        for (i = 0; i < nextIdx; i++) {
255
            fprintf(stderr, "  %s - %p:%lu\n", memZero[i].name, memZero[i].addr,
256
                (unsigned long)memZero[i].len);
257
        }
258
    }
259
    /* Uninitialized value in next index. */
260
    nextIdx = -1;
261
}
262
263
/* Add an address to check.
264
 *
265
 * @param [in] name  Name of address to check.
266
 * @param [in] addr  Address that needs to be checked.
267
 * @param [in] len   Length of data that must be zero.
268
 */
269
void wc_MemZero_Add(const char* name, const void* addr, size_t len)
270
{
271
    /* Initialize if not done. */
272
    if (nextIdx == -1) {
273
        wc_MemZero_Init();
274
    }
275
276
    /* Add an entry to the table while locked. */
277
    wc_LockMutex(&zeroMutex);
278
    if (nextIdx < WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN) {
279
        /* Fill in the next entry and update next index. */
280
        memZero[nextIdx].name = name;
281
        memZero[nextIdx].addr = addr;
282
        memZero[nextIdx].len  = len;
283
        nextIdx++;
284
    }
285
    else {
286
        /* Abort when too many entries. */
287
        fprintf(stderr, "\n[MEM_ZERO] Too many addresses to check\n");
288
        fprintf(stderr, "[MEM_ZERO] WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN\n");
289
        abort();
290
    }
291
    wc_UnLockMutex(&zeroMutex);
292
}
293
294
/* Check the memory in the range of the address for memory that must be zero.
295
 *
296
 * @param [in] addr  Start address of memory that is to be checked.
297
 * @param [in] len   Length of data associated with address.
298
 */
299
void wc_MemZero_Check(void* addr, size_t len)
300
{
301
    int i;
302
    size_t j;
303
304
    wc_LockMutex(&zeroMutex);
305
    /* Look at each address for overlap with address passes in. */
306
    for (i = 0; i < nextIdx; i++) {
307
        if ((memZero[i].addr < addr) ||
308
               ((size_t)memZero[i].addr >= (size_t)addr + len)) {
309
            /* Check address not part of memory to check. */
310
            continue;
311
        }
312
313
        /* Address is in range of memory being freed - check each byte zero. */
314
        for (j = 0; j < memZero[i].len; j++) {
315
            if (((unsigned char*)memZero[i].addr)[j] != 0) {
316
                /* Byte not zero - abort! */
317
                fprintf(stderr, "\n[MEM_ZERO] %s:%p + %lu is not zero\n",
318
                    memZero[i].name, memZero[i].addr, (unsigned long)j);
319
                fprintf(stderr, "[MEM_ZERO] Checking %p:%lu\n", addr,
320
                    (unsigned long)len);
321
            #ifndef TEST_ALWAYS_RUN_TO_END
322
                abort();
323
            #endif
324
            }
325
        }
326
        /* Update next index to write to. */
327
        nextIdx--;
328
        if (nextIdx > 0) {
329
            /* Remove entry. */
330
            XMEMMOVE(memZero + i, memZero + i + 1,
331
                sizeof(MemZero) * (nextIdx - i));
332
            /* Clear out top to make it easier to see what is to be checked. */
333
            XMEMSET(&memZero[nextIdx], 0, sizeof(MemZero));
334
        }
335
        /* Need to check this index again with new data. */
336
        i--;
337
    }
338
    wc_UnLockMutex(&zeroMutex);
339
}
340
#endif /* WOLFSSL_CHECK_MEM_ZERO */
341
342
#ifdef WOLFSSL_DEBUG_MEMORY
343
void* wolfSSL_Malloc(size_t size, const char* func, unsigned int line)
344
#else
345
void* wolfSSL_Malloc(size_t size)
346
#endif
347
389M
{
348
389M
    void* res = 0;
349
350
#ifdef WOLFSSL_MEM_FAIL_COUNT
351
    if (!wc_MemFailCount_AllocMem()) {
352
        WOLFSSL_MSG("MemFailCnt: Fail malloc");
353
        return NULL;
354
    }
355
#endif
356
357
#ifdef WOLFSSL_CHECK_MEM_ZERO
358
    /* Space for requested size. */
359
    size += MEM_ALIGN;
360
#endif
361
362
389M
    if (malloc_function) {
363
    #ifdef WOLFSSL_DEBUG_MEMORY
364
        res = malloc_function(size, func, line);
365
    #else
366
379M
        res = malloc_function(size);
367
379M
    #endif
368
379M
    }
369
9.74M
    else {
370
9.74M
    #ifndef WOLFSSL_NO_MALLOC
371
        #ifdef WOLFSSL_TRAP_MALLOC_SZ
372
        if (size > WOLFSSL_TRAP_MALLOC_SZ) {
373
            WOLFSSL_MSG("Malloc too big!");
374
        #ifdef WOLFSSL_MEM_FAIL_COUNT
375
            /* Allocation was counted above but no block exists to free. */
376
            wc_MemFailCount_AllocFailed();
377
        #endif
378
            return NULL;
379
        }
380
        #endif
381
382
9.74M
        res = malloc(size); /* native heap */
383
    #else
384
        WOLFSSL_MSG("No malloc available");
385
    #endif
386
9.74M
    }
387
388
#ifdef WOLFSSL_CHECK_MEM_ZERO
389
    /* Restore size to requested value. */
390
    size -= MEM_ALIGN;
391
    if (res != NULL) {
392
        /* Place size at front of allocated data and move pointer passed it. */
393
        *(size_t*)res = size;
394
        res = ((unsigned char*)res) + MEM_ALIGN;
395
    }
396
#endif
397
398
#ifdef WOLFSSL_DEBUG_MEMORY
399
#if defined(WOLFSSL_DEBUG_MEMORY_PRINT) && !defined(WOLFSSL_TRACK_MEMORY)
400
    fprintf(stderr, "Alloc: %p -> %u at %s:%u\n", res, (word32)size, func, line);
401
#else
402
    (void)func;
403
    (void)line;
404
#endif
405
#endif
406
407
#ifdef WOLFSSL_MALLOC_CHECK
408
    if (res == NULL)
409
        WOLFSSL_MSG("wolfSSL_malloc failed");
410
#endif
411
412
#ifdef WOLFSSL_FORCE_MALLOC_FAIL_TEST
413
    if (res && --gMemFailCount == 0) {
414
        fprintf(stderr, "\n---FORCED MEM FAIL TEST---\n");
415
        if (free_function) {
416
        #ifdef WOLFSSL_DEBUG_MEMORY
417
            free_function(res, func, line);
418
        #else
419
            free_function(res);
420
        #endif
421
        }
422
        else {
423
            free(res); /* native heap */
424
        }
425
        gMemFailCount = gMemFailCountSeed; /* reset */
426
    #ifdef WOLFSSL_MEM_FAIL_COUNT
427
        wc_MemFailCount_AllocFailed();
428
    #endif
429
        return NULL;
430
    }
431
#endif
432
433
#ifdef WOLFSSL_MEM_FAIL_COUNT
434
    if (res == NULL) {
435
        wc_MemFailCount_AllocFailed();
436
    }
437
#endif
438
439
389M
    return res;
440
389M
}
441
442
#ifdef WOLFSSL_DEBUG_MEMORY
443
void wolfSSL_Free(void *ptr, const char* func, unsigned int line)
444
#else
445
void wolfSSL_Free(void *ptr)
446
#endif
447
402M
{
448
#ifdef WOLFSSL_DEBUG_MEMORY
449
#if defined(WOLFSSL_DEBUG_MEMORY_PRINT) && !defined(WOLFSSL_TRACK_MEMORY)
450
    fprintf(stderr, "Free: %p at %s:%u\n", ptr, func, line);
451
#else
452
    (void)func;
453
    (void)line;
454
#endif
455
#endif
456
457
#ifdef WOLFSSL_CHECK_MEM_ZERO
458
    /* Move pointer back to originally allocated pointer. */
459
    ptr = ((unsigned char*)ptr) - MEM_ALIGN;
460
    /* Check that the pointer is zero where required. */
461
    wc_MemZero_Check(((unsigned char*)ptr) + MEM_ALIGN, *(size_t*)ptr);
462
#endif
463
#ifdef WOLFSSL_MEM_FAIL_COUNT
464
    /* Only count a free when there is a block to release. A null pointer
465
     * releases nothing (ISO/IEC 9899:2018 7.22.3.3), and a failed
466
     * wolfSSL_Malloc() no longer counts an allocation, so a NULL free must
467
     * not be counted either or Frees would exceed Total. */
468
    if (ptr != NULL) {
469
        wc_MemFailCount_FreeMem();
470
    }
471
#endif
472
473
402M
    if (free_function) {
474
    #ifdef WOLFSSL_DEBUG_MEMORY
475
        free_function(ptr, func, line);
476
    #else
477
392M
        free_function(ptr);
478
392M
    #endif
479
392M
    }
480
9.74M
    else {
481
9.74M
    #ifndef WOLFSSL_NO_MALLOC
482
9.74M
        free(ptr); /* native heap */
483
    #else
484
        WOLFSSL_MSG("No free available");
485
    #endif
486
9.74M
    }
487
402M
}
488
489
#ifdef WOLFSSL_DEBUG_MEMORY
490
void* wolfSSL_Realloc(void *ptr, size_t size, const char* func, unsigned int line)
491
#else
492
void* wolfSSL_Realloc(void *ptr, size_t size)
493
#endif
494
18.5M
{
495
#ifdef WOLFSSL_CHECK_MEM_ZERO
496
    /* Can't check data that has been freed during realloc.
497
     * Manually allocated new memory, copy data and free original pointer.
498
     */
499
#ifdef WOLFSSL_DEBUG_MEMORY
500
    void* res = wolfSSL_Malloc(size, func, line);
501
#else
502
    void* res = wolfSSL_Malloc(size);
503
#endif
504
    if (ptr != NULL) {
505
        /* Copy the minimum of old and new size. */
506
        size_t copySize = *(size_t*)(((unsigned char*)ptr) - MEM_ALIGN);
507
        if (size < copySize) {
508
            copySize = size;
509
        }
510
        XMEMCPY(res, ptr, copySize);
511
        /* Dispose of old pointer. */
512
    #ifdef WOLFSSL_DEBUG_MEMORY
513
        wolfSSL_Free(ptr, func, line);
514
    #else
515
        wolfSSL_Free(ptr);
516
    #endif
517
    }
518
519
    /* Return new pointer with data copied into it. */
520
    return res;
521
#else
522
18.5M
    void* res = 0;
523
524
#ifdef WOLFSSL_MEM_FAIL_COUNT
525
    if (!wc_MemFailCount_AllocMem()) {
526
        WOLFSSL_MSG("MemFailCnt: Fail realloc");
527
        return NULL;
528
    }
529
#endif
530
531
18.5M
    if (realloc_function) {
532
    #ifdef WOLFSSL_DEBUG_MEMORY
533
        res = realloc_function(ptr, size, func, line);
534
    #else
535
18.5M
        res = realloc_function(ptr, size);
536
18.5M
    #endif
537
18.5M
    }
538
132
    else {
539
132
    #ifndef WOLFSSL_NO_MALLOC
540
132
        res = realloc(ptr, size); /* native heap */
541
    #else
542
        WOLFSSL_MSG("No realloc available");
543
    #endif
544
132
    }
545
546
#ifdef WOLFSSL_MEM_FAIL_COUNT
547
    /* realloc(NULL, n) is malloc. AllocMem() already counted it; if the
548
     * allocator returns NULL for a positive size, no block exists to free.
549
     * Do not undo a failed realloc of a live pointer: that path still
550
     * counts a free below and the original block remains. */
551
    if (res == NULL && ptr == NULL && size > 0) {
552
        wc_MemFailCount_AllocFailed();
553
    }
554
    else if (ptr != NULL) {
555
        wc_MemFailCount_FreeMem();
556
    }
557
#endif
558
559
18.5M
    return res;
560
18.5M
#endif
561
18.5M
}
562
#endif /* WOLFSSL_STATIC_MEMORY */
563
564
#if defined(WOLFSSL_TRACK_MEMORY) && defined(USE_WOLFSSL_MEMORY) && \
565
    !defined(WOLFSSL_STATIC_MEMORY)
566
#include <wolfssl/wolfcrypt/mem_track.h>
567
WOLFSSL_API memoryStats *wc_MemStats_Ptr;
568
#endif /* WOLFSSL_TRACK_MEMORY && USE_WOLFSSL_MEMORY && !WOLFSSL_STATIC_MEMORY */
569
570
#ifdef WOLFSSL_STATIC_MEMORY
571
572
struct wc_Memory {
573
    byte*  buffer;
574
    struct wc_Memory* next;
575
#ifdef WOLFSSL_STATIC_MEMORY_LEAN
576
    /* lean static memory is assumed to be under 65k */
577
    word16 sz;
578
#else
579
    word32 sz;
580
#endif
581
#ifdef WOLFSSL_DEBUG_MEMORY
582
    word16 szUsed;
583
#endif
584
};
585
586
587
#ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK
588
static DebugMemoryCb DebugCb = NULL;
589
590
/* Used to set a debug memory callback. Helpful in cases where
591
 * printf is not available. */
592
void wolfSSL_SetDebugMemoryCb(DebugMemoryCb cb)
593
{
594
    DebugCb = cb;
595
}
596
#endif
597
598
/* returns amount of memory used on success. On error returns negative value
599
   wc_Memory** list is the list that new buckets are prepended to
600
 */
601
static int wc_create_memory_buckets(byte* buffer, word32 bufSz,
602
                              word32 buckSz, word32 buckNum, wc_Memory** list) {
603
    byte*  pt  = buffer;
604
    int    ret = 0;
605
    byte memSz   = (byte)sizeof(wc_Memory);
606
    word16 padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1);
607
    word16 i;
608
609
    /* if not enough space available for bucket size then do not try */
610
    if (buckSz + memSz + padSz > bufSz) {
611
        return ret;
612
    }
613
614
    for (i = 0; i < buckNum; i++) {
615
        if ((buckSz + memSz + padSz) <= (bufSz - ret)) {
616
            /* create a new struct and set its values */
617
            wc_Memory* mem = (struct wc_Memory*)(pt);
618
            mem->sz = buckSz;
619
            mem->buffer = (byte*)pt + padSz + memSz;
620
            mem->next = NULL;
621
622
        #ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK
623
            if (DebugCb) {
624
                DebugCb(buckSz, buckSz, WOLFSSL_DEBUG_MEMORY_INIT, 0);
625
            }
626
        #endif
627
628
            /* add the newly created struct to front of list */
629
            if (*list == NULL) {
630
                *list = mem;
631
            } else {
632
                mem->next = *list;
633
                *list = mem;
634
            }
635
636
            /* advance pointer and keep track of memory used */
637
            ret += buckSz + padSz + memSz;
638
            pt  += buckSz + padSz + memSz;
639
        }
640
        else {
641
            break; /* not enough space left for more buckets of this size */
642
        }
643
    }
644
645
    return ret;
646
}
647
648
static int wc_partition_static_memory(byte* buffer, word32 sz, int flag,
649
                                                             WOLFSSL_HEAP* heap)
650
{
651
    word32 ava = sz;
652
    byte*  pt  = buffer;
653
    int    ret = 0;
654
    byte   memSz = (word32)sizeof(wc_Memory);
655
    byte   padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1);
656
657
    WOLFSSL_ENTER("wc_partition_static_memory");
658
659
    /* align pt */
660
    while ((wc_ptr_t)pt % WOLFSSL_STATIC_ALIGN && pt < (buffer + sz)) {
661
        *pt = 0x00;
662
        pt++;
663
        ava--;
664
    }
665
666
#ifdef WOLFSSL_DEBUG_MEMORY
667
    fprintf(stderr, "Allocated %d bytes for static memory @ %p\n", ava, pt);
668
#endif
669
670
    /* divide into chunks of memory and add them to available list */
671
    while (ava >= (word32)(heap->sizeList[0] + padSz + memSz)) {
672
    #ifndef WOLFSSL_STATIC_MEMORY_LEAN
673
        /* creating only IO buffers from memory passed in, max TLS is 16k */
674
        if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) {
675
            if ((ret = wc_create_memory_buckets(pt, ava,
676
                            WOLFMEM_IO_SZ, 1, &(heap->io))) < 0) {
677
                WOLFSSL_LEAVE("wc_partition_static_memory", ret);
678
                return ret;
679
            }
680
681
            /* check if no more room left for creating IO buffers */
682
            if (ret == 0) {
683
                break;
684
            }
685
686
            /* advance pointer in buffer for next buckets and keep track
687
               of how much memory is left available */
688
            pt  += ret;
689
            ava -= ret;
690
        }
691
        else
692
    #endif
693
        {
694
            int i;
695
            /* start at largest and move to smaller buckets */
696
            for (i = (WOLFMEM_MAX_BUCKETS - 1); i >= 0; i--) {
697
                if ((word32)(heap->sizeList[i] + padSz + memSz) <= ava) {
698
                    if ((ret = wc_create_memory_buckets(pt, ava,
699
                                    heap->sizeList[i], heap->distList[i],
700
                                    &(heap->ava[i]))) < 0) {
701
                        WOLFSSL_LEAVE("wc_partition_static_memory", ret);
702
                        return ret;
703
                    }
704
705
                    /* advance pointer in buffer for next buckets and keep track
706
                       of how much memory is left available */
707
                    pt  += ret;
708
                    ava -= ret;
709
                }
710
            }
711
        }
712
    }
713
714
    (void)flag;
715
    return 1;
716
}
717
718
static int wc_init_memory_heap(WOLFSSL_HEAP* heap, unsigned int listSz,
719
        const word32 *sizeList, const word32 *distList)
720
{
721
    unsigned int i;
722
723
    XMEMSET(heap, 0, sizeof(WOLFSSL_HEAP));
724
725
    /* avoid XMEMCPY for LEAN static memory build */
726
    for (i = 0; i < listSz; i++) {
727
        heap->sizeList[i] = sizeList[i];
728
    }
729
730
    for (i = 0; i < listSz; i++) {
731
        heap->distList[i] = distList[i];
732
    }
733
734
#ifndef SINGLE_THREADED
735
    if (wc_InitMutex(&(heap->memory_mutex)) != 0) {
736
        WOLFSSL_MSG("Error creating heap memory mutex");
737
        return BAD_MUTEX_E;
738
    }
739
#endif
740
741
    return 0;
742
}
743
744
int wc_LoadStaticMemory_ex(WOLFSSL_HEAP_HINT** pHint,
745
        unsigned int listSz, const word32 *sizeList,
746
        const word32 *distList, unsigned char *buf,
747
        unsigned int sz, int flag, int maxSz)
748
{
749
    WOLFSSL_HEAP*      heap = NULL;
750
    WOLFSSL_HEAP_HINT* hint = NULL;
751
    word16 idx = 0;
752
    int ret;
753
754
    WOLFSSL_ENTER("wc_LoadStaticMemory_ex");
755
756
    if (pHint == NULL || buf == NULL || sizeList == NULL || distList == NULL) {
757
        return BAD_FUNC_ARG;
758
    }
759
760
    /* Cap the listSz to the actual number of items allocated in the list. */
761
    if (listSz > WOLFMEM_MAX_BUCKETS) {
762
        WOLFSSL_MSG("Truncating the list of memory buckets");
763
        listSz = WOLFMEM_MAX_BUCKETS;
764
    }
765
766
    if ((sizeof(WOLFSSL_HEAP) + sizeof(WOLFSSL_HEAP_HINT)) > sz - idx) {
767
        WOLFSSL_MSG("Not enough memory for partition tracking");
768
        return BUFFER_E; /* not enough memory for structures */
769
    }
770
771
    /* check if hint has already been assigned */
772
    if (*pHint == NULL) {
773
        heap = (WOLFSSL_HEAP*)buf;
774
        idx += sizeof(WOLFSSL_HEAP);
775
        hint = (WOLFSSL_HEAP_HINT*)(buf + idx);
776
        idx += sizeof(WOLFSSL_HEAP_HINT);
777
778
        ret = wc_init_memory_heap(heap, listSz, sizeList, distList);
779
        if (ret != 0) {
780
            return ret;
781
        }
782
783
        XMEMSET(hint, 0, sizeof(WOLFSSL_HEAP_HINT));
784
        hint->memory = heap;
785
    }
786
    else {
787
    #ifdef WOLFSSL_HEAP_TEST
788
        /* do not load in memory if test has been set */
789
        if (heap == (void*)WOLFSSL_HEAP_TEST) {
790
            return 0;
791
        }
792
    #endif
793
794
        hint = (WOLFSSL_HEAP_HINT*)(*pHint);
795
        heap = hint->memory;
796
    }
797
798
    ret = wc_partition_static_memory(buf + idx, sz - idx, flag, heap);
799
    if (ret != 1) {
800
        WOLFSSL_MSG("Error partitioning memory");
801
        return MEMORY_E;
802
    }
803
804
#ifndef WOLFSSL_STATIC_MEMORY_LEAN
805
    /* determine what max applies too */
806
    if ((flag & WOLFMEM_IO_POOL) || (flag & WOLFMEM_IO_POOL_FIXED)) {
807
        heap->maxIO = maxSz;
808
    }
809
    else { /* general memory used in handshakes */
810
        heap->maxHa = maxSz;
811
    }
812
    heap->flag |= flag;
813
#endif
814
    *pHint = hint;
815
816
    (void)maxSz;
817
    return 0;
818
}
819
820
int wc_LoadStaticMemory(WOLFSSL_HEAP_HINT** pHint,
821
    unsigned char* buf, unsigned int sz, int flag, int maxSz)
822
{
823
    word32 sizeList[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_BUCKETS };
824
    word32 distList[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_DIST };
825
    int ret = 0;
826
827
    WOLFSSL_ENTER("wc_LoadStaticMemory");
828
    ret = wc_LoadStaticMemory_ex(pHint,
829
            WOLFMEM_DEF_BUCKETS, sizeList, distList,
830
            buf, sz, flag, maxSz);
831
    WOLFSSL_LEAVE("wc_LoadStaticMemory", ret);
832
    return ret;
833
}
834
835
836
void wc_UnloadStaticMemory(WOLFSSL_HEAP_HINT* heap)
837
{
838
    WOLFSSL_ENTER("wc_UnloadStaticMemory");
839
#ifndef SINGLE_THREADED
840
    if (heap != NULL && heap->memory != NULL) {
841
        wc_FreeMutex(&heap->memory->memory_mutex);
842
    }
843
#else
844
    (void)heap;
845
#endif
846
}
847
848
#ifndef WOLFSSL_STATIC_MEMORY_LEAN
849
/* returns the size of management memory needed for each bucket.
850
 * This is memory that is used to keep track of and align memory buckets. */
851
int wolfSSL_MemoryPaddingSz(void)
852
{
853
    word32 memSz = (word32)sizeof(wc_Memory);
854
    word32 padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1);
855
    return memSz + padSz;
856
}
857
858
859
/* Used to calculate memory size for optimum use with buckets.
860
   returns the suggested size rounded down to the nearest bucket. */
861
int wolfSSL_StaticBufferSz_ex(unsigned int listSz,
862
        const word32 *sizeList, const word32 *distList,
863
        byte* buffer, word32 sz, int flag)
864
{
865
    word32 ava = sz;
866
    byte*  pt  = buffer;
867
    word32 memSz = (word32)sizeof(wc_Memory);
868
    word32 padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1);
869
870
    WOLFSSL_ENTER("wolfSSL_StaticBufferSz_ex");
871
872
    if (buffer == NULL || sizeList == NULL || distList == NULL) {
873
        return BAD_FUNC_ARG;
874
    }
875
876
    /* Cap the listSz to the actual number of items allocated in the list. */
877
    if (listSz > WOLFMEM_MAX_BUCKETS) {
878
        WOLFSSL_MSG("Truncating the list of memory buckets");
879
        listSz = WOLFMEM_MAX_BUCKETS;
880
    }
881
882
    /* align pt */
883
    while ((wc_ptr_t)pt % WOLFSSL_STATIC_ALIGN && pt < (buffer + sz)) {
884
        pt++;
885
        ava--;
886
    }
887
888
#ifndef WOLFSSL_STATIC_MEMORY_LEAN
889
    /* creating only IO buffers from memory passed in, max TLS is 16k */
890
    if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) {
891
        if (ava < (memSz + padSz + WOLFMEM_IO_SZ)) {
892
            return 0; /* not enough room for even one bucket */
893
        }
894
895
        ava = ava % (memSz + padSz + WOLFMEM_IO_SZ);
896
    }
897
    else
898
#endif
899
    {
900
        int i, k;
901
902
        if (ava < (sizeList[0] + padSz + memSz)) {
903
            return 0; /* not enough room for even one bucket */
904
        }
905
906
        while ((ava >= (sizeList[0] + padSz + memSz)) && (ava > 0)) {
907
            /* start at largest and move to smaller buckets */
908
            for (i = (listSz - 1); i >= 0; i--) {
909
                for (k = distList[i]; k > 0; k--) {
910
                    if ((sizeList[i] + padSz + memSz) <= ava) {
911
                        ava -= sizeList[i] + padSz + memSz;
912
                    }
913
                }
914
            }
915
        }
916
    }
917
918
    WOLFSSL_LEAVE("wolfSSL_StaticBufferSz_ex", sz - ava);
919
    return sz - ava; /* round down */
920
}
921
922
923
/* Calls wolfSSL_StaticBufferSz_ex with the static memory pool config
924
 * used by wolfSSL by default. */
925
int wolfSSL_StaticBufferSz(byte* buffer, word32 sz, int flag)
926
{
927
    word32 bucketSz[WOLFMEM_DEF_BUCKETS] = {WOLFMEM_BUCKETS};
928
    word32 distList[WOLFMEM_DEF_BUCKETS] = {WOLFMEM_DIST};
929
930
    return wolfSSL_StaticBufferSz_ex(WOLFMEM_DEF_BUCKETS, bucketSz, distList,
931
        buffer, sz, flag);
932
}
933
934
935
int FreeFixedIO(WOLFSSL_HEAP* heap, wc_Memory** io)
936
{
937
    WOLFSSL_MSG("Freeing fixed IO buffer");
938
939
    /* check if fixed buffer was set */
940
    if (*io == NULL) {
941
        return 1;
942
    }
943
944
    if (heap == NULL) {
945
        WOLFSSL_MSG("No heap to return fixed IO too");
946
    }
947
    else {
948
        /* put IO buffer back into IO pool */
949
        (*io)->next = heap->io;
950
        heap->io    = *io;
951
        *io         = NULL;
952
    }
953
954
    return 1;
955
}
956
957
958
int SetFixedIO(WOLFSSL_HEAP* heap, wc_Memory** io)
959
{
960
    WOLFSSL_MSG("Setting fixed IO for SSL");
961
    if (heap == NULL) {
962
        return MEMORY_E;
963
    }
964
965
    *io = heap->io;
966
967
    if (*io != NULL) {
968
        heap->io = (*io)->next;
969
        (*io)->next = NULL;
970
    }
971
    else { /* failed to grab an IO buffer */
972
        return 0;
973
    }
974
975
    return 1;
976
}
977
978
979
int wolfSSL_GetMemStats(WOLFSSL_HEAP* heap, WOLFSSL_MEM_STATS* stats)
980
{
981
        word32     i;
982
        wc_Memory* pt;
983
984
        XMEMSET(stats, 0, sizeof(WOLFSSL_MEM_STATS));
985
986
        stats->totalAlloc = heap->alloc;
987
        stats->totalFr    = heap->frAlc;
988
        stats->curAlloc   = stats->totalAlloc - stats->totalFr;
989
        stats->maxHa      = heap->maxHa;
990
        stats->maxIO      = heap->maxIO;
991
        for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) {
992
            stats->blockSz[i] = heap->sizeList[i];
993
            for (pt = heap->ava[i]; pt != NULL; pt = pt->next) {
994
                stats->avaBlock[i] += 1;
995
            }
996
        }
997
998
        for (pt = heap->io; pt != NULL; pt = pt->next) {
999
            stats->avaIO++;
1000
        }
1001
1002
        stats->flag       = heap->flag; /* flag used */
1003
1004
    return 1;
1005
}
1006
#endif /* !WOLFSSL_STATIC_MEMORY_LEAN */
1007
1008
1009
/* global heap hint to fall back on when no heap hint is passed to
1010
 * XMALLOC/XFREE
1011
 * NOT thread safe, should be set once before any expected XMALLOC XFREE calls
1012
 */
1013
static void* globalHeapHint = NULL;
1014
1015
1016
/* Used to set a new global heap hint. Returns a pointer to the current global
1017
 * heap hint before being set. */
1018
void* wolfSSL_SetGlobalHeapHint(void* heap)
1019
{
1020
    void *oldHint = globalHeapHint;
1021
1022
    globalHeapHint = heap;
1023
    return oldHint;
1024
}
1025
1026
1027
/* returns a pointer to the current global heap hint */
1028
void* wolfSSL_GetGlobalHeapHint(void)
1029
{
1030
    return globalHeapHint;
1031
}
1032
1033
1034
#ifdef WOLFSSL_DEBUG_MEMORY
1035
void* wolfSSL_Malloc(size_t size, void* heap, int type, const char* func, unsigned int line)
1036
#else
1037
void* wolfSSL_Malloc(size_t size, void* heap, int type)
1038
#endif
1039
{
1040
    void* res = 0;
1041
    wc_Memory* pt = NULL;
1042
    int   i;
1043
1044
    /* check for testing heap hint was set */
1045
#ifdef WOLFSSL_HEAP_TEST
1046
    if (heap == (void*)WOLFSSL_HEAP_TEST) {
1047
        return malloc(size); /* native heap */
1048
    }
1049
#endif
1050
1051
    /* if no heap hint then use dynamic memory*/
1052
    if (heap == NULL && globalHeapHint == NULL) {
1053
        #ifdef WOLFSSL_HEAP_TEST
1054
            /* allow using malloc for creating ctx and method */
1055
            if (type == DYNAMIC_TYPE_CTX || type == DYNAMIC_TYPE_METHOD ||
1056
                                            type == DYNAMIC_TYPE_CERT_MANAGER) {
1057
                WOLFSSL_MSG("ERROR allowing null heap hint for ctx/method");
1058
                res = malloc(size); /* native heap */
1059
            }
1060
            else {
1061
                WOLFSSL_MSG("ERROR null heap hint passed into XMALLOC");
1062
                res = NULL;
1063
            }
1064
        #else
1065
        #ifndef WOLFSSL_NO_MALLOC
1066
            #ifdef FREERTOS
1067
                res = pvPortMalloc(size); /* native heap */
1068
            #elif defined(WOLFSSL_EMBOS)
1069
                res = OS_HEAP_malloc(size);
1070
            #else
1071
                res = malloc(size); /* native heap */
1072
            #endif
1073
1074
            #ifdef WOLFSSL_DEBUG_MEMORY
1075
                fprintf(stderr, "[HEAP %p] Alloc: %p -> %u at %s:%u\n", heap,
1076
                    res, (word32)size, func, line);
1077
            #endif
1078
        #else
1079
            WOLFSSL_MSG("No heap hint found to use and no malloc");
1080
            #ifdef WOLFSSL_DEBUG_MEMORY
1081
            fprintf(stderr, "ERROR: at %s:%u\n", func, line);
1082
            #endif
1083
        #endif /* WOLFSSL_NO_MALLOC */
1084
        #endif /* WOLFSSL_HEAP_TEST */
1085
    }
1086
    else {
1087
        WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)heap;
1088
        WOLFSSL_HEAP*      mem;
1089
1090
        if (hint == NULL) {
1091
            hint = (WOLFSSL_HEAP_HINT*)globalHeapHint;
1092
        #ifdef WOLFSSL_DEBUG_MEMORY
1093
            fprintf(stderr, "(Using global heap hint %p) ", hint);
1094
        #endif
1095
        }
1096
        mem = hint->memory;
1097
1098
    #ifndef SINGLE_THREADED
1099
        if (wc_LockMutex(&(mem->memory_mutex)) != 0) {
1100
            WOLFSSL_MSG("Bad memory_mutex lock");
1101
            return NULL;
1102
        }
1103
    #endif
1104
1105
    #ifndef WOLFSSL_STATIC_MEMORY_LEAN
1106
        /* case of using fixed IO buffers */
1107
        if (mem->flag & WOLFMEM_IO_POOL_FIXED &&
1108
                                             (type == DYNAMIC_TYPE_OUT_BUFFER ||
1109
                                              type == DYNAMIC_TYPE_IN_BUFFER)) {
1110
            if (type == DYNAMIC_TYPE_OUT_BUFFER) {
1111
                pt = hint->outBuf;
1112
            }
1113
            if (type == DYNAMIC_TYPE_IN_BUFFER) {
1114
                pt = hint->inBuf;
1115
            }
1116
        }
1117
        else
1118
    #endif
1119
        {
1120
        #ifndef WOLFSSL_STATIC_MEMORY_LEAN
1121
            /* check if using IO pool flag */
1122
            if (mem->flag & WOLFMEM_IO_POOL &&
1123
                                             (type == DYNAMIC_TYPE_OUT_BUFFER ||
1124
                                              type == DYNAMIC_TYPE_IN_BUFFER)) {
1125
                if (mem->io != NULL) {
1126
                    pt      = mem->io;
1127
                    mem->io = pt->next;
1128
                }
1129
            }
1130
         #endif
1131
1132
            /* general static memory */
1133
            if (pt == NULL) {
1134
                for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) {
1135
                    if ((word32)size <= mem->sizeList[i]) {
1136
                        if (mem->ava[i] != NULL) {
1137
                            pt = mem->ava[i];
1138
                            mem->ava[i] = pt->next;
1139
                            break;
1140
                        }
1141
                    #ifdef WOLFSSL_DEBUG_STATIC_MEMORY
1142
                        else {
1143
                            fprintf(stderr, "Size: %lu, Empty: %d\n",
1144
                                (unsigned long) size, mem->sizeList[i]);
1145
                        }
1146
                    #endif
1147
                    }
1148
                }
1149
            }
1150
        }
1151
1152
        if (pt != NULL) {
1153
        #ifndef WOLFSSL_STATIC_MEMORY_LEAN
1154
            mem->alloc += 1;
1155
        #endif
1156
            res = pt->buffer;
1157
1158
        #ifdef WOLFSSL_DEBUG_MEMORY
1159
            pt->szUsed = size;
1160
            fprintf(stderr, "[HEAP %p] Alloc: %p -> %lu at %s:%u\n", heap,
1161
                pt->buffer, size, func, line);
1162
        #endif
1163
        #ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK
1164
            if (DebugCb) {
1165
                DebugCb(size, pt->sz, WOLFSSL_DEBUG_MEMORY_ALLOC, type);
1166
            }
1167
        #endif
1168
        #ifndef WOLFSSL_STATIC_MEMORY_LEAN
1169
            /* keep track of connection statistics if flag is set */
1170
            if (mem->flag & WOLFMEM_TRACK_STATS) {
1171
                WOLFSSL_MEM_CONN_STATS* stats = hint->stats;
1172
                if (stats != NULL) {
1173
                    stats->curMem += pt->sz;
1174
                    if (stats->peakMem < stats->curMem) {
1175
                        stats->peakMem = stats->curMem;
1176
                    }
1177
                    stats->curAlloc++;
1178
                    if (stats->peakAlloc < stats->curAlloc) {
1179
                        stats->peakAlloc = stats->curAlloc;
1180
                    }
1181
                    stats->totalAlloc++;
1182
                }
1183
            }
1184
        #endif
1185
        }
1186
        else {
1187
            WOLFSSL_MSG("ERROR ran out of static memory");
1188
            res = NULL;
1189
            #ifdef WOLFSSL_DEBUG_MEMORY
1190
                fprintf(stderr, "Looking for %lu bytes at %s:%u\n",
1191
                    (unsigned long) size, func, line);
1192
            #endif
1193
            #ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK
1194
            if (DebugCb) {
1195
                DebugCb(size, 0, WOLFSSL_DEBUG_MEMORY_FAIL, type);
1196
            }
1197
            #endif
1198
        }
1199
    #ifndef SINGLE_THREADED
1200
        wc_UnLockMutex(&(mem->memory_mutex));
1201
    #endif
1202
    }
1203
1204
    #ifdef WOLFSSL_MALLOC_CHECK
1205
        if ((wc_ptr_t)res % WOLFSSL_STATIC_ALIGN) {
1206
            WOLFSSL_MSG("ERROR memory is not aligned");
1207
            res = NULL;
1208
        }
1209
    #endif
1210
1211
1212
    (void)i;
1213
    (void)pt;
1214
    (void)type;
1215
1216
    return res;
1217
}
1218
1219
1220
#ifdef WOLFSSL_DEBUG_MEMORY
1221
void wolfSSL_Free(void *ptr, void* heap, int type, const char* func, unsigned int line)
1222
#else
1223
void wolfSSL_Free(void *ptr, void* heap, int type)
1224
#endif
1225
{
1226
    int i;
1227
1228
    if (ptr) {
1229
        /* check for testing heap hint was set */
1230
    #ifdef WOLFSSL_HEAP_TEST
1231
        if (heap == (void*)WOLFSSL_HEAP_TEST) {
1232
        #ifdef WOLFSSL_DEBUG_MEMORY
1233
            fprintf(stderr, "[HEAP %p] Free: %p at %s:%u\n", heap, ptr, func,
1234
                line);
1235
        #endif
1236
            return free(ptr); /* native heap */
1237
        }
1238
    #endif
1239
1240
        if (heap == NULL && globalHeapHint == NULL) {
1241
        #ifdef WOLFSSL_HEAP_TEST
1242
            /* allow using malloc for creating ctx and method */
1243
            if (type == DYNAMIC_TYPE_CTX || type == DYNAMIC_TYPE_METHOD ||
1244
                                            type == DYNAMIC_TYPE_CERT_MANAGER) {
1245
                WOLFSSL_MSG("ERROR allowing null heap hint for ctx/method");
1246
            }
1247
            else {
1248
                WOLFSSL_MSG("ERROR null heap hint passed into XFREE");
1249
            }
1250
        #endif
1251
        #ifndef WOLFSSL_NO_MALLOC
1252
            #ifdef WOLFSSL_DEBUG_MEMORY
1253
            fprintf(stderr, "[HEAP %p] Free: %p at %s:%u\n", heap, ptr, func,
1254
                line);
1255
            #endif
1256
            #ifdef FREERTOS
1257
                vPortFree(ptr); /* native heap */
1258
            #elif defined(WOLFSSL_EMBOS)
1259
                OS_HEAP_free(ptr); /* native heap */
1260
            #else
1261
                free(ptr); /* native heap */
1262
            #endif
1263
        #else
1264
            WOLFSSL_MSG("Error trying to call free when turned off");
1265
        #endif /* WOLFSSL_NO_MALLOC */
1266
        }
1267
        else {
1268
            WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)heap;
1269
            WOLFSSL_HEAP*      mem;
1270
            wc_Memory* pt;
1271
            word32 padSz = -(int)sizeof(wc_Memory) & (WOLFSSL_STATIC_ALIGN - 1);
1272
1273
            if (hint == NULL) {
1274
                hint = (WOLFSSL_HEAP_HINT*)globalHeapHint;
1275
            #ifdef WOLFSSL_DEBUG_MEMORY
1276
                fprintf(stderr, "(Using global heap hint %p) ", hint);
1277
            #endif
1278
            }
1279
            mem = hint->memory;
1280
            if (mem == NULL) {
1281
                WOLFSSL_MSG("Bad hint pointer to memory");
1282
                return;
1283
            }
1284
1285
            /* get memory struct and add it to available list */
1286
            pt = (wc_Memory*)((byte*)ptr - sizeof(wc_Memory) - padSz);
1287
        #ifndef SINGLE_THREADED
1288
            if (wc_LockMutex(&(mem->memory_mutex)) != 0) {
1289
                WOLFSSL_MSG("Bad memory_mutex lock");
1290
                return;
1291
            }
1292
        #endif
1293
1294
        #ifndef WOLFSSL_STATIC_MEMORY_LEAN
1295
            /* case of using fixed IO buffers */
1296
            if (mem->flag & WOLFMEM_IO_POOL_FIXED &&
1297
                                             (type == DYNAMIC_TYPE_OUT_BUFFER ||
1298
                                              type == DYNAMIC_TYPE_IN_BUFFER)) {
1299
                /* fixed IO pools are free'd at the end of SSL lifetime
1300
                   using FreeFixedIO(WOLFSSL_HEAP* heap, wc_Memory** io) */
1301
            }
1302
            else if (mem->flag & WOLFMEM_IO_POOL && pt->sz == WOLFMEM_IO_SZ &&
1303
                                             (type == DYNAMIC_TYPE_OUT_BUFFER ||
1304
                                              type == DYNAMIC_TYPE_IN_BUFFER)) {
1305
                pt->next = mem->io;
1306
                mem->io  = pt;
1307
            }
1308
            else
1309
       #endif
1310
            { /* general memory free */
1311
                for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) {
1312
                    if (pt->sz == mem->sizeList[i]) {
1313
                        pt->next = mem->ava[i];
1314
                        mem->ava[i] = pt;
1315
1316
                    #ifdef WOLFSSL_STATIC_MEMORY_DEBUG_CALLBACK
1317
                        if (DebugCb) {
1318
                        #ifdef WOLFSSL_DEBUG_MEMORY
1319
                            DebugCb(pt->szUsed, pt->sz, WOLFSSL_DEBUG_MEMORY_FREE, type);
1320
                        #else
1321
                            DebugCb(pt->sz, pt->sz, WOLFSSL_DEBUG_MEMORY_FREE, type);
1322
                        #endif
1323
                        }
1324
                    #endif
1325
                        break;
1326
                    }
1327
                }
1328
            }
1329
        #ifndef WOLFSSL_STATIC_MEMORY_LEAN
1330
            mem->inUse -= pt->sz;
1331
            mem->frAlc += 1;
1332
        #endif
1333
1334
        #ifdef WOLFSSL_DEBUG_MEMORY
1335
            fprintf(stderr, "[HEAP %p] Free: %p -> %u at %s:%u\n", heap,
1336
                pt->buffer, pt->szUsed, func, line);
1337
        #endif
1338
1339
        #ifndef WOLFSSL_STATIC_MEMORY_LEAN
1340
            /* keep track of connection statistics if flag is set */
1341
            if (mem->flag & WOLFMEM_TRACK_STATS) {
1342
                WOLFSSL_MEM_CONN_STATS* stats = hint->stats;
1343
                if (stats != NULL) {
1344
                    /* avoid under flow */
1345
                    if (stats->curMem > pt->sz) {
1346
                        stats->curMem -= pt->sz;
1347
                    }
1348
                    else {
1349
                        stats->curMem = 0;
1350
                    }
1351
1352
                    if (stats->curAlloc > 0) {
1353
                        stats->curAlloc--;
1354
                    }
1355
                    stats->totalFr++;
1356
                }
1357
            }
1358
        #endif
1359
        #ifndef SINGLE_THREADED
1360
            wc_UnLockMutex(&(mem->memory_mutex));
1361
        #endif
1362
        }
1363
    }
1364
1365
    (void)i;
1366
    (void)type;
1367
}
1368
1369
#ifndef WOLFSSL_NO_REALLOC
1370
#ifdef WOLFSSL_DEBUG_MEMORY
1371
void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type, const char* func, unsigned int line)
1372
#else
1373
void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type)
1374
#endif
1375
{
1376
    void* res = 0;
1377
    wc_Memory* pt = NULL;
1378
    int    i;
1379
1380
    /* check for testing heap hint was set */
1381
#ifdef WOLFSSL_HEAP_TEST
1382
    if (heap == (void*)WOLFSSL_HEAP_TEST) {
1383
        return realloc(ptr, size); /* native heap */
1384
    }
1385
#endif
1386
1387
    if (heap == NULL && globalHeapHint == NULL) {
1388
        #ifdef WOLFSSL_HEAP_TEST
1389
            WOLFSSL_MSG("ERROR null heap hint passed in to XREALLOC");
1390
        #endif
1391
        #ifndef WOLFSSL_NO_MALLOC
1392
            res = realloc(ptr, size); /* native heap */
1393
        #else
1394
            WOLFSSL_MSG("NO heap found to use for realloc");
1395
        #endif /* WOLFSSL_NO_MALLOC */
1396
    }
1397
    else {
1398
        WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)heap;
1399
        WOLFSSL_HEAP*      mem;
1400
        word32 padSz = -(int)sizeof(wc_Memory) & (WOLFSSL_STATIC_ALIGN - 1);
1401
1402
        if (hint == NULL) {
1403
            hint = (WOLFSSL_HEAP_HINT*)globalHeapHint;
1404
        #ifdef WOLFSSL_DEBUG_MEMORY
1405
            fprintf(stderr, "(Using global heap hint %p) ", hint);
1406
        #endif
1407
        }
1408
        mem = hint->memory;
1409
1410
        if (ptr == NULL) {
1411
        #ifdef WOLFSSL_DEBUG_MEMORY
1412
            return wolfSSL_Malloc(size, heap, type, func, line);
1413
        #else
1414
            return wolfSSL_Malloc(size, heap, type);
1415
        #endif
1416
        }
1417
    #ifndef SINGLE_THREADED
1418
        if (wc_LockMutex(&(mem->memory_mutex)) != 0) {
1419
            WOLFSSL_MSG("Bad memory_mutex lock");
1420
            return NULL;
1421
        }
1422
    #endif
1423
1424
    #ifndef WOLFSSL_STATIC_MEMORY_LEAN
1425
        /* case of using fixed IO buffers or IO pool */
1426
        if (((mem->flag & WOLFMEM_IO_POOL)||(mem->flag & WOLFMEM_IO_POOL_FIXED))
1427
                                          && (type == DYNAMIC_TYPE_OUT_BUFFER ||
1428
                                              type == DYNAMIC_TYPE_IN_BUFFER)) {
1429
            /* no realloc, is fixed size */
1430
            pt = (wc_Memory*)((byte*)ptr - padSz - sizeof(wc_Memory));
1431
            if (pt->sz < size) {
1432
                WOLFSSL_MSG("Error IO memory was not large enough");
1433
                res = NULL; /* return NULL in error case */
1434
            }
1435
            else {
1436
                res = pt->buffer;
1437
            }
1438
        }
1439
        else
1440
    #endif
1441
        {
1442
        /* general memory */
1443
            for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) {
1444
                if ((word32)size <= mem->sizeList[i]) {
1445
                    if (mem->ava[i] != NULL) {
1446
                        pt = mem->ava[i];
1447
                        mem->ava[i] = pt->next;
1448
                        break;
1449
                    }
1450
                }
1451
            }
1452
1453
            if (pt != NULL) {
1454
                word32 prvSz;
1455
1456
                res = pt->buffer;
1457
1458
                /* copy over original information and free ptr */
1459
                prvSz = ((wc_Memory*)((byte*)ptr - padSz -
1460
                                               sizeof(wc_Memory)))->sz;
1461
                prvSz = (prvSz > pt->sz)? pt->sz: prvSz;
1462
                XMEMCPY(pt->buffer, ptr, prvSz);
1463
            #ifndef WOLFSSL_STATIC_MEMORY_LEAN
1464
                mem->inUse += pt->sz;
1465
                mem->alloc += 1;
1466
            #endif
1467
1468
                /* free memory that was previously being used */
1469
            #ifndef SINGLE_THREADED
1470
                wc_UnLockMutex(&(mem->memory_mutex));
1471
            #endif
1472
                wolfSSL_Free(ptr, heap, type
1473
            #ifdef WOLFSSL_DEBUG_MEMORY
1474
                    , func, line
1475
            #endif
1476
                );
1477
            #ifndef SINGLE_THREADED
1478
                if (wc_LockMutex(&(mem->memory_mutex)) != 0) {
1479
                    WOLFSSL_MSG("Bad memory_mutex lock");
1480
                    return NULL;
1481
                }
1482
            #endif
1483
            }
1484
        }
1485
    #ifndef SINGLE_THREADED
1486
        wc_UnLockMutex(&(mem->memory_mutex));
1487
    #endif
1488
    }
1489
1490
    #ifdef WOLFSSL_MALLOC_CHECK
1491
        if ((wc_ptr_t)res % WOLFSSL_STATIC_ALIGN) {
1492
            WOLFSSL_MSG("ERROR memory is not aligned");
1493
            res = NULL;
1494
        }
1495
    #endif
1496
1497
    (void)i;
1498
    (void)pt;
1499
    (void)type;
1500
1501
    return res;
1502
}
1503
#endif /* WOLFSSL_STATIC_MEMORY */
1504
#endif /* WOLFSSL_NO_REALLOC */
1505
#endif /* USE_WOLFSSL_MEMORY */
1506
1507
1508
#ifdef HAVE_IO_POOL
1509
1510
/* Example for user io pool, shared build may need definitions in lib proper */
1511
1512
#include <stdlib.h>
1513
1514
#ifndef HAVE_THREAD_LS
1515
    #error "Oops, simple I/O pool example needs thread local storage"
1516
#endif
1517
1518
1519
/* allow simple per thread in and out pools */
1520
/* use 17k size since max record size is 16k plus overhead */
1521
static THREAD_LS_T byte pool_in[17*1024];
1522
static THREAD_LS_T byte pool_out[17*1024];
1523
1524
1525
void* XMALLOC(size_t n, void* heap, int type)
1526
{
1527
    (void)heap;
1528
1529
    if (type == DYNAMIC_TYPE_IN_BUFFER) {
1530
        if (n < sizeof(pool_in))
1531
            return pool_in;
1532
        else
1533
            return NULL;
1534
    }
1535
1536
    if (type == DYNAMIC_TYPE_OUT_BUFFER) {
1537
        if (n < sizeof(pool_out))
1538
            return pool_out;
1539
        else
1540
            return NULL;
1541
    }
1542
1543
    return malloc(n); /* native heap */
1544
}
1545
1546
void* XREALLOC(void *p, size_t n, void* heap, int type)
1547
{
1548
    (void)heap;
1549
1550
    if (type == DYNAMIC_TYPE_IN_BUFFER) {
1551
        if (n < sizeof(pool_in))
1552
            return pool_in;
1553
        else
1554
            return NULL;
1555
    }
1556
1557
    if (type == DYNAMIC_TYPE_OUT_BUFFER) {
1558
        if (n < sizeof(pool_out))
1559
            return pool_out;
1560
        else
1561
            return NULL;
1562
    }
1563
1564
    return realloc(p, n); /* native heap */
1565
}
1566
1567
void XFREE(void *p, void* heap, int type)
1568
{
1569
    (void)heap;
1570
1571
    if (type == DYNAMIC_TYPE_IN_BUFFER)
1572
        return;  /* do nothing, static pool */
1573
1574
    if (type == DYNAMIC_TYPE_OUT_BUFFER)
1575
        return;  /* do nothing, static pool */
1576
1577
    free(p); /* native heap */
1578
}
1579
1580
#endif /* HAVE_IO_POOL */
1581
1582
#ifdef WOLFSSL_MEMORY_LOG
1583
void *xmalloc(size_t n, void* heap, int type, const char* func,
1584
              const char* file, unsigned int line)
1585
{
1586
    void*   p = NULL;
1587
    word32* p32;
1588
1589
#ifdef WOLFSSL_MEM_FAIL_COUNT
1590
    if (!wc_MemFailCount_AllocMem()) {
1591
        WOLFSSL_MSG("MemFailCnt: Fail malloc");
1592
        return NULL;
1593
    }
1594
#endif
1595
1596
    if (malloc_function) {
1597
#if !defined(WOLFSSL_STATIC_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY)
1598
        p32 = malloc_function(n + sizeof(word32) * 4);
1599
#else
1600
        p32 = malloc_function(n + sizeof(word32) * 4, heap, type);
1601
#endif
1602
    }
1603
    else
1604
        p32 = malloc(n + sizeof(word32) * 4); /* native heap */
1605
1606
    if (p32 != NULL) {
1607
        p32[0] = (word32)n;
1608
        p = (void*)(p32 + 4);
1609
1610
        fprintf(stderr, "Alloc: %p -> %u (%d) at %s:%s:%u\n", p, (word32)n,
1611
                                                        type, func, file, line);
1612
    }
1613
#ifdef WOLFSSL_MEM_FAIL_COUNT
1614
    else {
1615
        /* Counted above, but the allocator returned NULL. No block to free. */
1616
        wc_MemFailCount_AllocFailed();
1617
    }
1618
#endif
1619
1620
    (void)heap;
1621
1622
    return p;
1623
}
1624
void *xrealloc(void *p, size_t n, void* heap, int type, const char* func,
1625
               const char* file, unsigned int line)
1626
{
1627
    void*   newp = NULL;
1628
    word32* p32;
1629
    word32* oldp32 = NULL;
1630
    word32  oldLen;
1631
1632
#ifdef WOLFSSL_MEM_FAIL_COUNT
1633
    if (!wc_MemFailCount_AllocMem()) {
1634
        WOLFSSL_MSG("MemFailCnt: Fail malloc");
1635
        return NULL;
1636
    }
1637
#endif
1638
1639
    if (p != NULL) {
1640
        oldp32 = (word32*)p;
1641
        oldp32 -= 4;
1642
        oldLen = oldp32[0];
1643
    }
1644
1645
    if (realloc_function) {
1646
#if !defined(WOLFSSL_STATIC_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY)
1647
        p32 = realloc_function(oldp32, n + sizeof(word32) * 4);
1648
#else
1649
        p32 = realloc_function(oldp32, n + sizeof(word32) * 4, heap, type);
1650
#endif
1651
    }
1652
    else
1653
        p32 = realloc(oldp32, n + sizeof(word32) * 4); /* native heap */
1654
1655
    if (p32 != NULL) {
1656
        p32[0] = (word32)n;
1657
        newp = (void*)(p32 + 4);
1658
1659
        if (p != NULL) {
1660
            fprintf(stderr, "Free: %p -> %u (%d) at %s:%s:%u\n", p, oldLen,
1661
                                                        type, func, file, line);
1662
        }
1663
        fprintf(stderr, "Alloc: %p -> %u (%d) at %s:%s:%u\n", newp, (word32)n,
1664
                                                        type, func, file, line);
1665
    }
1666
1667
#ifdef WOLFSSL_MEM_FAIL_COUNT
1668
    /* realloc(NULL, n) is malloc. AllocMem() already counted it; if the
1669
     * allocator returns NULL for a positive size, no block exists to free.
1670
     * Do not undo a failed realloc of a live pointer: that path still
1671
     * counts a free below and the original block remains. */
1672
    if (p32 == NULL && p == NULL && n > 0) {
1673
        wc_MemFailCount_AllocFailed();
1674
    }
1675
    else if (p != NULL) {
1676
        wc_MemFailCount_FreeMem();
1677
    }
1678
#endif
1679
1680
    (void)heap;
1681
1682
    return newp;
1683
}
1684
void xfree(void *p, void* heap, int type, const char* func, const char* file,
1685
           unsigned int line)
1686
{
1687
    word32* p32 = (word32*)p;
1688
1689
    if (p != NULL) {
1690
    #ifdef WOLFSSL_MEM_FAIL_COUNT
1691
        wc_MemFailCount_FreeMem();
1692
    #endif
1693
        p32 -= 4;
1694
1695
        fprintf(stderr, "Free: %p -> %u (%d) at %s:%s:%u\n", p, p32[0], type,
1696
                                                              func, file, line);
1697
1698
        if (free_function) {
1699
#if !defined(WOLFSSL_STATIC_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY)
1700
            free_function(p32);
1701
#else
1702
            free_function(p32, heap, type);
1703
#endif
1704
        }
1705
        else
1706
            free(p32); /* native heap */
1707
    }
1708
1709
    (void)heap;
1710
}
1711
#endif /* WOLFSSL_MEMORY_LOG */
1712
1713
#ifdef WOLFSSL_STACK_LOG
1714
/* Note: this code only works with GCC using -finstrument-functions. */
1715
void __attribute__((no_instrument_function))
1716
     __cyg_profile_func_enter(void *func,  void *caller)
1717
{
1718
    register void* sp asm("sp");
1719
    fprintf(stderr, "ENTER: %016lx %p\n", (unsigned long)(wc_ptr_t)func, sp);
1720
    (void)caller;
1721
}
1722
1723
void __attribute__((no_instrument_function))
1724
     __cyg_profile_func_exit(void *func, void *caller)
1725
{
1726
    register void* sp asm("sp");
1727
    fprintf(stderr, "EXIT: %016lx %p\n", (unsigned long)(wc_ptr_t)func, sp);
1728
    (void)caller;
1729
}
1730
#endif
1731
1732
#ifndef WOLFSSL_NO_FORCE_ZERO
1733
/* Exported version of ForceZero(). */
1734
void wc_ForceZero(void *mem, size_t len)
1735
142k
{
1736
142k
    ForceZero(mem, len);
1737
142k
}
1738
#endif
1739
1740
#ifndef WOLFSSL_NO_CONST_CMP
1741
/* Exported version of ConstantCompare(). */
1742
int wc_ConstantCompare(const byte* a, const byte* b, int length)
1743
1744
0
{
1745
0
    return ConstantCompare(a, b, length);
1746
0
}
1747
#endif
1748
1749
#ifdef WC_DEBUG_CIPHER_LIFECYCLE
1750
static const byte wc_debug_cipher_lifecycle_tag_value[] =
1751
    { 'W', 'o', 'l', 'f' };
1752
1753
WOLFSSL_LOCAL int wc_debug_CipherLifecycleInit(
1754
    void **CipherLifecycleTag,
1755
    void *heap)
1756
{
1757
    if (CipherLifecycleTag == NULL)
1758
        return BAD_FUNC_ARG;
1759
    *CipherLifecycleTag = (void *)XMALLOC(
1760
        sizeof(wc_debug_cipher_lifecycle_tag_value),
1761
        heap,
1762
        DYNAMIC_TYPE_DEBUG_TAG);
1763
    if (*CipherLifecycleTag == NULL)
1764
        return MEMORY_E;
1765
    XMEMCPY(*CipherLifecycleTag,
1766
            wc_debug_cipher_lifecycle_tag_value,
1767
            sizeof(wc_debug_cipher_lifecycle_tag_value));
1768
    return 0;
1769
}
1770
1771
WOLFSSL_LOCAL int wc_debug_CipherLifecycleCheck(
1772
    void *CipherLifecycleTag,
1773
    int abort_p)
1774
{
1775
    int ret;
1776
    if (CipherLifecycleTag == NULL) {
1777
        ret = BAD_STATE_E;
1778
        goto out;
1779
    }
1780
    if (XMEMCMP(CipherLifecycleTag,
1781
                wc_debug_cipher_lifecycle_tag_value,
1782
                sizeof(wc_debug_cipher_lifecycle_tag_value)) != 0)
1783
    {
1784
        ret = BAD_STATE_E;
1785
        goto out;
1786
    }
1787
    ret = 0;
1788
1789
out:
1790
#ifdef WOLFSSL_KERNEL_MODE
1791
    (void)abort_p;
1792
#else
1793
    if ((ret < 0) && abort_p)
1794
        abort();
1795
#endif
1796
1797
    return ret;
1798
}
1799
1800
WOLFSSL_LOCAL int wc_debug_CipherLifecycleFree(
1801
    void **CipherLifecycleTag,
1802
    void *heap,
1803
    int abort_p)
1804
{
1805
    int ret;
1806
    if (CipherLifecycleTag == NULL)
1807
        return BAD_FUNC_ARG;
1808
    ret = wc_debug_CipherLifecycleCheck(*CipherLifecycleTag, abort_p);
1809
    if (ret != 0)
1810
        return ret;
1811
    XFREE(*CipherLifecycleTag, heap, DYNAMIC_TYPE_DEBUG_TAG);
1812
    *CipherLifecycleTag = NULL;
1813
    return 0;
1814
}
1815
#endif /* WC_DEBUG_CIPHER_LIFECYCLE */
1816
1817
#ifdef DEBUG_VECTOR_REGISTER_ACCESS
1818
THREAD_LS_T int wc_svr_count = 0;
1819
THREAD_LS_T const char *wc_svr_last_file = NULL;
1820
THREAD_LS_T int wc_svr_last_line = -1;
1821
THREAD_LS_T int wc_debug_vector_registers_retval =
1822
    WC_DEBUG_VECTOR_REGISTERS_RETVAL_INITVAL;
1823
#endif
1824
1825
#ifdef DEBUG_VECTOR_REGISTER_ACCESS_FUZZING
1826
1827
#ifdef HAVE_THREAD_LS
1828
1829
WOLFSSL_LOCAL int SAVE_VECTOR_REGISTERS2_fuzzer(void) {
1830
    static THREAD_LS_T struct drand48_data wc_svr_fuzzing_state;
1831
    static THREAD_LS_T int wc_svr_fuzzing_seeded = 0;
1832
    long result;
1833
1834
#ifdef DEBUG_VECTOR_REGISTER_ACCESS
1835
    if (wc_debug_vector_registers_retval)
1836
        return wc_debug_vector_registers_retval;
1837
#endif
1838
1839
    if (wc_svr_fuzzing_seeded == 0) {
1840
        long seed = WC_DEBUG_VECTOR_REGISTERS_FUZZING_SEED;
1841
        char *seed_envstr = getenv("WC_DEBUG_VECTOR_REGISTERS_FUZZING_SEED");
1842
        if (seed_envstr)
1843
            seed = strtol(seed_envstr, NULL, 0);
1844
        (void)srand48_r(seed, &wc_svr_fuzzing_state);
1845
        wc_svr_fuzzing_seeded = 1;
1846
    }
1847
    (void)lrand48_r(&wc_svr_fuzzing_state, &result);
1848
    if (result & 1)
1849
        return WC_NO_ERR_TRACE(IO_FAILED_E);
1850
    else
1851
        return 0;
1852
}
1853
1854
#else /* !HAVE_THREAD_LS */
1855
1856
/* alternate implementation useful for testing in the kernel module build, where
1857
 * glibc and thread-local storage are unavailable.
1858
 */
1859
1860
WOLFSSL_LOCAL int SAVE_VECTOR_REGISTERS2_fuzzer(void) {
1861
    /* xorshift64 (Marsaglia 2003): a bijection on the nonzero 64-bit states
1862
     * with a single cycle of period 2^64 - 1 -- no state-space contraction,
1863
     * no short cycles, and the seed selects only the phase.  Aligned 64-bit
1864
     * stores are atomic on supported targets and every stored value is
1865
     * nonzero, so unsynchronized concurrent access loses updates but can
1866
     * never degenerate the state.
1867
     */
1868
    static word64 prn =
1869
        (word64)WC_DEBUG_VECTOR_REGISTERS_FUZZING_SEED != W64LIT(0) ?
1870
        (word64)WC_DEBUG_VECTOR_REGISTERS_FUZZING_SEED :
1871
        W64LIT(0x9e3779b97f4a7c15); /* zero is the map's one fixed point --
1872
                                     * substitute an arbitrary nonzero seed.
1873
                                     */
1874
    word64 x;
1875
1876
#ifdef DEBUG_VECTOR_REGISTER_ACCESS
1877
    if (wc_debug_vector_registers_retval)
1878
        return wc_debug_vector_registers_retval;
1879
#endif
1880
1881
    x = prn;
1882
    x ^= x << 13;
1883
    x ^= x >> 7;
1884
    x ^= x << 17;
1885
    prn = x;
1886
1887
    return ((x >> 32) & 1) ? WC_NO_ERR_TRACE(IO_FAILED_E) : 0;
1888
}
1889
1890
#endif /* !HAVE_THREAD_LS */
1891
1892
#endif /* DEBUG_VECTOR_REGISTER_ACCESS_FUZZING */
1893
1894
#if defined(WOLFSSL_LINUXKM) || defined(WC_SYM_RELOC_TABLES) || \
1895
    defined(WC_SYM_RELOC_TABLES_SUPPORT)
1896
    #include "linuxkm/linuxkm_memory.c"
1897
#endif