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>
119 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
120 # include <execinfo.h>
124 * The state changes to CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE when
125 * the application asks for it (usually after library initialisation for
126 * which no book-keeping is desired). State CRYPTO_MEM_CHECK_ON exists only
127 * temporarily when the library thinks that certain allocations should not be
128 * checked (e.g. the data structures used for memory checking). It is not
129 * suitable as an initial state: the library will unexpectedly enable memory
130 * checking when it executes one of those sections that want to disable
131 * checking temporarily. State CRYPTO_MEM_CHECK_ENABLE without ..._ON makes
132 * no sense whatsoever.
134 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
135 static int mh_mode = CRYPTO_MEM_CHECK_OFF;
138 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
139 static unsigned long order = 0; /* number of memory requests */
142 * For application-defined information (static C-string `info')
143 * to be displayed in memory leak list.
144 * Each thread has its own stack. For applications, there is
145 * OPENSSL_mem_debug_push("...") to push an entry,
146 * OPENSSL_mem_debug_pop() to pop an entry,
148 struct app_mem_info_st {
149 CRYPTO_THREADID threadid;
153 struct app_mem_info_st *next; /* tail of thread's stack */
158 * hash-table with those app_mem_info_st's that are at the
159 * top of their thread's stack (with `thread' as key); access requires
162 static LHASH_OF(APP_INFO) *amih = NULL;
164 /* memory-block description */
170 CRYPTO_THREADID threadid;
174 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
180 static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
181 * key); access requires MALLOC2 lock */
183 /* num_disable > 0 iff mh_mode == CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
184 static unsigned int num_disable = 0;
187 * Valid iff num_disable > 0. CRYPTO_LOCK_MALLOC2 is locked exactly in this
188 * case (by the thread named in disabling_thread).
190 static CRYPTO_THREADID disabling_threadid;
192 static void app_info_free(APP_INFO *inf)
196 if (--(inf->references) <= 0) {
197 app_info_free(inf->next);
203 int CRYPTO_mem_ctrl(int mode)
205 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
210 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
215 case CRYPTO_MEM_CHECK_ON:
216 mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
220 case CRYPTO_MEM_CHECK_OFF:
225 /* switch off temporarily (for library-internal use): */
226 case CRYPTO_MEM_CHECK_DISABLE:
227 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
229 CRYPTO_THREADID_current(&cur);
230 /* see if we don't have the MALLOC2 lock already */
232 || CRYPTO_THREADID_cmp(&disabling_threadid, &cur)) {
234 * Long-time lock CRYPTO_LOCK_MALLOC2 must not be claimed
235 * while we're holding CRYPTO_LOCK_MALLOC, or we'll deadlock
236 * if somebody else holds CRYPTO_LOCK_MALLOC2 (and cannot
237 * release it because we block entry to this function). Give
238 * them a chance, first, and then claim the locks in
239 * appropriate order (long-time lock first).
241 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
243 * Note that after we have waited for CRYPTO_LOCK_MALLOC2 and
244 * CRYPTO_LOCK_MALLOC, we'll still be in the right "case" and
245 * "if" branch because MemCheck_start and MemCheck_stop may
246 * never be used while there are multiple OpenSSL threads.
248 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC2);
249 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
250 mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
251 CRYPTO_THREADID_cpy(&disabling_threadid, &cur);
257 case CRYPTO_MEM_CHECK_ENABLE:
258 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
259 if (num_disable) { /* always true, or something is going wrong */
261 if (num_disable == 0) {
262 mh_mode |= CRYPTO_MEM_CHECK_ENABLE;
263 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
269 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
274 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
276 static int mem_check_on(void)
280 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
282 CRYPTO_THREADID_current(&cur);
283 CRYPTO_r_lock(CRYPTO_LOCK_MALLOC);
285 ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
286 || CRYPTO_THREADID_cmp(&disabling_threadid, &cur);
288 CRYPTO_r_unlock(CRYPTO_LOCK_MALLOC);
293 static int mem_cmp(const MEM *a, const MEM *b)
296 const char *ap = (const char *)a->addr, *bp = (const char *)b->addr;
304 return (const char *)a->addr - (const char *)b->addr;
308 static unsigned long mem_hash(const MEM *a)
312 ret = (size_t)a->addr;
314 ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
318 static int app_info_cmp(const APP_INFO *a, const APP_INFO *b)
320 return CRYPTO_THREADID_cmp(&a->threadid, &b->threadid);
323 static unsigned long app_info_hash(const APP_INFO *a)
327 ret = CRYPTO_THREADID_hash(&a->threadid);
328 /* This is left in as a "who am I to question legacy?" measure */
329 ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
333 /* returns 1 if there was an info to pop, 0 if the stack was empty. */
334 static int pop_info(void)
337 APP_INFO *current = NULL;
340 CRYPTO_THREADID_current(&tmp.threadid);
341 if ((current = lh_APP_INFO_delete(amih, &tmp)) != NULL) {
342 APP_INFO *next = current->next;
346 (void)lh_APP_INFO_insert(amih, next);
348 if (--(current->references) <= 0) {
349 current->next = NULL;
352 OPENSSL_free(current);
360 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
362 APP_INFO *ami, *amim;
365 if (mem_check_on()) {
366 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
368 if ((ami = OPENSSL_malloc(sizeof(*ami))) == NULL)
371 if ((amih = lh_APP_INFO_new(app_info_hash, app_info_cmp)) == NULL) {
377 CRYPTO_THREADID_current(&ami->threadid);
384 if ((amim = lh_APP_INFO_insert(amih, ami)) != NULL)
388 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
394 int CRYPTO_mem_debug_pop(void)
398 if (mem_check_on()) {
399 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
401 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
406 static unsigned long break_order_num = 0;
408 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int before_p,
409 const char *file, int line)
414 switch (before_p & 127) {
421 if (mem_check_on()) {
422 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
423 if ((m = OPENSSL_malloc(sizeof(*m))) == NULL) {
425 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
429 if ((mh = lh_MEM_new(mem_hash, mem_cmp)) == NULL) {
441 CRYPTO_THREADID_current(&m->threadid);
443 if (order == break_order_num) {
448 # if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
449 m->array_siz = backtrace(m->array, OSSL_NELEM(m->array));
451 m->time = time(NULL);
453 CRYPTO_THREADID_current(&tmp.threadid);
456 && (amim = lh_APP_INFO_retrieve(amih, &tmp)) != NULL) {
461 if ((mm = lh_MEM_insert(mh, m)) != NULL) {
462 /* Not good, but don't sweat it */
463 if (mm->app_info != NULL) {
464 mm->app_info->references--;
469 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
476 void CRYPTO_mem_debug_free(void *addr, int before_p)
485 if (mem_check_on() && (mh != NULL)) {
486 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
489 mp = lh_MEM_delete(mh, &m);
491 app_info_free(mp->app_info);
495 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
503 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num,
504 int before_p, const char *file, int line)
516 CRYPTO_mem_debug_malloc(addr2, num, 128 | before_p, file, line);
520 if (mem_check_on()) {
521 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
524 mp = lh_MEM_delete(mh, &m);
528 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
529 mp->array_siz = backtrace(mp->array, OSSL_NELEM(mp->array));
531 (void)lh_MEM_insert(mh, mp);
534 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
541 typedef struct mem_leak_st {
548 static void print_leak(const MEM *m, MEM_LEAK *l)
554 struct tm *lcl = NULL;
557 #define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))
559 /* Is one "leak" the BIO we were given? */
560 if (m->addr == (char *)l->bio) {
565 lcl = localtime(&m->time);
566 BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
567 lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
568 bufp += strlen(bufp);
570 BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
571 m->order, m->file, m->line);
572 bufp += strlen(bufp);
574 BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ",
575 CRYPTO_THREADID_hash(&m->threadid));
576 bufp += strlen(bufp);
578 BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%p\n",
580 bufp += strlen(bufp);
582 BIO_puts(l->bio, buf);
591 CRYPTO_THREADID_cpy(&ti, &amip->threadid);
598 memset(buf, '>', ami_cnt);
599 BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
600 " thread=%lu, file=%s, line=%d, info=\"",
601 CRYPTO_THREADID_hash(&amip->threadid), amip->file,
603 buf_len = strlen(buf);
604 info_len = strlen(amip->info);
605 if (128 - buf_len - 3 < info_len) {
606 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
609 OPENSSL_strlcpy(buf + buf_len, amip->info, sizeof buf - buf_len);
610 buf_len = strlen(buf);
612 BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
614 BIO_puts(l->bio, buf);
618 while (amip && !CRYPTO_THREADID_cmp(&amip->threadid, &ti));
621 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
624 char **strings = backtrace_symbols(m->array, m->array_siz);
626 for (i = 0; i < m->array_siz; i++)
627 fprintf(stderr, "##> %s\n", strings[i]);
633 IMPLEMENT_LHASH_DOALL_ARG_CONST(MEM, MEM_LEAK);
635 int CRYPTO_mem_leaks(BIO *b)
639 if (mh == NULL && amih == NULL)
642 /* Ensure all resources are released */
645 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
652 lh_MEM_doall_MEM_LEAK(mh, print_leak, &ml);
653 /* Don't count the BIO that was passed in as a "leak" */
654 if (ml.seen && ml.chunks >= 1 && ml.bytes >= (int)sizeof (*b)) {
656 ml.bytes -= (int)sizeof (*b);
658 if (ml.chunks != 0) {
659 BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks);
662 * Make sure that, if we found no leaks, memory-leak debugging itself
663 * does not introduce memory leaks (which might irritate external
664 * debugging tools). (When someone enables leak checking, but does not
665 * call this function, we declare it to be their fault.)
669 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
672 * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses
675 old_mh_mode = mh_mode;
676 mh_mode = CRYPTO_MEM_CHECK_OFF;
681 if (lh_APP_INFO_num_items(amih) == 0) {
682 lh_APP_INFO_free(amih);
687 mh_mode = old_mh_mode;
688 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
690 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
691 return ml.chunks == 0 ? 1 : 0;
694 # ifndef OPENSSL_NO_STDIO
695 int CRYPTO_mem_leaks_fp(FILE *fp)
700 if (mh == NULL && amih == NULL)
703 * Need to turn off memory checking when allocated BIOs ... especially as
704 * we're creating them at a time when we're trying to check we've not
705 * left anything un-free()'d!!
707 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
708 b = BIO_new(BIO_s_file());
709 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
712 BIO_set_fp(b, fp, BIO_NOCLOSE);
713 ret = CRYPTO_mem_leaks(b);