2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
58 /* ====================================================================
59 * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
87 * 6. Redistributions of any form whatsoever must retain the following
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
115 #include "internal/cryptlib.h"
116 #include <openssl/crypto.h>
117 #include <openssl/buffer.h>
118 #include <openssl/bio.h>
119 #include <openssl/lhash.h>
120 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
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 static int mh_mode = CRYPTO_MEM_CHECK_OFF;
137 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
138 static unsigned long order = 0; /* number of memory requests */
140 DECLARE_LHASH_OF(MEM);
141 static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
142 * key); access requires MALLOC2 lock */
145 * For application-defined information (static C-string `info')
146 * to be displayed in memory leak list.
147 * Each thread has its own stack. For applications, there is
148 * OPENSSL_mem_debug_push("...") to push an entry,
149 * OPENSSL_mem_debug_pop() to pop an entry,
151 typedef struct app_mem_info_st {
152 CRYPTO_THREADID threadid;
156 struct app_mem_info_st *next; /* tail of thread's stack */
161 * hash-table with those app_mem_info_st's that are at the
162 * top of their thread's stack (with `thread' as key); access requires
165 DECLARE_LHASH_OF(APP_INFO);
166 static LHASH_OF(APP_INFO) *amih = NULL;
168 /* memory-block description */
169 typedef struct mem_st {
174 CRYPTO_THREADID threadid;
178 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
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 #ifndef 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 IMPLEMENT_LHASH_COMP_FN(mem, MEM)
311 static unsigned long mem_hash(const MEM *a)
315 ret = (size_t)a->addr;
317 ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
321 static IMPLEMENT_LHASH_HASH_FN(mem, MEM)
323 /* static int app_info_cmp(APP_INFO *a, APP_INFO *b) */
324 static int app_info_cmp(const void *a_void, const void *b_void)
326 return CRYPTO_THREADID_cmp(&((const APP_INFO *)a_void)->threadid,
327 &((const APP_INFO *)b_void)->threadid);
330 static IMPLEMENT_LHASH_COMP_FN(app_info, APP_INFO)
332 static unsigned long app_info_hash(const APP_INFO *a)
336 ret = CRYPTO_THREADID_hash(&a->threadid);
337 /* This is left in as a "who am I to question legacy?" measure */
338 ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
342 static IMPLEMENT_LHASH_HASH_FN(app_info, APP_INFO)
344 static APP_INFO *pop_info(void)
347 APP_INFO *ret = NULL;
350 CRYPTO_THREADID_current(&tmp.threadid);
351 if ((ret = lh_APP_INFO_delete(amih, &tmp)) != NULL) {
352 APP_INFO *next = ret->next;
356 (void)lh_APP_INFO_insert(amih, next);
358 if (--(ret->references) <= 0) {
369 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
371 APP_INFO *ami, *amim;
374 if (mem_check_on()) {
375 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
377 if ((ami = OPENSSL_malloc(sizeof(*ami))) == NULL)
380 if ((amih = lh_APP_INFO_new()) == NULL) {
386 CRYPTO_THREADID_current(&ami->threadid);
393 if ((amim = lh_APP_INFO_insert(amih, ami)) != NULL)
397 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
403 int CRYPTO_mem_debug_pop(void)
407 if (mem_check_on()) {
408 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
409 ret = (pop_info() != NULL);
410 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
415 static unsigned long break_order_num = 0;
417 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int before_p,
418 const char *file, int line)
423 switch (before_p & 127) {
430 if (mem_check_on()) {
431 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
432 if ((m = OPENSSL_malloc(sizeof(*m))) == NULL) {
434 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
438 if ((mh = lh_MEM_new()) == NULL) {
450 CRYPTO_THREADID_current(&m->threadid);
452 if (order == break_order_num) {
457 # if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
458 m->array_siz = backtrace(m->array, OSSL_NELEM(m->array));
460 m->time = time(NULL);
462 CRYPTO_THREADID_current(&tmp.threadid);
465 && (amim = lh_APP_INFO_retrieve(amih, &tmp)) != NULL) {
470 if ((mm = lh_MEM_insert(mh, m)) != NULL) {
471 /* Not good, but don't sweat it */
472 if (mm->app_info != NULL) {
473 mm->app_info->references--;
478 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
485 void CRYPTO_mem_debug_free(void *addr, int before_p)
494 if (mem_check_on() && (mh != NULL)) {
495 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
498 mp = lh_MEM_delete(mh, &m);
500 app_info_free(mp->app_info);
504 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
512 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num,
513 int before_p, const char *file, int line)
525 CRYPTO_mem_debug_malloc(addr2, num, 128 | before_p, file, line);
529 if (mem_check_on()) {
530 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
533 mp = lh_MEM_delete(mh, &m);
537 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
538 mp->array_siz = backtrace(mp->array, OSSL_NELEM(mp->array));
540 (void)lh_MEM_insert(mh, mp);
543 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
550 typedef struct mem_leak_st {
557 static void print_leak_doall_arg(const MEM *m, MEM_LEAK *l)
563 struct tm *lcl = NULL;
566 #define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))
568 /* Is one "leak" the BIO we were given? */
569 if (m->addr == (char *)l->bio) {
574 lcl = localtime(&m->time);
575 BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
576 lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
577 bufp += strlen(bufp);
579 BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
580 m->order, m->file, m->line);
581 bufp += strlen(bufp);
583 BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ",
584 CRYPTO_THREADID_hash(&m->threadid));
585 bufp += strlen(bufp);
587 BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%p\n",
589 bufp += strlen(bufp);
591 BIO_puts(l->bio, buf);
600 CRYPTO_THREADID_cpy(&ti, &amip->threadid);
607 memset(buf, '>', ami_cnt);
608 BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
609 " thread=%lu, file=%s, line=%d, info=\"",
610 CRYPTO_THREADID_hash(&amip->threadid), amip->file,
612 buf_len = strlen(buf);
613 info_len = strlen(amip->info);
614 if (128 - buf_len - 3 < info_len) {
615 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
618 OPENSSL_strlcpy(buf + buf_len, amip->info, sizeof buf - buf_len);
619 buf_len = strlen(buf);
621 BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
623 BIO_puts(l->bio, buf);
627 while (amip && !CRYPTO_THREADID_cmp(&amip->threadid, &ti));
630 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
633 char **strings = backtrace_symbols(m->array, m->array_siz);
635 for (i = 0; i < m->array_siz; i++)
636 fprintf(stderr, "##> %s\n", strings[i]);
642 static IMPLEMENT_LHASH_DOALL_ARG_FN(print_leak, const MEM, MEM_LEAK)
644 void CRYPTO_mem_leaks(BIO *b)
648 if (mh == NULL && amih == NULL)
651 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
658 lh_MEM_doall_arg(mh, LHASH_DOALL_ARG_FN(print_leak), MEM_LEAK, &ml);
659 /* Don't count the BIO that was passed in as a "leak" */
660 if (ml.seen && ml.chunks >= 1 && ml.bytes >= (int)sizeof (*b)) {
662 ml.bytes -= (int)sizeof (*b);
664 if (ml.chunks != 0) {
665 BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks);
666 # ifdef CRYPTO_MDEBUG_ABORT
671 * Make sure that, if we found no leaks, memory-leak debugging itself
672 * does not introduce memory leaks (which might irritate external
673 * debugging tools). (When someone enables leak checking, but does not
674 * call this function, we declare it to be their fault.)
678 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
681 * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses
684 old_mh_mode = mh_mode;
685 mh_mode = CRYPTO_MEM_CHECK_OFF;
690 if (lh_APP_INFO_num_items(amih) == 0) {
691 lh_APP_INFO_free(amih);
696 mh_mode = old_mh_mode;
697 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
699 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
702 # ifndef OPENSSL_NO_STDIO
703 void CRYPTO_mem_leaks_fp(FILE *fp)
710 * Need to turn off memory checking when allocated BIOs ... especially as
711 * we're creating them at a time when we're trying to check we've not
712 * left anything un-free()'d!!
714 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
715 b = BIO_new(BIO_s_file());
716 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
719 BIO_set_fp(b, fp, BIO_NOCLOSE);