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.]
63 #include <openssl/crypto.h>
64 #include <openssl/buffer.h>
65 #include <openssl/bio.h>
66 #include <openssl/lhash.h>
68 static int mh_mode = CRYPTO_MEM_CHECK_OFF;
70 * The state changes to CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE when
71 * the application asks for it (usually after library initialisation for
72 * which no book-keeping is desired). State CRYPTO_MEM_CHECK_ON exists only
73 * temporarily when the library thinks that certain allocations should not be
74 * checked (e.g. the data structures used for memory checking). It is not
75 * suitable as an initial state: the library will unexpectedly enable memory
76 * checking when it executes one of those sections that want to disable
77 * checking temporarily. State CRYPTO_MEM_CHECK_ENABLE without ..._ON makes
78 * no sense whatsoever.
81 static unsigned long order = 0; /* number of memory requests */
82 static LHASH *mh = NULL; /* hash-table of memory requests (address as
83 * key); access requires MALLOC2 lock */
85 typedef struct app_mem_info_st
87 * For application-defined information (static C-string `info')
88 * to be displayed in memory leak list.
89 * Each thread has its own stack. For applications, there is
90 * CRYPTO_push_info("...") to push an entry,
91 * CRYPTO_pop_info() to pop an entry,
92 * CRYPTO_remove_all_info() to pop all entries.
99 struct app_mem_info_st *next; /* tail of thread's stack */
103 static void app_info_free(APP_INFO *);
105 static LHASH *amih = NULL; /* hash-table with those app_mem_info_st's
106 * that are at the top of their thread's
107 * stack (with `thread' as key); access
108 * requires MALLOC2 lock */
110 typedef struct mem_st
111 /* memory-block description */
117 unsigned long thread;
123 static long options = /* extra information to be recorded */
124 #if defined(CRYPTO_MDEBUG_TIME) || defined(CRYPTO_MDEBUG_ALL)
125 V_CRYPTO_MDEBUG_TIME |
127 #if defined(CRYPTO_MDEBUG_THREAD) || defined(CRYPTO_MDEBUG_ALL)
128 V_CRYPTO_MDEBUG_THREAD |
132 static unsigned int num_disable = 0; /* num_disable > 0 iff mh_mode ==
133 * CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
134 static unsigned long disabling_thread = 0; /* Valid iff num_disable > 0.
135 * CRYPTO_LOCK_MALLOC2 is locked
136 * exactly in this case (by the
138 * disabling_thread). */
140 static void app_info_free(APP_INFO *inf)
142 if (--(inf->references) <= 0) {
143 if (inf->next != NULL) {
144 app_info_free(inf->next);
150 int CRYPTO_mem_ctrl(int mode)
154 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
157 * for applications (not to be called while multiple threads use the
160 case CRYPTO_MEM_CHECK_ON: /* aka MemCheck_start() */
161 mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
164 case CRYPTO_MEM_CHECK_OFF: /* aka MemCheck_stop() */
166 num_disable = 0; /* should be true *before* MemCheck_stop is
167 * used, or there'll be a lot of confusion */
170 /* switch off temporarily (for library-internal use): */
171 case CRYPTO_MEM_CHECK_DISABLE: /* aka MemCheck_off() */
172 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
173 /* otherwise we already have the MALLOC2 lock */
174 if (!num_disable || (disabling_thread != CRYPTO_thread_id())) {
176 * Long-time lock CRYPTO_LOCK_MALLOC2 must not be claimed
177 * while we're holding CRYPTO_LOCK_MALLOC, or we'll deadlock
178 * if somebody else holds CRYPTO_LOCK_MALLOC2 (and cannot
179 * release it because we block entry to this function). Give
180 * them a chance, first, and then claim the locks in
181 * appropriate order (long-time lock first).
183 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
185 * Note that after we have waited for CRYPTO_LOCK_MALLOC2 and
186 * CRYPTO_LOCK_MALLOC, we'll still be in the right "case" and
187 * "if" branch because MemCheck_start and MemCheck_stop may
188 * never be used while there are multiple OpenSSL threads.
190 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC2);
191 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
192 mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
193 disabling_thread = CRYPTO_thread_id();
198 case CRYPTO_MEM_CHECK_ENABLE: /* aka MemCheck_on() */
199 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
200 if (num_disable) { /* always true, or something is going wrong */
202 if (num_disable == 0) {
203 mh_mode |= CRYPTO_MEM_CHECK_ENABLE;
204 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
213 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
217 int CRYPTO_is_mem_check_on(void)
221 if (mh_mode & CRYPTO_MEM_CHECK_ON) {
222 CRYPTO_r_lock(CRYPTO_LOCK_MALLOC);
224 ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
225 || (disabling_thread != CRYPTO_thread_id());
227 CRYPTO_r_unlock(CRYPTO_LOCK_MALLOC);
232 void CRYPTO_dbg_set_options(long bits)
237 long CRYPTO_dbg_get_options(void)
242 /* static int mem_cmp(MEM *a, MEM *b) */
243 static int mem_cmp(const void *a_void, const void *b_void)
246 const char *a = (const char *)((const MEM *)a_void)->addr,
247 *b = (const char *)((const MEM *)b_void)->addr;
255 return ((const char *)((const MEM *)a_void)->addr
256 - (const char *)((const MEM *)b_void)->addr);
260 /* static unsigned long mem_hash(MEM *a) */
261 static unsigned long mem_hash(const void *a_void)
265 ret = (unsigned long)((const MEM *)a_void)->addr;
267 ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
271 /* static int app_info_cmp(APP_INFO *a, APP_INFO *b) */
272 static int app_info_cmp(const void *a_void, const void *b_void)
274 return (((const APP_INFO *)a_void)->thread
275 != ((const APP_INFO *)b_void)->thread);
278 /* static unsigned long app_info_hash(APP_INFO *a) */
279 static unsigned long app_info_hash(const void *a_void)
283 ret = (unsigned long)((const APP_INFO *)a_void)->thread;
285 ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
289 static APP_INFO *pop_info(void)
292 APP_INFO *ret = NULL;
295 tmp.thread = CRYPTO_thread_id();
296 if ((ret = (APP_INFO *)lh_delete(amih, &tmp)) != NULL) {
297 APP_INFO *next = ret->next;
301 lh_insert(amih, (char *)next);
303 #ifdef LEVITTE_DEBUG_MEM
304 if (ret->thread != tmp.thread) {
306 "pop_info(): deleted info has other thread ID (%lu) than the current thread (%lu)!!!!\n",
307 ret->thread, tmp.thread);
311 if (--(ret->references) <= 0) {
322 int CRYPTO_dbg_push_info(const char *info, const char *file, int line)
324 APP_INFO *ami, *amim;
327 if (is_MemCheck_on()) {
328 MemCheck_off(); /* obtain MALLOC2 lock */
330 if ((ami = (APP_INFO *)OPENSSL_malloc(sizeof(APP_INFO))) == NULL) {
335 if ((amih = lh_new(app_info_hash, app_info_cmp)) == NULL) {
342 ami->thread = CRYPTO_thread_id();
349 if ((amim = (APP_INFO *)lh_insert(amih, (char *)ami)) != NULL) {
350 #ifdef LEVITTE_DEBUG_MEM
351 if (ami->thread != amim->thread) {
353 "CRYPTO_push_info(): previous info has other thread ID (%lu) than the current thread (%lu)!!!!\n",
354 amim->thread, ami->thread);
361 MemCheck_on(); /* release MALLOC2 lock */
367 int CRYPTO_dbg_pop_info(void)
371 if (is_MemCheck_on()) { /* _must_ be true, or something went severely
373 MemCheck_off(); /* obtain MALLOC2 lock */
375 ret = (pop_info() != NULL);
377 MemCheck_on(); /* release MALLOC2 lock */
382 int CRYPTO_dbg_remove_all_info(void)
386 if (is_MemCheck_on()) { /* _must_ be true */
387 MemCheck_off(); /* obtain MALLOC2 lock */
389 while (pop_info() != NULL)
392 MemCheck_on(); /* release MALLOC2 lock */
397 static unsigned long break_order_num = 0;
398 void CRYPTO_dbg_malloc(void *addr, int num, const char *file, int line,
404 switch (before_p & 127) {
411 if (is_MemCheck_on()) {
412 MemCheck_off(); /* make sure we hold MALLOC2 lock */
413 if ((m = (MEM *)OPENSSL_malloc(sizeof(MEM))) == NULL) {
415 MemCheck_on(); /* release MALLOC2 lock if num_disabled drops
420 if ((mh = lh_new(mem_hash, mem_cmp)) == NULL) {
432 if (options & V_CRYPTO_MDEBUG_THREAD)
433 m->thread = CRYPTO_thread_id();
437 if (order == break_order_num) {
442 #ifdef LEVITTE_DEBUG_MEM
443 fprintf(stderr, "LEVITTE_DEBUG_MEM: [%5d] %c 0x%p (%d)\n",
444 m->order, (before_p & 128) ? '*' : '+', m->addr, m->num);
446 if (options & V_CRYPTO_MDEBUG_TIME)
447 m->time = time(NULL);
451 tmp.thread = CRYPTO_thread_id();
455 (APP_INFO *)lh_retrieve(amih, (char *)&tmp)) != NULL) {
460 if ((mm = (MEM *)lh_insert(mh, (char *)m)) != NULL) {
461 /* Not good, but don't sweat it */
462 if (mm->app_info != NULL) {
463 mm->app_info->references--;
468 MemCheck_on(); /* release MALLOC2 lock if num_disabled drops
476 void CRYPTO_dbg_free(void *addr, int before_p)
485 if (is_MemCheck_on() && (mh != NULL)) {
486 MemCheck_off(); /* make sure we hold MALLOC2 lock */
489 mp = (MEM *)lh_delete(mh, (char *)&m);
491 #ifdef LEVITTE_DEBUG_MEM
492 fprintf(stderr, "LEVITTE_DEBUG_MEM: [%5d] - 0x%p (%d)\n",
493 mp->order, mp->addr, mp->num);
495 if (mp->app_info != NULL)
496 app_info_free(mp->app_info);
500 MemCheck_on(); /* release MALLOC2 lock if num_disabled drops
509 void CRYPTO_dbg_realloc(void *addr1, void *addr2, int num,
510 const char *file, int line, int before_p)
514 #ifdef LEVITTE_DEBUG_MEM
516 "LEVITTE_DEBUG_MEM: --> CRYPTO_dbg_malloc(addr1 = %p, addr2 = %p, num = %d, file = \"%s\", line = %d, before_p = %d)\n",
517 addr1, addr2, num, file, line, before_p);
528 CRYPTO_dbg_malloc(addr2, num, file, line, 128 | before_p);
532 if (is_MemCheck_on()) {
533 MemCheck_off(); /* make sure we hold MALLOC2 lock */
536 mp = (MEM *)lh_delete(mh, (char *)&m);
538 #ifdef LEVITTE_DEBUG_MEM
540 "LEVITTE_DEBUG_MEM: [%5d] * 0x%p (%d) -> 0x%p (%d)\n",
541 mp->order, mp->addr, mp->num, addr2, num);
545 lh_insert(mh, (char *)mp);
548 MemCheck_on(); /* release MALLOC2 lock if num_disabled drops
556 typedef struct mem_leak_st {
562 static void print_leak(const MEM *m, MEM_LEAK *l)
568 struct tm *lcl = NULL;
571 #define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))
573 if (m->addr == (char *)l->bio)
576 if (options & V_CRYPTO_MDEBUG_TIME) {
577 lcl = localtime(&m->time);
579 BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
580 lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
581 bufp += strlen(bufp);
584 BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
585 m->order, m->file, m->line);
586 bufp += strlen(bufp);
588 if (options & V_CRYPTO_MDEBUG_THREAD) {
589 BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ", m->thread);
590 bufp += strlen(bufp);
593 BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%08lX\n",
594 m->num, (unsigned long)m->addr);
595 bufp += strlen(bufp);
597 BIO_puts(l->bio, buf);
613 memset(buf, '>', ami_cnt);
614 BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
615 " thread=%lu, file=%s, line=%d, info=\"",
616 amip->thread, amip->file, amip->line);
617 buf_len = strlen(buf);
618 info_len = strlen(amip->info);
619 if (128 - buf_len - 3 < info_len) {
620 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
623 BUF_strlcpy(buf + buf_len, amip->info, sizeof buf - buf_len);
624 buf_len = strlen(buf);
626 BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
628 BIO_puts(l->bio, buf);
632 while (amip && amip->thread == ti);
634 #ifdef LEVITTE_DEBUG_MEM
636 fprintf(stderr, "Thread switch detected in backtrace!!!!\n");
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 MemCheck_off(); /* obtain MALLOC2 lock */
657 lh_doall_arg(mh, LHASH_DOALL_ARG_FN(print_leak), (char *)&ml);
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.) XXX This
666 * should be in CRYPTO_mem_leaks_cb, and CRYPTO_mem_leaks should be
667 * implemented by using CRYPTO_mem_leaks_cb. (Also their should be a
668 * variant of lh_doall_arg that takes a function pointer instead of a
669 * void *; this would obviate the ugly and illegal void_fn_to_char
670 * kludge in CRYPTO_mem_leaks_cb. Otherwise the code police will come
675 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
678 * avoid deadlock when lh_free() uses CRYPTO_dbg_free(), which uses
679 * CRYPTO_is_mem_check_on
681 old_mh_mode = mh_mode;
682 mh_mode = CRYPTO_MEM_CHECK_OFF;
689 if (lh_num_items(amih) == 0) {
695 mh_mode = old_mh_mode;
696 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
698 MemCheck_on(); /* release MALLOC2 lock */
701 #ifndef OPENSSL_NO_FP_API
702 void CRYPTO_mem_leaks_fp(FILE *fp)
709 * Need to turn off memory checking when allocated BIOs ... especially as
710 * we're creating them at a time when we're trying to check we've not
711 * left anything un-free()'d!!
714 b = BIO_new(BIO_s_file());
718 BIO_set_fp(b, fp, BIO_NOCLOSE);
725 * FIXME: We really don't allow much to the callback. For example, it has no
726 * chance of reaching the info stack for the item it processes. Should it
727 * really be this way? -- Richard Levitte
730 * NB: The prototypes have been typedef'd to CRYPTO_MEM_LEAK_CB inside
731 * crypto.h If this code is restructured, remove the callback type if it is
732 * no longer needed. -- Geoff Thorpe
734 static void cb_leak(const MEM *m, CRYPTO_MEM_LEAK_CB **cb)
736 (**cb) (m->order, m->file, m->line, m->num, m->addr);
739 static IMPLEMENT_LHASH_DOALL_ARG_FN(cb_leak, const MEM *,
740 CRYPTO_MEM_LEAK_CB **)
742 void CRYPTO_mem_leaks_cb(CRYPTO_MEM_LEAK_CB *cb)
746 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC2);
747 lh_doall_arg(mh, LHASH_DOALL_ARG_FN(cb_leak), &cb);
748 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
751 void CRYPTO_malloc_debug_init(void)
753 CRYPTO_set_mem_debug_functions(CRYPTO_dbg_malloc,
756 CRYPTO_dbg_set_options,
757 CRYPTO_dbg_get_options);
758 CRYPTO_set_mem_info_functions(CRYPTO_dbg_push_info,
760 CRYPTO_dbg_remove_all_info);
763 char *CRYPTO_strdup(const char *str, const char *file, int line)
765 char *ret = CRYPTO_malloc(strlen(str) + 1, file, line);