xref: /openssl/crypto/mem_sec.c (revision 7ed6de99)
1 /*
2  * Copyright 2015-2024 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright 2004-2014, Akamai Technologies. All Rights Reserved.
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10 
11 /*
12  * This file is in two halves. The first half implements the public API
13  * to be used by external consumers, and to be used by OpenSSL to store
14  * data in a "secure arena." The second half implements the secure arena.
15  * For details on that implementation, see below (look for uppercase
16  * "SECURE HEAP IMPLEMENTATION").
17  */
18 #include "internal/e_os.h"
19 #include <openssl/crypto.h>
20 #include <openssl/err.h>
21 
22 #include <string.h>
23 
24 #ifndef OPENSSL_NO_SECURE_MEMORY
25 # if defined(_WIN32)
26 #  include <windows.h>
27 #  if defined(WINAPI_FAMILY_PARTITION)
28 #   if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)
29 /*
30  * While VirtualLock is available under the app partition (e.g. UWP),
31  * the headers do not define the API. Define it ourselves instead.
32  */
33 WINBASEAPI
34 BOOL
35 WINAPI
36 VirtualLock(
37     _In_ LPVOID lpAddress,
38     _In_ SIZE_T dwSize
39     );
40 #   endif
41 #  endif
42 # endif
43 # include <stdlib.h>
44 # include <assert.h>
45 # if defined(OPENSSL_SYS_UNIX)
46 #  include <unistd.h>
47 # endif
48 # include <sys/types.h>
49 # if defined(OPENSSL_SYS_UNIX)
50 #  include <sys/mman.h>
51 #  if defined(__FreeBSD__)
52 #    define MADV_DONTDUMP MADV_NOCORE
53 #  endif
54 #  if !defined(MAP_CONCEAL)
55 #    define MAP_CONCEAL 0
56 #  endif
57 # endif
58 # if defined(OPENSSL_SYS_LINUX)
59 #  include <sys/syscall.h>
60 #  if defined(SYS_mlock2)
61 #   include <linux/mman.h>
62 #   include <errno.h>
63 #  endif
64 #  include <sys/param.h>
65 # endif
66 # include <sys/stat.h>
67 # include <fcntl.h>
68 #endif
69 #ifndef HAVE_MADVISE
70 # if defined(MADV_DONTDUMP)
71 #  define HAVE_MADVISE 1
72 # else
73 #  define HAVE_MADVISE 0
74 # endif
75 #endif
76 #if HAVE_MADVISE
77 # undef NO_MADVISE
78 #else
79 # define NO_MADVISE
80 #endif
81 
82 #define CLEAR(p, s) OPENSSL_cleanse(p, s)
83 #ifndef PAGE_SIZE
84 # define PAGE_SIZE    4096
85 #endif
86 #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
87 # define MAP_ANON MAP_ANONYMOUS
88 #endif
89 
90 #ifndef OPENSSL_NO_SECURE_MEMORY
91 static size_t secure_mem_used;
92 
93 static int secure_mem_initialized;
94 
95 static CRYPTO_RWLOCK *sec_malloc_lock = NULL;
96 
97 /*
98  * These are the functions that must be implemented by a secure heap (sh).
99  */
100 static int sh_init(size_t size, size_t minsize);
101 static void *sh_malloc(size_t size);
102 static void sh_free(void *ptr);
103 static void sh_done(void);
104 static size_t sh_actual_size(char *ptr);
105 static int sh_allocated(const char *ptr);
106 #endif
107 
CRYPTO_secure_malloc_init(size_t size,size_t minsize)108 int CRYPTO_secure_malloc_init(size_t size, size_t minsize)
109 {
110 #ifndef OPENSSL_NO_SECURE_MEMORY
111     int ret = 0;
112 
113     if (!secure_mem_initialized) {
114         sec_malloc_lock = CRYPTO_THREAD_lock_new();
115         if (sec_malloc_lock == NULL)
116             return 0;
117         if ((ret = sh_init(size, minsize)) != 0) {
118             secure_mem_initialized = 1;
119         } else {
120             CRYPTO_THREAD_lock_free(sec_malloc_lock);
121             sec_malloc_lock = NULL;
122         }
123     }
124 
125     return ret;
126 #else
127     return 0;
128 #endif /* OPENSSL_NO_SECURE_MEMORY */
129 }
130 
CRYPTO_secure_malloc_done(void)131 int CRYPTO_secure_malloc_done(void)
132 {
133 #ifndef OPENSSL_NO_SECURE_MEMORY
134     if (secure_mem_used == 0) {
135         sh_done();
136         secure_mem_initialized = 0;
137         CRYPTO_THREAD_lock_free(sec_malloc_lock);
138         sec_malloc_lock = NULL;
139         return 1;
140     }
141 #endif /* OPENSSL_NO_SECURE_MEMORY */
142     return 0;
143 }
144 
CRYPTO_secure_malloc_initialized(void)145 int CRYPTO_secure_malloc_initialized(void)
146 {
147 #ifndef OPENSSL_NO_SECURE_MEMORY
148     return secure_mem_initialized;
149 #else
150     return 0;
151 #endif /* OPENSSL_NO_SECURE_MEMORY */
152 }
153 
CRYPTO_secure_malloc(size_t num,const char * file,int line)154 void *CRYPTO_secure_malloc(size_t num, const char *file, int line)
155 {
156 #ifndef OPENSSL_NO_SECURE_MEMORY
157     void *ret = NULL;
158     size_t actual_size;
159     int reason = CRYPTO_R_SECURE_MALLOC_FAILURE;
160 
161     if (!secure_mem_initialized) {
162         return CRYPTO_malloc(num, file, line);
163     }
164     if (!CRYPTO_THREAD_write_lock(sec_malloc_lock)) {
165         reason = ERR_R_CRYPTO_LIB;
166         goto err;
167     }
168     ret = sh_malloc(num);
169     actual_size = ret ? sh_actual_size(ret) : 0;
170     secure_mem_used += actual_size;
171     CRYPTO_THREAD_unlock(sec_malloc_lock);
172  err:
173     if (ret == NULL && (file != NULL || line != 0)) {
174         ERR_new();
175         ERR_set_debug(file, line, NULL);
176         ERR_set_error(ERR_LIB_CRYPTO, reason, NULL);
177     }
178     return ret;
179 #else
180     return CRYPTO_malloc(num, file, line);
181 #endif /* OPENSSL_NO_SECURE_MEMORY */
182 }
183 
CRYPTO_secure_zalloc(size_t num,const char * file,int line)184 void *CRYPTO_secure_zalloc(size_t num, const char *file, int line)
185 {
186 #ifndef OPENSSL_NO_SECURE_MEMORY
187     if (secure_mem_initialized)
188         /* CRYPTO_secure_malloc() zeroes allocations when it is implemented */
189         return CRYPTO_secure_malloc(num, file, line);
190 #endif
191     return CRYPTO_zalloc(num, file, line);
192 }
193 
CRYPTO_secure_free(void * ptr,const char * file,int line)194 void CRYPTO_secure_free(void *ptr, const char *file, int line)
195 {
196 #ifndef OPENSSL_NO_SECURE_MEMORY
197     size_t actual_size;
198 
199     if (ptr == NULL)
200         return;
201     if (!CRYPTO_secure_allocated(ptr)) {
202         CRYPTO_free(ptr, file, line);
203         return;
204     }
205     if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
206         return;
207     actual_size = sh_actual_size(ptr);
208     CLEAR(ptr, actual_size);
209     secure_mem_used -= actual_size;
210     sh_free(ptr);
211     CRYPTO_THREAD_unlock(sec_malloc_lock);
212 #else
213     CRYPTO_free(ptr, file, line);
214 #endif /* OPENSSL_NO_SECURE_MEMORY */
215 }
216 
CRYPTO_secure_clear_free(void * ptr,size_t num,const char * file,int line)217 void CRYPTO_secure_clear_free(void *ptr, size_t num,
218                               const char *file, int line)
219 {
220 #ifndef OPENSSL_NO_SECURE_MEMORY
221     size_t actual_size;
222 
223     if (ptr == NULL)
224         return;
225     if (!CRYPTO_secure_allocated(ptr)) {
226         OPENSSL_cleanse(ptr, num);
227         CRYPTO_free(ptr, file, line);
228         return;
229     }
230     if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
231         return;
232     actual_size = sh_actual_size(ptr);
233     CLEAR(ptr, actual_size);
234     secure_mem_used -= actual_size;
235     sh_free(ptr);
236     CRYPTO_THREAD_unlock(sec_malloc_lock);
237 #else
238     if (ptr == NULL)
239         return;
240     OPENSSL_cleanse(ptr, num);
241     CRYPTO_free(ptr, file, line);
242 #endif /* OPENSSL_NO_SECURE_MEMORY */
243 }
244 
CRYPTO_secure_allocated(const void * ptr)245 int CRYPTO_secure_allocated(const void *ptr)
246 {
247 #ifndef OPENSSL_NO_SECURE_MEMORY
248     if (!secure_mem_initialized)
249         return 0;
250     /*
251      * Only read accesses to the arena take place in sh_allocated() and this
252      * is only changed by the sh_init() and sh_done() calls which are not
253      * locked.  Hence, it is safe to make this check without a lock too.
254      */
255     return sh_allocated(ptr);
256 #else
257     return 0;
258 #endif /* OPENSSL_NO_SECURE_MEMORY */
259 }
260 
CRYPTO_secure_used(void)261 size_t CRYPTO_secure_used(void)
262 {
263     size_t ret = 0;
264 
265 #ifndef OPENSSL_NO_SECURE_MEMORY
266     if (!CRYPTO_THREAD_read_lock(sec_malloc_lock))
267         return 0;
268 
269     ret = secure_mem_used;
270 
271     CRYPTO_THREAD_unlock(sec_malloc_lock);
272 #endif /* OPENSSL_NO_SECURE_MEMORY */
273     return ret;
274 }
275 
CRYPTO_secure_actual_size(void * ptr)276 size_t CRYPTO_secure_actual_size(void *ptr)
277 {
278 #ifndef OPENSSL_NO_SECURE_MEMORY
279     size_t actual_size;
280 
281     if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
282         return 0;
283     actual_size = sh_actual_size(ptr);
284     CRYPTO_THREAD_unlock(sec_malloc_lock);
285     return actual_size;
286 #else
287     return 0;
288 #endif
289 }
290 
291 /*
292  * SECURE HEAP IMPLEMENTATION
293  */
294 #ifndef OPENSSL_NO_SECURE_MEMORY
295 
296 
297 /*
298  * The implementation provided here uses a fixed-sized mmap() heap,
299  * which is locked into memory, not written to core files, and protected
300  * on either side by an unmapped page, which will catch pointer overruns
301  * (or underruns) and an attempt to read data out of the secure heap.
302  * Free'd memory is zero'd or otherwise cleansed.
303  *
304  * This is a pretty standard buddy allocator.  We keep areas in a multiple
305  * of "sh.minsize" units.  The freelist and bitmaps are kept separately,
306  * so all (and only) data is kept in the mmap'd heap.
307  *
308  * This code assumes eight-bit bytes.  The numbers 3 and 7 are all over the
309  * place.
310  */
311 
312 #define ONE ((size_t)1)
313 
314 # define TESTBIT(t, b)  (t[(b) >> 3] &  (ONE << ((b) & 7)))
315 # define SETBIT(t, b)   (t[(b) >> 3] |= (ONE << ((b) & 7)))
316 # define CLEARBIT(t, b) (t[(b) >> 3] &= (0xFF & ~(ONE << ((b) & 7))))
317 
318 #define WITHIN_ARENA(p) \
319     ((char*)(p) >= sh.arena && (char*)(p) < &sh.arena[sh.arena_size])
320 #define WITHIN_FREELIST(p) \
321     ((char*)(p) >= (char*)sh.freelist && (char*)(p) < (char*)&sh.freelist[sh.freelist_size])
322 
323 
324 typedef struct sh_list_st {
325     struct sh_list_st *next;
326     struct sh_list_st **p_next;
327 } SH_LIST;
328 
329 typedef struct sh_st {
330     char* map_result;
331     size_t map_size;
332     char *arena;
333     size_t arena_size;
334     char **freelist;
335     ossl_ssize_t freelist_size;
336     size_t minsize;
337     unsigned char *bittable;
338     unsigned char *bitmalloc;
339     size_t bittable_size; /* size in bits */
340 } SH;
341 
342 static SH sh;
343 
sh_getlist(char * ptr)344 static size_t sh_getlist(char *ptr)
345 {
346     ossl_ssize_t list = sh.freelist_size - 1;
347     size_t bit = (sh.arena_size + ptr - sh.arena) / sh.minsize;
348 
349     for (; bit; bit >>= 1, list--) {
350         if (TESTBIT(sh.bittable, bit))
351             break;
352         OPENSSL_assert((bit & 1) == 0);
353     }
354 
355     return list;
356 }
357 
358 
sh_testbit(char * ptr,int list,unsigned char * table)359 static int sh_testbit(char *ptr, int list, unsigned char *table)
360 {
361     size_t bit;
362 
363     OPENSSL_assert(list >= 0 && list < sh.freelist_size);
364     OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
365     bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
366     OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
367     return TESTBIT(table, bit);
368 }
369 
sh_clearbit(char * ptr,int list,unsigned char * table)370 static void sh_clearbit(char *ptr, int list, unsigned char *table)
371 {
372     size_t bit;
373 
374     OPENSSL_assert(list >= 0 && list < sh.freelist_size);
375     OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
376     bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
377     OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
378     OPENSSL_assert(TESTBIT(table, bit));
379     CLEARBIT(table, bit);
380 }
381 
sh_setbit(char * ptr,int list,unsigned char * table)382 static void sh_setbit(char *ptr, int list, unsigned char *table)
383 {
384     size_t bit;
385 
386     OPENSSL_assert(list >= 0 && list < sh.freelist_size);
387     OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
388     bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
389     OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
390     OPENSSL_assert(!TESTBIT(table, bit));
391     SETBIT(table, bit);
392 }
393 
sh_add_to_list(char ** list,char * ptr)394 static void sh_add_to_list(char **list, char *ptr)
395 {
396     SH_LIST *temp;
397 
398     OPENSSL_assert(WITHIN_FREELIST(list));
399     OPENSSL_assert(WITHIN_ARENA(ptr));
400 
401     temp = (SH_LIST *)ptr;
402     temp->next = *(SH_LIST **)list;
403     OPENSSL_assert(temp->next == NULL || WITHIN_ARENA(temp->next));
404     temp->p_next = (SH_LIST **)list;
405 
406     if (temp->next != NULL) {
407         OPENSSL_assert((char **)temp->next->p_next == list);
408         temp->next->p_next = &(temp->next);
409     }
410 
411     *list = ptr;
412 }
413 
sh_remove_from_list(char * ptr)414 static void sh_remove_from_list(char *ptr)
415 {
416     SH_LIST *temp, *temp2;
417 
418     temp = (SH_LIST *)ptr;
419     if (temp->next != NULL)
420         temp->next->p_next = temp->p_next;
421     *temp->p_next = temp->next;
422     if (temp->next == NULL)
423         return;
424 
425     temp2 = temp->next;
426     OPENSSL_assert(WITHIN_FREELIST(temp2->p_next) || WITHIN_ARENA(temp2->p_next));
427 }
428 
429 
sh_init(size_t size,size_t minsize)430 static int sh_init(size_t size, size_t minsize)
431 {
432     int ret;
433     size_t i;
434     size_t pgsize;
435     size_t aligned;
436 #if defined(_WIN32)
437     DWORD flOldProtect;
438     SYSTEM_INFO systemInfo;
439 #endif
440 
441     memset(&sh, 0, sizeof(sh));
442 
443     /* make sure size is a powers of 2 */
444     OPENSSL_assert(size > 0);
445     OPENSSL_assert((size & (size - 1)) == 0);
446     if (size == 0 || (size & (size - 1)) != 0)
447         goto err;
448 
449     if (minsize <= sizeof(SH_LIST)) {
450         OPENSSL_assert(sizeof(SH_LIST) <= 65536);
451         /*
452          * Compute the minimum possible allocation size.
453          * This must be a power of 2 and at least as large as the SH_LIST
454          * structure.
455          */
456         minsize = sizeof(SH_LIST) - 1;
457         minsize |= minsize >> 1;
458         minsize |= minsize >> 2;
459         if (sizeof(SH_LIST) > 16)
460             minsize |= minsize >> 4;
461         if (sizeof(SH_LIST) > 256)
462             minsize |= minsize >> 8;
463         minsize++;
464     } else {
465         /* make sure minsize is a powers of 2 */
466           OPENSSL_assert((minsize & (minsize - 1)) == 0);
467           if ((minsize & (minsize - 1)) != 0)
468               goto err;
469     }
470 
471     sh.arena_size = size;
472     sh.minsize = minsize;
473     sh.bittable_size = (sh.arena_size / sh.minsize) * 2;
474 
475     /* Prevent allocations of size 0 later on */
476     if (sh.bittable_size >> 3 == 0)
477         goto err;
478 
479     sh.freelist_size = -1;
480     for (i = sh.bittable_size; i; i >>= 1)
481         sh.freelist_size++;
482 
483     sh.freelist = OPENSSL_zalloc(sh.freelist_size * sizeof(char *));
484     OPENSSL_assert(sh.freelist != NULL);
485     if (sh.freelist == NULL)
486         goto err;
487 
488     sh.bittable = OPENSSL_zalloc(sh.bittable_size >> 3);
489     OPENSSL_assert(sh.bittable != NULL);
490     if (sh.bittable == NULL)
491         goto err;
492 
493     sh.bitmalloc = OPENSSL_zalloc(sh.bittable_size >> 3);
494     OPENSSL_assert(sh.bitmalloc != NULL);
495     if (sh.bitmalloc == NULL)
496         goto err;
497 
498     /* Allocate space for heap, and two extra pages as guards */
499 #if defined(_SC_PAGE_SIZE) || defined (_SC_PAGESIZE)
500     {
501 # if defined(_SC_PAGE_SIZE)
502         long tmppgsize = sysconf(_SC_PAGE_SIZE);
503 # else
504         long tmppgsize = sysconf(_SC_PAGESIZE);
505 # endif
506         if (tmppgsize < 1)
507             pgsize = PAGE_SIZE;
508         else
509             pgsize = (size_t)tmppgsize;
510     }
511 #elif defined(_WIN32)
512     GetSystemInfo(&systemInfo);
513     pgsize = (size_t)systemInfo.dwPageSize;
514 #else
515     pgsize = PAGE_SIZE;
516 #endif
517     sh.map_size = pgsize + sh.arena_size + pgsize;
518 
519 #if !defined(_WIN32)
520 # ifdef MAP_ANON
521     sh.map_result = mmap(NULL, sh.map_size,
522                          PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE|MAP_CONCEAL, -1, 0);
523 # else
524     {
525         int fd;
526 
527         sh.map_result = MAP_FAILED;
528         if ((fd = open("/dev/zero", O_RDWR)) >= 0) {
529             sh.map_result = mmap(NULL, sh.map_size,
530                                  PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
531             close(fd);
532         }
533     }
534 # endif
535     if (sh.map_result == MAP_FAILED)
536         goto err;
537 #else
538     sh.map_result = VirtualAlloc(NULL, sh.map_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
539 
540     if (sh.map_result == NULL)
541             goto err;
542 #endif
543 
544     sh.arena = (char *)(sh.map_result + pgsize);
545     sh_setbit(sh.arena, 0, sh.bittable);
546     sh_add_to_list(&sh.freelist[0], sh.arena);
547 
548     /* Now try to add guard pages and lock into memory. */
549     ret = 1;
550 
551 #if !defined(_WIN32)
552     /* Starting guard is already aligned from mmap. */
553     if (mprotect(sh.map_result, pgsize, PROT_NONE) < 0)
554         ret = 2;
555 #else
556     if (VirtualProtect(sh.map_result, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE)
557         ret = 2;
558 #endif
559 
560     /* Ending guard page - need to round up to page boundary */
561     aligned = (pgsize + sh.arena_size + (pgsize - 1)) & ~(pgsize - 1);
562 #if !defined(_WIN32)
563     if (mprotect(sh.map_result + aligned, pgsize, PROT_NONE) < 0)
564         ret = 2;
565 #else
566     if (VirtualProtect(sh.map_result + aligned, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE)
567         ret = 2;
568 #endif
569 
570 #if defined(OPENSSL_SYS_LINUX) && defined(MLOCK_ONFAULT) && defined(SYS_mlock2)
571     if (syscall(SYS_mlock2, sh.arena, sh.arena_size, MLOCK_ONFAULT) < 0) {
572         if (errno == ENOSYS) {
573             if (mlock(sh.arena, sh.arena_size) < 0)
574                 ret = 2;
575         } else {
576             ret = 2;
577         }
578     }
579 #elif defined(_WIN32)
580     if (VirtualLock(sh.arena, sh.arena_size) == FALSE)
581         ret = 2;
582 #else
583     if (mlock(sh.arena, sh.arena_size) < 0)
584         ret = 2;
585 #endif
586 #ifndef NO_MADVISE
587     if (madvise(sh.arena, sh.arena_size, MADV_DONTDUMP) < 0)
588         ret = 2;
589 #endif
590 
591     return ret;
592 
593  err:
594     sh_done();
595     return 0;
596 }
597 
sh_done(void)598 static void sh_done(void)
599 {
600     OPENSSL_free(sh.freelist);
601     OPENSSL_free(sh.bittable);
602     OPENSSL_free(sh.bitmalloc);
603 #if !defined(_WIN32)
604     if (sh.map_result != MAP_FAILED && sh.map_size)
605         munmap(sh.map_result, sh.map_size);
606 #else
607     if (sh.map_result != NULL && sh.map_size)
608         VirtualFree(sh.map_result, 0, MEM_RELEASE);
609 #endif
610     memset(&sh, 0, sizeof(sh));
611 }
612 
sh_allocated(const char * ptr)613 static int sh_allocated(const char *ptr)
614 {
615     return WITHIN_ARENA(ptr) ? 1 : 0;
616 }
617 
sh_find_my_buddy(char * ptr,int list)618 static char *sh_find_my_buddy(char *ptr, int list)
619 {
620     size_t bit;
621     char *chunk = NULL;
622 
623     bit = (ONE << list) + (ptr - sh.arena) / (sh.arena_size >> list);
624     bit ^= 1;
625 
626     if (TESTBIT(sh.bittable, bit) && !TESTBIT(sh.bitmalloc, bit))
627         chunk = sh.arena + ((bit & ((ONE << list) - 1)) * (sh.arena_size >> list));
628 
629     return chunk;
630 }
631 
sh_malloc(size_t size)632 static void *sh_malloc(size_t size)
633 {
634     ossl_ssize_t list, slist;
635     size_t i;
636     char *chunk;
637 
638     if (size > sh.arena_size)
639         return NULL;
640 
641     list = sh.freelist_size - 1;
642     for (i = sh.minsize; i < size; i <<= 1)
643         list--;
644     if (list < 0)
645         return NULL;
646 
647     /* try to find a larger entry to split */
648     for (slist = list; slist >= 0; slist--)
649         if (sh.freelist[slist] != NULL)
650             break;
651     if (slist < 0)
652         return NULL;
653 
654     /* split larger entry */
655     while (slist != list) {
656         char *temp = sh.freelist[slist];
657 
658         /* remove from bigger list */
659         OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
660         sh_clearbit(temp, slist, sh.bittable);
661         sh_remove_from_list(temp);
662         OPENSSL_assert(temp != sh.freelist[slist]);
663 
664         /* done with bigger list */
665         slist++;
666 
667         /* add to smaller list */
668         OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
669         sh_setbit(temp, slist, sh.bittable);
670         sh_add_to_list(&sh.freelist[slist], temp);
671         OPENSSL_assert(sh.freelist[slist] == temp);
672 
673         /* split in 2 */
674         temp += sh.arena_size >> slist;
675         OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
676         sh_setbit(temp, slist, sh.bittable);
677         sh_add_to_list(&sh.freelist[slist], temp);
678         OPENSSL_assert(sh.freelist[slist] == temp);
679 
680         OPENSSL_assert(temp-(sh.arena_size >> slist) == sh_find_my_buddy(temp, slist));
681     }
682 
683     /* peel off memory to hand back */
684     chunk = sh.freelist[list];
685     OPENSSL_assert(sh_testbit(chunk, list, sh.bittable));
686     sh_setbit(chunk, list, sh.bitmalloc);
687     sh_remove_from_list(chunk);
688 
689     OPENSSL_assert(WITHIN_ARENA(chunk));
690 
691     /* zero the free list header as a precaution against information leakage */
692     memset(chunk, 0, sizeof(SH_LIST));
693 
694     return chunk;
695 }
696 
sh_free(void * ptr)697 static void sh_free(void *ptr)
698 {
699     size_t list;
700     void *buddy;
701 
702     if (ptr == NULL)
703         return;
704     OPENSSL_assert(WITHIN_ARENA(ptr));
705     if (!WITHIN_ARENA(ptr))
706         return;
707 
708     list = sh_getlist(ptr);
709     OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
710     sh_clearbit(ptr, list, sh.bitmalloc);
711     sh_add_to_list(&sh.freelist[list], ptr);
712 
713     /* Try to coalesce two adjacent free areas. */
714     while ((buddy = sh_find_my_buddy(ptr, list)) != NULL) {
715         OPENSSL_assert(ptr == sh_find_my_buddy(buddy, list));
716         OPENSSL_assert(ptr != NULL);
717         OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
718         sh_clearbit(ptr, list, sh.bittable);
719         sh_remove_from_list(ptr);
720         OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
721         sh_clearbit(buddy, list, sh.bittable);
722         sh_remove_from_list(buddy);
723 
724         list--;
725 
726         /* Zero the higher addressed block's free list pointers */
727         memset(ptr > buddy ? ptr : buddy, 0, sizeof(SH_LIST));
728         if (ptr > buddy)
729             ptr = buddy;
730 
731         OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
732         sh_setbit(ptr, list, sh.bittable);
733         sh_add_to_list(&sh.freelist[list], ptr);
734         OPENSSL_assert(sh.freelist[list] == ptr);
735     }
736 }
737 
sh_actual_size(char * ptr)738 static size_t sh_actual_size(char *ptr)
739 {
740     int list;
741 
742     OPENSSL_assert(WITHIN_ARENA(ptr));
743     if (!WITHIN_ARENA(ptr))
744         return 0;
745     list = sh_getlist(ptr);
746     OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
747     return sh.arena_size / (ONE << list);
748 }
749 #endif /* OPENSSL_NO_SECURE_MEMORY */
750