2 * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
13 #include "internal/cryptlib.h"
14 #include "internal/thread_once.h"
15 #include <openssl/crypto.h>
16 #include <openssl/buffer.h>
17 #include "internal/bio.h"
18 #include <openssl/lhash.h>
20 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
21 # include <execinfo.h>
25 * The state changes to CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE when
26 * the application asks for it (usually after library initialisation for
27 * which no book-keeping is desired). State CRYPTO_MEM_CHECK_ON exists only
28 * temporarily when the library thinks that certain allocations should not be
29 * checked (e.g. the data structures used for memory checking). It is not
30 * suitable as an initial state: the library will unexpectedly enable memory
31 * checking when it executes one of those sections that want to disable
32 * checking temporarily. State CRYPTO_MEM_CHECK_ENABLE without ..._ON makes
33 * no sense whatsoever.
35 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
36 static int mh_mode = CRYPTO_MEM_CHECK_OFF;
39 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
40 static unsigned long order = 0; /* number of memory requests */
43 * For application-defined information (static C-string `info')
44 * to be displayed in memory leak list.
45 * Each thread has its own stack. For applications, there is
46 * OPENSSL_mem_debug_push("...") to push an entry,
47 * OPENSSL_mem_debug_pop() to pop an entry,
49 struct app_mem_info_st {
50 CRYPTO_THREAD_ID threadid;
54 struct app_mem_info_st *next; /* tail of thread's stack */
58 static CRYPTO_ONCE memdbg_init = CRYPTO_ONCE_STATIC_INIT;
59 static CRYPTO_RWLOCK *malloc_lock = NULL;
60 static CRYPTO_RWLOCK *long_malloc_lock = NULL;
61 static CRYPTO_THREAD_LOCAL appinfokey;
63 /* memory-block description */
69 CRYPTO_THREAD_ID threadid;
73 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
79 static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
80 * key); access requires MALLOC2 lock */
82 /* num_disable > 0 iff mh_mode == CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
83 static unsigned int num_disable = 0;
86 * Valid iff num_disable > 0. long_malloc_lock is locked exactly in this
87 * case (by the thread named in disabling_thread).
89 static CRYPTO_THREAD_ID disabling_threadid;
91 DEFINE_RUN_ONCE_STATIC(do_memdbg_init)
93 malloc_lock = CRYPTO_THREAD_glock_new("malloc");
94 long_malloc_lock = CRYPTO_THREAD_glock_new("long_malloc");
95 if (malloc_lock == NULL || long_malloc_lock == NULL
96 || !CRYPTO_THREAD_init_local(&appinfokey, NULL)) {
97 CRYPTO_THREAD_lock_free(malloc_lock);
99 CRYPTO_THREAD_lock_free(long_malloc_lock);
100 long_malloc_lock = NULL;
106 static void app_info_free(APP_INFO *inf)
110 if (--(inf->references) <= 0) {
111 app_info_free(inf->next);
117 int CRYPTO_mem_ctrl(int mode)
119 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
124 if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
127 CRYPTO_THREAD_write_lock(malloc_lock);
132 case CRYPTO_MEM_CHECK_ON:
133 mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
137 case CRYPTO_MEM_CHECK_OFF:
142 /* switch off temporarily (for library-internal use): */
143 case CRYPTO_MEM_CHECK_DISABLE:
144 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
145 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
146 /* see if we don't have long_malloc_lock already */
148 || !CRYPTO_THREAD_compare_id(disabling_threadid, cur)) {
150 * Long-time lock long_malloc_lock must not be claimed
151 * while we're holding malloc_lock, or we'll deadlock
152 * if somebody else holds long_malloc_lock (and cannot
153 * release it because we block entry to this function). Give
154 * them a chance, first, and then claim the locks in
155 * appropriate order (long-time lock first).
157 CRYPTO_THREAD_unlock(malloc_lock);
159 * Note that after we have waited for long_malloc_lock and
160 * malloc_lock, we'll still be in the right "case" and
161 * "if" branch because MemCheck_start and MemCheck_stop may
162 * never be used while there are multiple OpenSSL threads.
164 CRYPTO_THREAD_write_lock(long_malloc_lock);
165 CRYPTO_THREAD_write_lock(malloc_lock);
166 mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
167 disabling_threadid = cur;
173 case CRYPTO_MEM_CHECK_ENABLE:
174 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
175 if (num_disable) { /* always true, or something is going wrong */
177 if (num_disable == 0) {
178 mh_mode |= CRYPTO_MEM_CHECK_ENABLE;
179 CRYPTO_THREAD_unlock(long_malloc_lock);
185 CRYPTO_THREAD_unlock(malloc_lock);
190 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
192 static int mem_check_on(void)
195 CRYPTO_THREAD_ID cur;
197 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
198 if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
201 cur = CRYPTO_THREAD_get_current_id();
202 CRYPTO_THREAD_read_lock(malloc_lock);
204 ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
205 || !CRYPTO_THREAD_compare_id(disabling_threadid, cur);
207 CRYPTO_THREAD_unlock(malloc_lock);
212 static int mem_cmp(const MEM *a, const MEM *b)
215 const char *ap = (const char *)a->addr, *bp = (const char *)b->addr;
223 return (const char *)a->addr - (const char *)b->addr;
227 static unsigned long mem_hash(const MEM *a)
231 ret = (size_t)a->addr;
233 ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
237 /* returns 1 if there was an info to pop, 0 if the stack was empty. */
238 static int pop_info(void)
240 APP_INFO *current = NULL;
242 if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
245 current = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
246 if (current != NULL) {
247 APP_INFO *next = current->next;
251 CRYPTO_THREAD_set_local(&appinfokey, next);
253 CRYPTO_THREAD_set_local(&appinfokey, NULL);
255 if (--(current->references) <= 0) {
256 current->next = NULL;
259 OPENSSL_free(current);
266 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
268 APP_INFO *ami, *amim;
271 if (mem_check_on()) {
272 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
274 if (!RUN_ONCE(&memdbg_init, do_memdbg_init)
275 || (ami = OPENSSL_malloc(sizeof(*ami))) == NULL)
278 ami->threadid = CRYPTO_THREAD_get_current_id();
285 amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
286 CRYPTO_THREAD_set_local(&appinfokey, ami);
292 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
298 int CRYPTO_mem_debug_pop(void)
302 if (mem_check_on()) {
303 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
305 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
310 static unsigned long break_order_num = 0;
312 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int before_p,
313 const char *file, int line)
318 switch (before_p & 127) {
325 if (mem_check_on()) {
326 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
328 if (!RUN_ONCE(&memdbg_init, do_memdbg_init)
329 || (m = OPENSSL_malloc(sizeof(*m))) == NULL) {
331 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
335 if ((mh = lh_MEM_new(mem_hash, mem_cmp)) == NULL) {
347 m->threadid = CRYPTO_THREAD_get_current_id();
349 if (order == break_order_num) {
354 # ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
355 m->array_siz = backtrace(m->array, OSSL_NELEM(m->array));
357 m->time = time(NULL);
359 amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
364 if ((mm = lh_MEM_insert(mh, m)) != NULL) {
365 /* Not good, but don't sweat it */
366 if (mm->app_info != NULL) {
367 mm->app_info->references--;
372 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
379 void CRYPTO_mem_debug_free(void *addr, int before_p,
380 const char *file, int line)
389 if (mem_check_on() && (mh != NULL)) {
390 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
393 mp = lh_MEM_delete(mh, &m);
395 app_info_free(mp->app_info);
399 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
407 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num,
408 int before_p, const char *file, int line)
420 CRYPTO_mem_debug_malloc(addr2, num, 128 | before_p, file, line);
424 if (mem_check_on()) {
425 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
428 mp = lh_MEM_delete(mh, &m);
432 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
433 mp->array_siz = backtrace(mp->array, OSSL_NELEM(mp->array));
435 (void)lh_MEM_insert(mh, mp);
438 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
445 typedef struct mem_leak_st {
446 int (*print_cb) (const char *str, size_t len, void *u);
452 static void print_leak(const MEM *m, MEM_LEAK *l)
456 size_t len = sizeof(buf), ami_cnt;
459 struct tm *lcl = NULL;
461 * Convert between CRYPTO_THREAD_ID (which could be anything at all) and
462 * a long. This may not be meaningful depending on what CRYPTO_THREAD_ID is
463 * but hopefully should give something sensible on most platforms
466 CRYPTO_THREAD_ID tid;
471 lcl = localtime(&m->time);
472 n = BIO_snprintf(bufp, len, "[%02d:%02d:%02d] ",
473 lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
481 n = BIO_snprintf(bufp, len, "%5lu file=%s, line=%d, ",
482 m->order, m->file, m->line);
489 tid.tid = m->threadid;
490 n = BIO_snprintf(bufp, len, "thread=%lu, ", tid.ltid);
496 n = BIO_snprintf(bufp, len, "number=%d, address=%p\n", m->num, m->addr);
502 l->print_cb(buf, (size_t)(bufp - buf), l->print_cb_arg);
518 if (ami_cnt >= sizeof(buf) - 1)
520 memset(buf, '>', ami_cnt);
523 tid.tid = amip->threadid;
524 n = BIO_snprintf(buf + ami_cnt, sizeof(buf) - ami_cnt,
525 " thread=%lu, file=%s, line=%d, info=\"",
526 tid.ltid, amip->file, amip->line);
529 buf_len = ami_cnt + n;
530 info_len = strlen(amip->info);
531 if (128 - buf_len - 3 < info_len) {
532 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
535 n = BIO_snprintf(buf + buf_len, sizeof(buf) - buf_len, "%s",
541 n = BIO_snprintf(buf + buf_len, sizeof(buf) - buf_len, "\"\n");
545 l->print_cb(buf, buf_len + n, l->print_cb_arg);
549 while (amip && CRYPTO_THREAD_compare_id(amip->threadid, ti));
552 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
555 char **strings = backtrace_symbols(m->array, m->array_siz);
557 for (i = 0; i < m->array_siz; i++)
558 fprintf(stderr, "##> %s\n", strings[i]);
564 IMPLEMENT_LHASH_DOALL_ARG_CONST(MEM, MEM_LEAK);
566 int CRYPTO_mem_leaks_cb(int (*cb) (const char *str, size_t len, void *u),
571 /* Ensure all resources are released */
574 if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
577 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
584 lh_MEM_doall_MEM_LEAK(mh, print_leak, &ml);
586 if (ml.chunks != 0) {
589 BIO_snprintf(buf, sizeof(buf), "%ld bytes leaked in %d chunks\n",
590 ml.bytes, ml.chunks);
591 cb(buf, strlen(buf), u);
594 * Make sure that, if we found no leaks, memory-leak debugging itself
595 * does not introduce memory leaks (which might irritate external
596 * debugging tools). (When someone enables leak checking, but does not
597 * call this function, we declare it to be their fault.)
601 CRYPTO_THREAD_write_lock(malloc_lock);
604 * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses
607 old_mh_mode = mh_mode;
608 mh_mode = CRYPTO_MEM_CHECK_OFF;
613 mh_mode = old_mh_mode;
614 CRYPTO_THREAD_unlock(malloc_lock);
616 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF);
618 /* Clean up locks etc */
619 CRYPTO_THREAD_cleanup_local(&appinfokey);
620 CRYPTO_THREAD_lock_free(malloc_lock);
621 CRYPTO_THREAD_lock_free(long_malloc_lock);
623 long_malloc_lock = NULL;
625 return ml.chunks == 0 ? 1 : 0;
628 static int print_bio(const char *str, size_t len, void *b)
630 return BIO_write((BIO *)b, str, len);
633 int CRYPTO_mem_leaks(BIO *b)
636 * OPENSSL_cleanup() will free the ex_data locks so we can't have any
637 * ex_data hanging around
641 return CRYPTO_mem_leaks_cb(print_bio, b);
644 # ifndef OPENSSL_NO_STDIO
645 int CRYPTO_mem_leaks_fp(FILE *fp)
651 * Need to turn off memory checking when allocated BIOs ... especially as
652 * we're creating them at a time when we're trying to check we've not
653 * left anything un-free()'d!!
655 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
656 b = BIO_new(BIO_s_file());
657 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
660 BIO_set_fp(b, fp, BIO_NOCLOSE);
661 ret = CRYPTO_mem_leaks_cb(print_bio, b);