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 <openssl/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_THREADID threadid;
154 struct app_mem_info_st *next; /* tail of thread's stack */
159 * hash-table with those app_mem_info_st's that are at the
160 * top of their thread's stack (with `thread' as key); access requires
163 static LHASH_OF(APP_INFO) *amih = NULL;
165 /* memory-block description */
171 CRYPTO_THREADID threadid;
175 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
181 static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
182 * key); access requires MALLOC2 lock */
184 /* num_disable > 0 iff mh_mode == CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
185 static unsigned int num_disable = 0;
188 * Valid iff num_disable > 0. CRYPTO_LOCK_MALLOC2 is locked exactly in this
189 * case (by the thread named in disabling_thread).
191 static CRYPTO_THREADID disabling_threadid;
193 static void app_info_free(APP_INFO *inf)
197 if (--(inf->references) <= 0) {
198 app_info_free(inf->next);
204 int CRYPTO_mem_ctrl(int mode)
206 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
211 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
216 case CRYPTO_MEM_CHECK_ON:
217 mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
221 case CRYPTO_MEM_CHECK_OFF:
226 /* switch off temporarily (for library-internal use): */
227 case CRYPTO_MEM_CHECK_DISABLE:
228 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
230 CRYPTO_THREADID_current(&cur);
231 /* see if we don't have the MALLOC2 lock already */
233 || CRYPTO_THREADID_cmp(&disabling_threadid, &cur)) {
235 * Long-time lock CRYPTO_LOCK_MALLOC2 must not be claimed
236 * while we're holding CRYPTO_LOCK_MALLOC, or we'll deadlock
237 * if somebody else holds CRYPTO_LOCK_MALLOC2 (and cannot
238 * release it because we block entry to this function). Give
239 * them a chance, first, and then claim the locks in
240 * appropriate order (long-time lock first).
242 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
244 * Note that after we have waited for CRYPTO_LOCK_MALLOC2 and
245 * CRYPTO_LOCK_MALLOC, we'll still be in the right "case" and
246 * "if" branch because MemCheck_start and MemCheck_stop may
247 * never be used while there are multiple OpenSSL threads.
249 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC2);
250 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
251 mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
252 CRYPTO_THREADID_cpy(&disabling_threadid, &cur);
258 case CRYPTO_MEM_CHECK_ENABLE:
259 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
260 if (num_disable) { /* always true, or something is going wrong */
262 if (num_disable == 0) {
263 mh_mode |= CRYPTO_MEM_CHECK_ENABLE;
264 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
270 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
275 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
277 static int mem_check_on(void)
281 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
283 CRYPTO_THREADID_current(&cur);
284 CRYPTO_r_lock(CRYPTO_LOCK_MALLOC);
286 ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
287 || CRYPTO_THREADID_cmp(&disabling_threadid, &cur);
289 CRYPTO_r_unlock(CRYPTO_LOCK_MALLOC);
294 static int mem_cmp(const MEM *a, const MEM *b)
297 const char *ap = (const char *)a->addr, *bp = (const char *)b->addr;
305 return (const char *)a->addr - (const char *)b->addr;
309 static unsigned long mem_hash(const MEM *a)
313 ret = (size_t)a->addr;
315 ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
319 static int app_info_cmp(const APP_INFO *a, const APP_INFO *b)
321 return CRYPTO_THREADID_cmp(&a->threadid, &b->threadid);
324 static unsigned long app_info_hash(const APP_INFO *a)
328 ret = CRYPTO_THREADID_hash(&a->threadid);
329 /* This is left in as a "who am I to question legacy?" measure */
330 ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
334 /* returns 1 if there was an info to pop, 0 if the stack was empty. */
335 static int pop_info(void)
338 APP_INFO *current = NULL;
341 CRYPTO_THREADID_current(&tmp.threadid);
342 if ((current = lh_APP_INFO_delete(amih, &tmp)) != NULL) {
343 APP_INFO *next = current->next;
347 (void)lh_APP_INFO_insert(amih, next);
349 if (--(current->references) <= 0) {
350 current->next = NULL;
353 OPENSSL_free(current);
361 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
363 APP_INFO *ami, *amim;
366 if (mem_check_on()) {
367 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
369 if ((ami = OPENSSL_malloc(sizeof(*ami))) == NULL)
372 if ((amih = lh_APP_INFO_new(app_info_hash, app_info_cmp)) == NULL) {
378 CRYPTO_THREADID_current(&ami->threadid);
385 if ((amim = lh_APP_INFO_insert(amih, ami)) != NULL)
389 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
395 int CRYPTO_mem_debug_pop(void)
399 if (mem_check_on()) {
400 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
402 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
407 static unsigned long break_order_num = 0;
409 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int before_p,
410 const char *file, int line)
415 switch (before_p & 127) {
422 if (mem_check_on()) {
423 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
424 if ((m = OPENSSL_malloc(sizeof(*m))) == NULL) {
426 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
430 if ((mh = lh_MEM_new(mem_hash, mem_cmp)) == NULL) {
442 CRYPTO_THREADID_current(&m->threadid);
444 if (order == break_order_num) {
449 # ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
450 m->array_siz = backtrace(m->array, OSSL_NELEM(m->array));
452 m->time = time(NULL);
454 CRYPTO_THREADID_current(&tmp.threadid);
457 && (amim = lh_APP_INFO_retrieve(amih, &tmp)) != NULL) {
462 if ((mm = lh_MEM_insert(mh, m)) != NULL) {
463 /* Not good, but don't sweat it */
464 if (mm->app_info != NULL) {
465 mm->app_info->references--;
470 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
477 void CRYPTO_mem_debug_free(void *addr, int before_p,
478 const char *file, int line)
487 if (mem_check_on() && (mh != NULL)) {
488 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
491 mp = lh_MEM_delete(mh, &m);
493 app_info_free(mp->app_info);
497 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
505 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num,
506 int before_p, const char *file, int line)
518 CRYPTO_mem_debug_malloc(addr2, num, 128 | before_p, file, line);
522 if (mem_check_on()) {
523 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
526 mp = lh_MEM_delete(mh, &m);
530 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
531 mp->array_siz = backtrace(mp->array, OSSL_NELEM(mp->array));
533 (void)lh_MEM_insert(mh, mp);
536 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
543 typedef struct mem_leak_st {
550 static void print_leak(const MEM *m, MEM_LEAK *l)
556 struct tm *lcl = NULL;
559 #define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))
561 /* Is one "leak" the BIO we were given? */
562 if (m->addr == (char *)l->bio) {
567 lcl = localtime(&m->time);
568 BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
569 lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
570 bufp += strlen(bufp);
572 BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
573 m->order, m->file, m->line);
574 bufp += strlen(bufp);
576 BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ",
577 CRYPTO_THREADID_hash(&m->threadid));
578 bufp += strlen(bufp);
580 BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%p\n",
582 bufp += strlen(bufp);
584 BIO_puts(l->bio, buf);
593 CRYPTO_THREADID_cpy(&ti, &amip->threadid);
600 memset(buf, '>', ami_cnt);
601 BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
602 " thread=%lu, file=%s, line=%d, info=\"",
603 CRYPTO_THREADID_hash(&amip->threadid), amip->file,
605 buf_len = strlen(buf);
606 info_len = strlen(amip->info);
607 if (128 - buf_len - 3 < info_len) {
608 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
611 OPENSSL_strlcpy(buf + buf_len, amip->info, sizeof buf - buf_len);
612 buf_len = strlen(buf);
614 BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
616 BIO_puts(l->bio, buf);
620 while (amip && !CRYPTO_THREADID_cmp(&amip->threadid, &ti));
623 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
626 char **strings = backtrace_symbols(m->array, m->array_siz);
628 for (i = 0; i < m->array_siz; i++)
629 fprintf(stderr, "##> %s\n", strings[i]);
635 IMPLEMENT_LHASH_DOALL_ARG_CONST(MEM, MEM_LEAK);
637 int CRYPTO_mem_leaks(BIO *b)
641 if (mh == NULL && amih == NULL)
644 /* Ensure all resources are released */
647 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
654 lh_MEM_doall_MEM_LEAK(mh, print_leak, &ml);
655 /* Don't count the BIO that was passed in as a "leak" */
656 if (ml.seen && ml.chunks >= 1 && ml.bytes >= (int)sizeof (*b)) {
658 ml.bytes -= (int)sizeof (*b);
660 if (ml.chunks != 0) {
661 BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks);
664 * Make sure that, if we found no leaks, memory-leak debugging itself
665 * does not introduce memory leaks (which might irritate external
666 * debugging tools). (When someone enables leak checking, but does not
667 * call this function, we declare it to be their fault.)
671 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
674 * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses
677 old_mh_mode = mh_mode;
678 mh_mode = CRYPTO_MEM_CHECK_OFF;
683 if (lh_APP_INFO_num_items(amih) == 0) {
684 lh_APP_INFO_free(amih);
689 mh_mode = old_mh_mode;
690 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
692 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
693 return ml.chunks == 0 ? 1 : 0;
696 # ifndef OPENSSL_NO_STDIO
697 int CRYPTO_mem_leaks_fp(FILE *fp)
702 if (mh == NULL && amih == NULL)
705 * Need to turn off memory checking when allocated BIOs ... especially as
706 * we're creating them at a time when we're trying to check we've not
707 * left anything un-free()'d!!
709 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
710 b = BIO_new(BIO_s_file());
711 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
714 BIO_set_fp(b, fp, BIO_NOCLOSE);
715 ret = CRYPTO_mem_leaks(b);