2 * Copyright 1995-2016 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 <openssl/crypto.h>
15 #include <openssl/buffer.h>
16 #include "internal/bio.h"
17 #include <openssl/lhash.h>
19 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
20 # include <execinfo.h>
24 * The state changes to CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE when
25 * the application asks for it (usually after library initialisation for
26 * which no book-keeping is desired). State CRYPTO_MEM_CHECK_ON exists only
27 * temporarily when the library thinks that certain allocations should not be
28 * checked (e.g. the data structures used for memory checking). It is not
29 * suitable as an initial state: the library will unexpectedly enable memory
30 * checking when it executes one of those sections that want to disable
31 * checking temporarily. State CRYPTO_MEM_CHECK_ENABLE without ..._ON makes
32 * no sense whatsoever.
34 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
35 static int mh_mode = CRYPTO_MEM_CHECK_OFF;
38 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
39 static unsigned long order = 0; /* number of memory requests */
42 * For application-defined information (static C-string `info')
43 * to be displayed in memory leak list.
44 * Each thread has its own stack. For applications, there is
45 * OPENSSL_mem_debug_push("...") to push an entry,
46 * OPENSSL_mem_debug_pop() to pop an entry,
48 struct app_mem_info_st {
49 CRYPTO_THREAD_ID threadid;
53 struct app_mem_info_st *next; /* tail of thread's stack */
57 static CRYPTO_ONCE memdbg_init = CRYPTO_ONCE_STATIC_INIT;
58 static CRYPTO_RWLOCK *malloc_lock = NULL;
59 static CRYPTO_RWLOCK *long_malloc_lock = NULL;
60 static CRYPTO_THREAD_LOCAL appinfokey;
62 /* memory-block description */
68 CRYPTO_THREAD_ID threadid;
72 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
78 static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
79 * key); access requires MALLOC2 lock */
81 /* num_disable > 0 iff mh_mode == CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
82 static unsigned int num_disable = 0;
85 * Valid iff num_disable > 0. long_malloc_lock is locked exactly in this
86 * case (by the thread named in disabling_thread).
88 static CRYPTO_THREAD_ID disabling_threadid;
90 static void do_memdbg_init(void)
92 malloc_lock = CRYPTO_THREAD_lock_new();
93 long_malloc_lock = CRYPTO_THREAD_lock_new();
94 CRYPTO_THREAD_init_local(&appinfokey, NULL);
97 static void app_info_free(APP_INFO *inf)
101 if (--(inf->references) <= 0) {
102 app_info_free(inf->next);
108 int CRYPTO_mem_ctrl(int mode)
110 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
115 if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
118 CRYPTO_THREAD_write_lock(malloc_lock);
123 case CRYPTO_MEM_CHECK_ON:
124 mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
128 case CRYPTO_MEM_CHECK_OFF:
133 /* switch off temporarily (for library-internal use): */
134 case CRYPTO_MEM_CHECK_DISABLE:
135 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
136 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
137 /* see if we don't have long_malloc_lock already */
139 || !CRYPTO_THREAD_compare_id(disabling_threadid, cur)) {
141 * Long-time lock long_malloc_lock must not be claimed
142 * while we're holding malloc_lock, or we'll deadlock
143 * if somebody else holds long_malloc_lock (and cannot
144 * release it because we block entry to this function). Give
145 * them a chance, first, and then claim the locks in
146 * appropriate order (long-time lock first).
148 CRYPTO_THREAD_unlock(malloc_lock);
150 * Note that after we have waited for long_malloc_lock and
151 * malloc_lock, we'll still be in the right "case" and
152 * "if" branch because MemCheck_start and MemCheck_stop may
153 * never be used while there are multiple OpenSSL threads.
155 CRYPTO_THREAD_write_lock(long_malloc_lock);
156 CRYPTO_THREAD_write_lock(malloc_lock);
157 mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
158 disabling_threadid = cur;
164 case CRYPTO_MEM_CHECK_ENABLE:
165 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
166 if (num_disable) { /* always true, or something is going wrong */
168 if (num_disable == 0) {
169 mh_mode |= CRYPTO_MEM_CHECK_ENABLE;
170 CRYPTO_THREAD_unlock(long_malloc_lock);
176 CRYPTO_THREAD_unlock(malloc_lock);
181 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
183 static int mem_check_on(void)
186 CRYPTO_THREAD_ID cur;
188 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
189 if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
192 cur = CRYPTO_THREAD_get_current_id();
193 CRYPTO_THREAD_read_lock(malloc_lock);
195 ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
196 || !CRYPTO_THREAD_compare_id(disabling_threadid, cur);
198 CRYPTO_THREAD_unlock(malloc_lock);
203 static int mem_cmp(const MEM *a, const MEM *b)
206 const char *ap = (const char *)a->addr, *bp = (const char *)b->addr;
214 return (const char *)a->addr - (const char *)b->addr;
218 static unsigned long mem_hash(const MEM *a)
222 ret = (size_t)a->addr;
224 ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
228 /* returns 1 if there was an info to pop, 0 if the stack was empty. */
229 static int pop_info(void)
231 APP_INFO *current = NULL;
233 if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
236 current = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
237 if (current != NULL) {
238 APP_INFO *next = current->next;
242 CRYPTO_THREAD_set_local(&appinfokey, next);
244 CRYPTO_THREAD_set_local(&appinfokey, NULL);
246 if (--(current->references) <= 0) {
247 current->next = NULL;
250 OPENSSL_free(current);
257 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
259 APP_INFO *ami, *amim;
262 if (mem_check_on()) {
263 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
265 if (!RUN_ONCE(&memdbg_init, do_memdbg_init)
266 || (ami = OPENSSL_malloc(sizeof(*ami))) == NULL)
269 ami->threadid = CRYPTO_THREAD_get_current_id();
276 amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
277 CRYPTO_THREAD_set_local(&appinfokey, ami);
283 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
289 int CRYPTO_mem_debug_pop(void)
293 if (mem_check_on()) {
294 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
296 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
301 static unsigned long break_order_num = 0;
303 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int before_p,
304 const char *file, int line)
309 switch (before_p & 127) {
316 if (mem_check_on()) {
317 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
319 if (!RUN_ONCE(&memdbg_init, do_memdbg_init)
320 || (m = OPENSSL_malloc(sizeof(*m))) == NULL) {
322 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
326 if ((mh = lh_MEM_new(mem_hash, mem_cmp)) == NULL) {
338 m->threadid = CRYPTO_THREAD_get_current_id();
340 if (order == break_order_num) {
345 # ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
346 m->array_siz = backtrace(m->array, OSSL_NELEM(m->array));
348 m->time = time(NULL);
350 amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
355 if ((mm = lh_MEM_insert(mh, m)) != NULL) {
356 /* Not good, but don't sweat it */
357 if (mm->app_info != NULL) {
358 mm->app_info->references--;
363 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
370 void CRYPTO_mem_debug_free(void *addr, int before_p,
371 const char *file, int line)
380 if (mem_check_on() && (mh != NULL)) {
381 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
384 mp = lh_MEM_delete(mh, &m);
386 app_info_free(mp->app_info);
390 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
398 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num,
399 int before_p, const char *file, int line)
411 CRYPTO_mem_debug_malloc(addr2, num, 128 | before_p, file, line);
415 if (mem_check_on()) {
416 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
419 mp = lh_MEM_delete(mh, &m);
423 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
424 mp->array_siz = backtrace(mp->array, OSSL_NELEM(mp->array));
426 (void)lh_MEM_insert(mh, mp);
429 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
436 typedef struct mem_leak_st {
442 static void print_leak(const MEM *m, MEM_LEAK *l)
448 struct tm *lcl = NULL;
450 * Convert between CRYPTO_THREAD_ID (which could be anything at all) and
451 * a long. This may not be meaningful depending on what CRYPTO_THREAD_ID is
452 * but hopefully should give something sensible on most platforms
455 CRYPTO_THREAD_ID tid;
460 #define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))
462 lcl = localtime(&m->time);
463 BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
464 lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
465 bufp += strlen(bufp);
467 BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
468 m->order, m->file, m->line);
469 bufp += strlen(bufp);
472 tid.tid = m->threadid;
473 BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ", tid.ltid);
474 bufp += strlen(bufp);
476 BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%p\n",
478 bufp += strlen(bufp);
480 BIO_puts(l->bio, buf);
496 memset(buf, '>', ami_cnt);
498 tid.tid = amip->threadid;
499 BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
500 " thread=%lu, file=%s, line=%d, info=\"",
501 tid.ltid, amip->file,
503 buf_len = strlen(buf);
504 info_len = strlen(amip->info);
505 if (128 - buf_len - 3 < info_len) {
506 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
509 OPENSSL_strlcpy(buf + buf_len, amip->info, sizeof buf - buf_len);
510 buf_len = strlen(buf);
512 BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
514 BIO_puts(l->bio, buf);
518 while (amip && CRYPTO_THREAD_compare_id(amip->threadid, ti));
521 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
524 char **strings = backtrace_symbols(m->array, m->array_siz);
526 for (i = 0; i < m->array_siz; i++)
527 fprintf(stderr, "##> %s\n", strings[i]);
533 IMPLEMENT_LHASH_DOALL_ARG_CONST(MEM, MEM_LEAK);
535 int CRYPTO_mem_leaks(BIO *b)
540 * OPENSSL_cleanup() will free the ex_data locks so we can't have any
541 * ex_data hanging around
545 /* Ensure all resources are released */
548 if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
551 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
557 lh_MEM_doall_MEM_LEAK(mh, print_leak, &ml);
559 if (ml.chunks != 0) {
560 BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks);
563 * Make sure that, if we found no leaks, memory-leak debugging itself
564 * does not introduce memory leaks (which might irritate external
565 * debugging tools). (When someone enables leak checking, but does not
566 * call this function, we declare it to be their fault.)
570 CRYPTO_THREAD_write_lock(malloc_lock);
573 * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses
576 old_mh_mode = mh_mode;
577 mh_mode = CRYPTO_MEM_CHECK_OFF;
582 mh_mode = old_mh_mode;
583 CRYPTO_THREAD_unlock(malloc_lock);
585 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF);
587 /* Clean up locks etc */
588 CRYPTO_THREAD_cleanup_local(&appinfokey);
589 CRYPTO_THREAD_lock_free(malloc_lock);
590 CRYPTO_THREAD_lock_free(long_malloc_lock);
592 long_malloc_lock = NULL;
594 return ml.chunks == 0 ? 1 : 0;
597 # ifndef OPENSSL_NO_STDIO
598 int CRYPTO_mem_leaks_fp(FILE *fp)
604 * Need to turn off memory checking when allocated BIOs ... especially as
605 * we're creating them at a time when we're trying to check we've not
606 * left anything un-free()'d!!
608 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
609 b = BIO_new(BIO_s_file());
610 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
613 BIO_set_fp(b, fp, BIO_NOCLOSE);
614 ret = CRYPTO_mem_leaks(b);