1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
57 /* ====================================================================
58 * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
114 #include "internal/cryptlib.h"
115 #include <openssl/crypto.h>
116 #include <openssl/buffer.h>
117 #include "internal/bio.h"
118 #include <openssl/lhash.h>
120 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
121 # include <execinfo.h>
125 * The state changes to CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE when
126 * the application asks for it (usually after library initialisation for
127 * which no book-keeping is desired). State CRYPTO_MEM_CHECK_ON exists only
128 * temporarily when the library thinks that certain allocations should not be
129 * checked (e.g. the data structures used for memory checking). It is not
130 * suitable as an initial state: the library will unexpectedly enable memory
131 * checking when it executes one of those sections that want to disable
132 * checking temporarily. State CRYPTO_MEM_CHECK_ENABLE without ..._ON makes
133 * no sense whatsoever.
135 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
136 static int mh_mode = CRYPTO_MEM_CHECK_OFF;
139 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
140 static unsigned long order = 0; /* number of memory requests */
143 * For application-defined information (static C-string `info')
144 * to be displayed in memory leak list.
145 * Each thread has its own stack. For applications, there is
146 * OPENSSL_mem_debug_push("...") to push an entry,
147 * OPENSSL_mem_debug_pop() to pop an entry,
149 struct app_mem_info_st {
150 CRYPTO_THREAD_ID threadid;
154 struct app_mem_info_st *next; /* tail of thread's stack */
158 static CRYPTO_ONCE memdbg_init = CRYPTO_ONCE_STATIC_INIT;
159 static CRYPTO_RWLOCK *malloc_lock = NULL;
160 static CRYPTO_RWLOCK *long_malloc_lock = NULL;
161 static CRYPTO_THREAD_LOCAL appinfokey;
163 /* memory-block description */
169 CRYPTO_THREAD_ID threadid;
173 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
179 static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
180 * key); access requires MALLOC2 lock */
182 /* num_disable > 0 iff mh_mode == CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
183 static unsigned int num_disable = 0;
186 * Valid iff num_disable > 0. long_malloc_lock is locked exactly in this
187 * case (by the thread named in disabling_thread).
189 static CRYPTO_THREAD_ID disabling_threadid;
191 static void do_memdbg_init(void)
193 malloc_lock = CRYPTO_THREAD_lock_new();
194 long_malloc_lock = CRYPTO_THREAD_lock_new();
195 CRYPTO_THREAD_init_local(&appinfokey, NULL);
198 static void app_info_free(APP_INFO *inf)
202 if (--(inf->references) <= 0) {
203 app_info_free(inf->next);
209 int CRYPTO_mem_ctrl(int mode)
211 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
216 CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
218 CRYPTO_THREAD_write_lock(malloc_lock);
223 case CRYPTO_MEM_CHECK_ON:
224 mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
228 case CRYPTO_MEM_CHECK_OFF:
233 /* switch off temporarily (for library-internal use): */
234 case CRYPTO_MEM_CHECK_DISABLE:
235 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
236 CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
237 /* see if we don't have long_malloc_lock already */
239 || !CRYPTO_THREAD_compare_id(disabling_threadid, cur)) {
241 * Long-time lock long_malloc_lock must not be claimed
242 * while we're holding malloc_lock, or we'll deadlock
243 * if somebody else holds long_malloc_lock (and cannot
244 * release it because we block entry to this function). Give
245 * them a chance, first, and then claim the locks in
246 * appropriate order (long-time lock first).
248 CRYPTO_THREAD_unlock(malloc_lock);
250 * Note that after we have waited for long_malloc_lock and
251 * malloc_lock, we'll still be in the right "case" and
252 * "if" branch because MemCheck_start and MemCheck_stop may
253 * never be used while there are multiple OpenSSL threads.
255 CRYPTO_THREAD_write_lock(long_malloc_lock);
256 CRYPTO_THREAD_write_lock(malloc_lock);
257 mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
258 disabling_threadid = cur;
264 case CRYPTO_MEM_CHECK_ENABLE:
265 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
266 if (num_disable) { /* always true, or something is going wrong */
268 if (num_disable == 0) {
269 mh_mode |= CRYPTO_MEM_CHECK_ENABLE;
270 CRYPTO_THREAD_unlock(long_malloc_lock);
276 CRYPTO_THREAD_unlock(malloc_lock);
281 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
283 static int mem_check_on(void)
286 CRYPTO_THREAD_ID cur;
288 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
289 CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
291 cur = CRYPTO_THREAD_get_current_id();
292 CRYPTO_THREAD_read_lock(malloc_lock);
294 ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
295 || !CRYPTO_THREAD_compare_id(disabling_threadid, cur);
297 CRYPTO_THREAD_unlock(malloc_lock);
302 static int mem_cmp(const MEM *a, const MEM *b)
305 const char *ap = (const char *)a->addr, *bp = (const char *)b->addr;
313 return (const char *)a->addr - (const char *)b->addr;
317 static unsigned long mem_hash(const MEM *a)
321 ret = (size_t)a->addr;
323 ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
327 /* returns 1 if there was an info to pop, 0 if the stack was empty. */
328 static int pop_info(void)
330 APP_INFO *current = NULL;
332 CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
333 current = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
334 if (current != NULL) {
335 APP_INFO *next = current->next;
339 CRYPTO_THREAD_set_local(&appinfokey, next);
341 CRYPTO_THREAD_set_local(&appinfokey, NULL);
343 if (--(current->references) <= 0) {
344 current->next = NULL;
347 OPENSSL_free(current);
354 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
356 APP_INFO *ami, *amim;
359 if (mem_check_on()) {
360 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
362 CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
364 if ((ami = OPENSSL_malloc(sizeof(*ami))) == NULL)
367 ami->threadid = CRYPTO_THREAD_get_current_id();
374 amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
375 CRYPTO_THREAD_set_local(&appinfokey, ami);
381 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
387 int CRYPTO_mem_debug_pop(void)
391 if (mem_check_on()) {
392 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
394 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
399 static unsigned long break_order_num = 0;
401 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int before_p,
402 const char *file, int line)
407 switch (before_p & 127) {
414 if (mem_check_on()) {
415 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
417 CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
419 if ((m = OPENSSL_malloc(sizeof(*m))) == NULL) {
421 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
425 if ((mh = lh_MEM_new(mem_hash, mem_cmp)) == NULL) {
437 m->threadid = CRYPTO_THREAD_get_current_id();
439 if (order == break_order_num) {
444 # ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
445 m->array_siz = backtrace(m->array, OSSL_NELEM(m->array));
447 m->time = time(NULL);
449 amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
454 if ((mm = lh_MEM_insert(mh, m)) != NULL) {
455 /* Not good, but don't sweat it */
456 if (mm->app_info != NULL) {
457 mm->app_info->references--;
462 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
469 void CRYPTO_mem_debug_free(void *addr, int before_p,
470 const char *file, int line)
479 if (mem_check_on() && (mh != NULL)) {
480 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
483 mp = lh_MEM_delete(mh, &m);
485 app_info_free(mp->app_info);
489 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
497 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num,
498 int before_p, const char *file, int line)
510 CRYPTO_mem_debug_malloc(addr2, num, 128 | before_p, file, line);
514 if (mem_check_on()) {
515 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
518 mp = lh_MEM_delete(mh, &m);
522 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
523 mp->array_siz = backtrace(mp->array, OSSL_NELEM(mp->array));
525 (void)lh_MEM_insert(mh, mp);
528 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
535 typedef struct mem_leak_st {
541 static void print_leak(const MEM *m, MEM_LEAK *l)
547 struct tm *lcl = NULL;
549 * Convert between CRYPTO_THREAD_ID (which could be anything at all) and
550 * a long. This may not be meaningful depending on what CRYPTO_THREAD_ID is
551 * but hopefully should give something sensible on most platforms
554 CRYPTO_THREAD_ID tid;
559 #define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))
561 lcl = localtime(&m->time);
562 BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
563 lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
564 bufp += strlen(bufp);
566 BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
567 m->order, m->file, m->line);
568 bufp += strlen(bufp);
571 tid.tid = m->threadid;
572 BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ", tid.ltid);
573 bufp += strlen(bufp);
575 BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%p\n",
577 bufp += strlen(bufp);
579 BIO_puts(l->bio, buf);
595 memset(buf, '>', ami_cnt);
597 tid.tid = amip->threadid;
598 BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
599 " thread=%lu, file=%s, line=%d, info=\"",
600 tid.ltid, amip->file,
602 buf_len = strlen(buf);
603 info_len = strlen(amip->info);
604 if (128 - buf_len - 3 < info_len) {
605 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
608 OPENSSL_strlcpy(buf + buf_len, amip->info, sizeof buf - buf_len);
609 buf_len = strlen(buf);
611 BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
613 BIO_puts(l->bio, buf);
617 while (amip && CRYPTO_THREAD_compare_id(amip->threadid, ti));
620 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
623 char **strings = backtrace_symbols(m->array, m->array_siz);
625 for (i = 0; i < m->array_siz; i++)
626 fprintf(stderr, "##> %s\n", strings[i]);
632 IMPLEMENT_LHASH_DOALL_ARG_CONST(MEM, MEM_LEAK);
634 int CRYPTO_mem_leaks(BIO *b)
639 * OPENSSL_cleanup() will free the ex_data locks so we can't have any
640 * ex_data hanging around
644 /* Ensure all resources are released */
647 CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
649 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
655 lh_MEM_doall_MEM_LEAK(mh, print_leak, &ml);
657 if (ml.chunks != 0) {
658 BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks);
661 * Make sure that, if we found no leaks, memory-leak debugging itself
662 * does not introduce memory leaks (which might irritate external
663 * debugging tools). (When someone enables leak checking, but does not
664 * call this function, we declare it to be their fault.)
668 CRYPTO_THREAD_write_lock(malloc_lock);
671 * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses
674 old_mh_mode = mh_mode;
675 mh_mode = CRYPTO_MEM_CHECK_OFF;
680 mh_mode = old_mh_mode;
681 CRYPTO_THREAD_unlock(malloc_lock);
683 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF);
685 /* Clean up locks etc */
686 CRYPTO_THREAD_cleanup_local(&appinfokey);
687 CRYPTO_THREAD_lock_free(malloc_lock);
688 CRYPTO_THREAD_lock_free(long_malloc_lock);
690 long_malloc_lock = NULL;
692 return ml.chunks == 0 ? 1 : 0;
695 # ifndef OPENSSL_NO_STDIO
696 int CRYPTO_mem_leaks_fp(FILE *fp)
702 * Need to turn off memory checking when allocated BIOs ... especially as
703 * we're creating them at a time when we're trying to check we've not
704 * left anything un-free()'d!!
706 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
707 b = BIO_new(BIO_s_file());
708 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
711 BIO_set_fp(b, fp, BIO_NOCLOSE);
712 ret = CRYPTO_mem_leaks(b);