mem_dbg.c 23.0 KB
Newer Older
1
/* crypto/mem_dbg.c */
R
Richard Levitte 已提交
2 3
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
4
 *
R
Richard Levitte 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
23 24 25
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
R
Richard Levitte 已提交
26 27
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
28
 * 2. Redistributions in binary form must reproduce the above copyright
R
Richard Levitte 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
57
 */
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
/* ====================================================================
 * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    openssl-core@openssl.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */
111 112 113 114

#include <stdio.h>
#include <stdlib.h>
#include <time.h>	
115
#include "cryptlib.h"
116 117 118 119 120
#include <openssl/crypto.h>
#include <openssl/buffer.h>
#include <openssl/bio.h>
#include <openssl/lhash.h>

121 122 123 124 125 126
static int mh_mode=CRYPTO_MEM_CHECK_OFF;
/* The state changes to CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE
 * when the application asks for it (usually after library initialisation
 * for which no book-keeping is desired).
 *
 * State CRYPTO_MEM_CHECK_ON exists only temporarily when the library
127 128 129 130 131 132 133 134 135
 * thinks that certain allocations should not be checked (e.g. the data
 * structures used for memory checking).  It is not suitable as an initial
 * state: the library will unexpectedly enable memory checking when it
 * executes one of those sections that want to disable checking
 * temporarily.
 *
 * State CRYPTO_MEM_CHECK_ENABLE without ..._ON makes no sense whatsoever.
 */

136
static unsigned long order = 0; /* number of memory requests */
B
Ben Laurie 已提交
137 138 139 140 141

DECLARE_LHASH_OF(MEM);
static LHASH_OF(MEM) *mh=NULL; /* hash-table of memory requests
				* (address as key); access requires
				* MALLOC2 lock */
142 143 144


typedef struct app_mem_info_st
145 146 147
/* For application-defined information (static C-string `info')
 * to be displayed in memory leak list.
 * Each thread has its own stack.  For applications, there is
B
Rename  
Bodo Möller 已提交
148 149 150
 *   CRYPTO_push_info("...")     to push an entry,
 *   CRYPTO_pop_info()           to pop an entry,
 *   CRYPTO_remove_all_info()    to pop all entries.
151
 */
152
	{
153
	CRYPTO_THREADID threadid;
154 155 156
	const char *file;
	int line;
	const char *info;
157
	struct app_mem_info_st *next; /* tail of thread's stack */
158 159 160
	int references;
	} APP_INFO;

161 162
static void app_info_free(APP_INFO *);

B
Ben Laurie 已提交
163 164 165 166 167 168 169
DECLARE_LHASH_OF(APP_INFO);
static LHASH_OF(APP_INFO) *amih=NULL; /* hash-table with those
				       * app_mem_info_st's that are at
				       * the top of their thread's
				       * stack (with `thread' as key);
				       * access requires MALLOC2
				       * lock */
170 171

typedef struct mem_st
172
/* memory-block description */
173
	{
174
	void *addr;
175 176 177
	int num;
	const char *file;
	int line;
178
	CRYPTO_THREADID threadid;
179 180 181 182 183
	unsigned long order;
	time_t time;
	APP_INFO *app_info;
	} MEM;

184 185 186
static long options =             /* extra information to be recorded */
#if defined(CRYPTO_MDEBUG_TIME) || defined(CRYPTO_MDEBUG_ALL)
	V_CRYPTO_MDEBUG_TIME |
187
#endif
188 189
#if defined(CRYPTO_MDEBUG_THREAD) || defined(CRYPTO_MDEBUG_ALL)
	V_CRYPTO_MDEBUG_THREAD |
190
#endif
191
	0;
192

193

194 195 196 197
static unsigned int num_disable = 0; /* num_disable > 0
                                      *     iff
                                      * mh_mode == CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE)
                                      */
198

199 200
/* Valid iff num_disable > 0.  CRYPTO_LOCK_MALLOC2 is locked exactly in this
 * case (by the thread named in disabling_thread).
201
 */
202
static CRYPTO_THREADID disabling_threadid;
203

204 205 206 207 208 209 210 211 212 213 214 215
static void app_info_free(APP_INFO *inf)
	{
	if (--(inf->references) <= 0)
		{
		if (inf->next != NULL)
			{
			app_info_free(inf->next);
			}
		OPENSSL_free(inf);
		}
	}

216 217 218 219 220 221 222
int CRYPTO_mem_ctrl(int mode)
	{
	int ret=mh_mode;

	CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
	switch (mode)
		{
223 224
	/* for applications (not to be called while multiple threads
	 * use the library): */
225 226
	case CRYPTO_MEM_CHECK_ON: /* aka MemCheck_start() */
		mh_mode = CRYPTO_MEM_CHECK_ON|CRYPTO_MEM_CHECK_ENABLE;
227
		num_disable = 0;
228 229 230
		break;
	case CRYPTO_MEM_CHECK_OFF: /* aka MemCheck_stop() */
		mh_mode = 0;
231 232
		num_disable = 0; /* should be true *before* MemCheck_stop is used,
		                    or there'll be a lot of confusion */
233 234 235 236 237 238
		break;

	/* switch off temporarily (for library-internal use): */
	case CRYPTO_MEM_CHECK_DISABLE: /* aka MemCheck_off() */
		if (mh_mode & CRYPTO_MEM_CHECK_ON)
			{
239 240 241
			CRYPTO_THREADID cur;
			CRYPTO_THREADID_current(&cur);
			if (!num_disable || CRYPTO_THREADID_cmp(&disabling_threadid, &cur)) /* otherwise we already have the MALLOC2 lock */
242 243 244
				{
				/* Long-time lock CRYPTO_LOCK_MALLOC2 must not be claimed while
				 * we're holding CRYPTO_LOCK_MALLOC, or we'll deadlock if
245 246
				 * somebody else holds CRYPTO_LOCK_MALLOC2 (and cannot release
				 * it because we block entry to this function).
247 248 249 250 251 252 253 254 255 256 257
				 * Give them a chance, first, and then claim the locks in
				 * appropriate order (long-time lock first).
				 */
				CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
				/* Note that after we have waited for CRYPTO_LOCK_MALLOC2
				 * and CRYPTO_LOCK_MALLOC, we'll still be in the right
				 * "case" and "if" branch because MemCheck_start and
				 * MemCheck_stop may never be used while there are multiple
				 * OpenSSL threads. */
				CRYPTO_w_lock(CRYPTO_LOCK_MALLOC2);
				CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
258
				mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
259
				CRYPTO_THREADID_cpy(&disabling_threadid, &cur);
260
				}
261
			num_disable++;
262 263 264 265 266
			}
		break;
	case CRYPTO_MEM_CHECK_ENABLE: /* aka MemCheck_on() */
		if (mh_mode & CRYPTO_MEM_CHECK_ON)
			{
267
			if (num_disable) /* always true, or something is going wrong */
268
				{
269 270 271 272 273 274
				num_disable--;
				if (num_disable == 0)
					{
					mh_mode|=CRYPTO_MEM_CHECK_ENABLE;
					CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
					}
275 276 277 278 279 280 281 282 283 284 285
				}
			}
		break;

	default:
		break;
		}
	CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
	return(ret);
	}

286
int CRYPTO_is_mem_check_on(void)
287 288 289 290 291
	{
	int ret = 0;

	if (mh_mode & CRYPTO_MEM_CHECK_ON)
		{
292 293
		CRYPTO_THREADID cur;
		CRYPTO_THREADID_current(&cur);
294
		CRYPTO_r_lock(CRYPTO_LOCK_MALLOC);
295

296
		ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
297
		        || CRYPTO_THREADID_cmp(&disabling_threadid, &cur);
298

299
		CRYPTO_r_unlock(CRYPTO_LOCK_MALLOC);
300 301 302 303 304
		}
	return(ret);
	}	


305
void CRYPTO_dbg_set_options(long bits)
306 307 308 309
	{
	options = bits;
	}

310
long CRYPTO_dbg_get_options(void)
311 312 313 314
	{
	return options;
	}

B
Ben Laurie 已提交
315
static int mem_cmp(const MEM *a, const MEM *b)
316
	{
317
#ifdef _WIN64
318 319 320 321
	const char *ap=(const char *)a->addr,
		   *bp=(const char *)b->addr;
	if (ap==bp)	return 0;
	else if (ap>bp)	return 1;
322 323
	else		return -1;
#else
B
Ben Laurie 已提交
324
	return (const char *)a->addr - (const char *)b->addr;
325
#endif
326
	}
B
Ben Laurie 已提交
327
static IMPLEMENT_LHASH_COMP_FN(mem, MEM)
328

B
Ben Laurie 已提交
329
static unsigned long mem_hash(const MEM *a)
330 331 332
	{
	unsigned long ret;

B
Ben Laurie 已提交
333
	ret=(unsigned long)a->addr;
334 335 336 337

	ret=ret*17851+(ret>>14)*7+(ret>>4)*251;
	return(ret);
	}
B
Ben Laurie 已提交
338
static IMPLEMENT_LHASH_HASH_FN(mem, MEM)
339

340
/* static int app_info_cmp(APP_INFO *a, APP_INFO *b) */
341
static int app_info_cmp(const void *a_void, const void *b_void)
342
	{
343 344
	return CRYPTO_THREADID_cmp(&((const APP_INFO *)a_void)->threadid,
				&((const APP_INFO *)b_void)->threadid);
345
	}
B
Ben Laurie 已提交
346
static IMPLEMENT_LHASH_COMP_FN(app_info, APP_INFO)
347

B
Ben Laurie 已提交
348
static unsigned long app_info_hash(const APP_INFO *a)
349 350
	{
	unsigned long ret;
351

352 353
	ret = CRYPTO_THREADID_hash(&a->threadid);
	/* This is left in as a "who am I to question legacy?" measure */
354 355 356
	ret=ret*17851+(ret>>14)*7+(ret>>4)*251;
	return(ret);
	}
B
Ben Laurie 已提交
357
static IMPLEMENT_LHASH_HASH_FN(app_info, APP_INFO)
358

U
Ulf Möller 已提交
359
static APP_INFO *pop_info(void)
360 361 362 363 364 365
	{
	APP_INFO tmp;
	APP_INFO *ret = NULL;

	if (amih != NULL)
		{
366
		CRYPTO_THREADID_current(&tmp.threadid);
B
Ben Laurie 已提交
367
		if ((ret=lh_APP_INFO_delete(amih,&tmp)) != NULL)
368 369 370 371 372 373
			{
			APP_INFO *next=ret->next;

			if (next != NULL)
				{
				next->references++;
374
				(void)lh_APP_INFO_insert(amih,next);
375
				}
376
#ifdef LEVITTE_DEBUG_MEM
377
			if (CRYPTO_THREADID_cmp(&ret->threadid, &tmp.threadid))
378
				{
379 380 381
				fprintf(stderr, "pop_info(): deleted info has other thread ID (%lu) than the current thread (%lu)!!!!\n",
					CRYPTO_THREADID_hash(&ret->threadid),
					CRYPTO_THREADID_hash(&tmp.threadid));
382 383 384 385 386 387 388 389
				abort();
				}
#endif
			if (--(ret->references) <= 0)
				{
				ret->next = NULL;
				if (next != NULL)
					next->references--;
390
				OPENSSL_free(ret);
391 392 393 394 395 396
				}
			}
		}
	return(ret);
	}

B
Rename  
Bodo Möller 已提交
397
int CRYPTO_push_info_(const char *info, const char *file, int line)
398 399 400 401 402 403
	{
	APP_INFO *ami, *amim;
	int ret=0;

	if (is_MemCheck_on())
		{
404
		MemCheck_off(); /* obtain MALLOC2 lock */
405

406
		if ((ami = (APP_INFO *)OPENSSL_malloc(sizeof(APP_INFO))) == NULL)
407 408 409 410 411 412
			{
			ret=0;
			goto err;
			}
		if (amih == NULL)
			{
B
Ben Laurie 已提交
413
			if ((amih=lh_APP_INFO_new()) == NULL)
414
				{
415
				OPENSSL_free(ami);
416 417 418 419 420
				ret=0;
				goto err;
				}
			}

421
		CRYPTO_THREADID_current(&ami->threadid);
422 423 424 425 426 427
		ami->file=file;
		ami->line=line;
		ami->info=info;
		ami->references=1;
		ami->next=NULL;

B
Ben Laurie 已提交
428
		if ((amim=lh_APP_INFO_insert(amih,ami)) != NULL)
429
			{
430
#ifdef LEVITTE_DEBUG_MEM
431
			if (CRYPTO_THREADID_cmp(&ami->threadid, &amim->threadid))
432
				{
433 434 435
				fprintf(stderr, "CRYPTO_push_info(): previous info has other thread ID (%lu) than the current thread (%lu)!!!!\n",
					CRYPTO_THREADID_hash(&amim->threadid),
					CRYPTO_THREADID_hash(&ami->threadid));
436 437 438 439 440 441
				abort();
				}
#endif
			ami->next=amim;
			}
 err:
442
		MemCheck_on(); /* release MALLOC2 lock */
443 444 445 446 447
		}

	return(ret);
	}

B
Rename  
Bodo Möller 已提交
448
int CRYPTO_pop_info(void)
449 450 451
	{
	int ret=0;

452
	if (is_MemCheck_on()) /* _must_ be true, or something went severely wrong */
453
		{
454
		MemCheck_off(); /* obtain MALLOC2 lock */
455

B
Rename  
Bodo Möller 已提交
456
		ret=(pop_info() != NULL);
457

458
		MemCheck_on(); /* release MALLOC2 lock */
459 460 461 462 463 464 465 466
		}
	return(ret);
	}

int CRYPTO_remove_all_info(void)
	{
	int ret=0;

467
	if (is_MemCheck_on()) /* _must_ be true */
468
		{
469
		MemCheck_off(); /* obtain MALLOC2 lock */
470

B
Rename  
Bodo Möller 已提交
471
		while(pop_info() != NULL)
472 473
			ret++;

474
		MemCheck_on(); /* release MALLOC2 lock */
475 476 477 478 479 480
		}
	return(ret);
	}


static unsigned long break_order_num=0;
481
void CRYPTO_dbg_malloc(void *addr, int num, const char *file, int line,
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
	int before_p)
	{
	MEM *m,*mm;
	APP_INFO tmp,*amim;

	switch(before_p & 127)
		{
	case 0:
		break;
	case 1:
		if (addr == NULL)
			break;

		if (is_MemCheck_on())
			{
497
			MemCheck_off(); /* make sure we hold MALLOC2 lock */
498
			if ((m=(MEM *)OPENSSL_malloc(sizeof(MEM))) == NULL)
499
				{
500
				OPENSSL_free(addr);
501 502
				MemCheck_on(); /* release MALLOC2 lock
				                * if num_disabled drops to 0 */
503 504 505 506
				return;
				}
			if (mh == NULL)
				{
B
Ben Laurie 已提交
507
				if ((mh=lh_MEM_new()) == NULL)
508
					{
509 510
					OPENSSL_free(addr);
					OPENSSL_free(m);
511 512 513 514 515 516 517 518 519
					addr=NULL;
					goto err;
					}
				}

			m->addr=addr;
			m->file=file;
			m->line=line;
			m->num=num;
520
			if (options & V_CRYPTO_MDEBUG_THREAD)
521
				CRYPTO_THREADID_current(&m->threadid);
522
			else
523
				memset(&m->threadid, 0, sizeof(m->threadid));
524 525 526 527 528 529 530

			if (order == break_order_num)
				{
				/* BREAK HERE */
				m->order=order;
				}
			m->order=order++;
531
#ifdef LEVITTE_DEBUG_MEM
532
			fprintf(stderr, "LEVITTE_DEBUG_MEM: [%5ld] %c 0x%p (%d)\n",
533 534 535 536 537 538 539 540 541
				m->order,
				(before_p & 128) ? '*' : '+',
				m->addr, m->num);
#endif
			if (options & V_CRYPTO_MDEBUG_TIME)
				m->time=time(NULL);
			else
				m->time=0;

542
			CRYPTO_THREADID_current(&tmp.threadid);
543 544
			m->app_info=NULL;
			if (amih != NULL
B
Ben Laurie 已提交
545
			    && (amim=lh_APP_INFO_retrieve(amih,&tmp)) != NULL)
546 547 548 549 550
				{
				m->app_info = amim;
				amim->references++;
				}

B
Ben Laurie 已提交
551
			if ((mm=lh_MEM_insert(mh, m)) != NULL)
552 553 554 555 556 557
				{
				/* Not good, but don't sweat it */
				if (mm->app_info != NULL)
					{
					mm->app_info->references--;
					}
558
				OPENSSL_free(mm);
559 560
				}
		err:
561 562
			MemCheck_on(); /* release MALLOC2 lock
			                * if num_disabled drops to 0 */
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
			}
		break;
		}
	return;
	}

void CRYPTO_dbg_free(void *addr, int before_p)
	{
	MEM m,*mp;

	switch(before_p)
		{
	case 0:
		if (addr == NULL)
			break;

		if (is_MemCheck_on() && (mh != NULL))
			{
581
			MemCheck_off(); /* make sure we hold MALLOC2 lock */
582 583

			m.addr=addr;
B
Ben Laurie 已提交
584
			mp=lh_MEM_delete(mh,&m);
585 586
			if (mp != NULL)
				{
587
#ifdef LEVITTE_DEBUG_MEM
588
			fprintf(stderr, "LEVITTE_DEBUG_MEM: [%5ld] - 0x%p (%d)\n",
589 590 591
				mp->order, mp->addr, mp->num);
#endif
				if (mp->app_info != NULL)
592
					app_info_free(mp->app_info);
593
				OPENSSL_free(mp);
594 595
				}

596 597
			MemCheck_on(); /* release MALLOC2 lock
			                * if num_disabled drops to 0 */
598 599 600 601 602 603 604
			}
		break;
	case 1:
		break;
		}
	}

605 606
void CRYPTO_dbg_realloc(void *addr1, void *addr2, int num,
	const char *file, int line, int before_p)
607 608 609
	{
	MEM m,*mp;

610 611
#ifdef LEVITTE_DEBUG_MEM
	fprintf(stderr, "LEVITTE_DEBUG_MEM: --> CRYPTO_dbg_malloc(addr1 = %p, addr2 = %p, num = %d, file = \"%s\", line = %d, before_p = %d)\n",
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
		addr1, addr2, num, file, line, before_p);
#endif

	switch(before_p)
		{
	case 0:
		break;
	case 1:
		if (addr2 == NULL)
			break;

		if (addr1 == NULL)
			{
			CRYPTO_dbg_malloc(addr2, num, file, line, 128 | before_p);
			break;
			}

		if (is_MemCheck_on())
			{
631
			MemCheck_off(); /* make sure we hold MALLOC2 lock */
632 633

			m.addr=addr1;
B
Ben Laurie 已提交
634
			mp=lh_MEM_delete(mh,&m);
635 636
			if (mp != NULL)
				{
637
#ifdef LEVITTE_DEBUG_MEM
638
				fprintf(stderr, "LEVITTE_DEBUG_MEM: [%5ld] * 0x%p (%d) -> 0x%p (%d)\n",
639 640 641 642 643 644
					mp->order,
					mp->addr, mp->num,
					addr2, num);
#endif
				mp->addr=addr2;
				mp->num=num;
645
				(void)lh_MEM_insert(mh,mp);
646 647
				}

648 649
			MemCheck_on(); /* release MALLOC2 lock
			                * if num_disabled drops to 0 */
650 651 652 653 654 655 656 657 658 659 660 661 662 663
			}
		break;
		}
	return;
	}


typedef struct mem_leak_st
	{
	BIO *bio;
	int chunks;
	long bytes;
	} MEM_LEAK;

B
Ben Laurie 已提交
664
static void print_leak_doall_arg(const MEM *m, MEM_LEAK *l)
665 666 667 668
	{
	char buf[1024];
	char *bufp = buf;
	APP_INFO *amip;
669
	int ami_cnt;
670
	struct tm *lcl = NULL;
671
	CRYPTO_THREADID ti;
672

673 674
#define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))

675 676 677 678 679 680 681
	if(m->addr == (char *)l->bio)
	    return;

	if (options & V_CRYPTO_MDEBUG_TIME)
		{
		lcl = localtime(&m->time);
	
682
		BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
683 684 685 686
			lcl->tm_hour,lcl->tm_min,lcl->tm_sec);
		bufp += strlen(bufp);
		}

687
	BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
688 689 690 691 692
		m->order,m->file,m->line);
	bufp += strlen(bufp);

	if (options & V_CRYPTO_MDEBUG_THREAD)
		{
693 694
		BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ",
			CRYPTO_THREADID_hash(&m->threadid));
695 696 697
		bufp += strlen(bufp);
		}

698
	BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%08lX\n",
699 700 701 702 703 704 705 706 707 708
		m->num,(unsigned long)m->addr);
	bufp += strlen(bufp);

	BIO_puts(l->bio,buf);
	
	l->chunks++;
	l->bytes+=m->num;

	amip=m->app_info;
	ami_cnt=0;
709 710
	if (!amip)
		return;
711 712
	CRYPTO_THREADID_cpy(&ti, &amip->threadid);

713
	do
714
		{
715
		int buf_len;
716 717 718 719
		int info_len;

		ami_cnt++;
		memset(buf,'>',ami_cnt);
720
		BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
721 722 723
			" thread=%lu, file=%s, line=%d, info=\"",
			CRYPTO_THREADID_hash(&amip->threadid), amip->file,
			amip->line);
724 725 726 727 728 729 730 731 732
		buf_len=strlen(buf);
		info_len=strlen(amip->info);
		if (128 - buf_len - 3 < info_len)
			{
			memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
			buf_len = 128 - 3;
			}
		else
			{
733 734
			BUF_strlcpy(buf + buf_len, amip->info,
				    sizeof buf - buf_len);
735 736
			buf_len = strlen(buf);
			}
737
		BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
738 739 740 741 742
		
		BIO_puts(l->bio,buf);

		amip = amip->next;
		}
743
	while(amip && !CRYPTO_THREADID_cmp(&amip->threadid, &ti));
744

745
#ifdef LEVITTE_DEBUG_MEM
746 747
	if (amip)
		{
R
Typo...  
Richard Levitte 已提交
748
		fprintf(stderr, "Thread switch detected in backtrace!!!!\n");
749 750 751 752 753
		abort();
		}
#endif
	}

B
Ben Laurie 已提交
754
static IMPLEMENT_LHASH_DOALL_ARG_FN(print_leak, const MEM, MEM_LEAK)
755

756 757 758 759
void CRYPTO_mem_leaks(BIO *b)
	{
	MEM_LEAK ml;

760 761
	if (mh == NULL && amih == NULL)
		return;
762 763 764

	MemCheck_off(); /* obtain MALLOC2 lock */

765 766 767
	ml.bio=b;
	ml.bytes=0;
	ml.chunks=0;
768
	if (mh != NULL)
B
Ben Laurie 已提交
769 770
		lh_MEM_doall_arg(mh, LHASH_DOALL_ARG_FN(print_leak), MEM_LEAK,
				 &ml);
771 772
	if (ml.chunks != 0)
		{
773 774
		BIO_printf(b,"%ld bytes leaked in %d chunks\n",
			   ml.bytes,ml.chunks);
775 776 777
#ifdef CRYPTO_MDEBUG_ABORT
		abort();
#endif
778
		}
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
	else
		{
		/* Make sure that, if we found no leaks, memory-leak debugging itself
		 * does not introduce memory leaks (which might irritate
		 * external debugging tools).
		 * (When someone enables leak checking, but does not call
		 * this function, we declare it to be their fault.)
		 *
		 * XXX    This should be in CRYPTO_mem_leaks_cb,
		 * and CRYPTO_mem_leaks should be implemented by
		 * using CRYPTO_mem_leaks_cb.
		 * (Also their should be a variant of lh_doall_arg
		 * that takes a function pointer instead of a void *;
		 * this would obviate the ugly and illegal
		 * void_fn_to_char kludge in CRYPTO_mem_leaks_cb.
		 * Otherwise the code police will come and get us.)
		 */
B
Bodo Möller 已提交
796 797
		int old_mh_mode;

798
		CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
B
Bodo Möller 已提交
799 800 801 802 803 804

		/* avoid deadlock when lh_free() uses CRYPTO_dbg_free(),
		 * which uses CRYPTO_is_mem_check_on */
		old_mh_mode = mh_mode;
		mh_mode = CRYPTO_MEM_CHECK_OFF;

805 806
		if (mh != NULL)
			{
B
Ben Laurie 已提交
807
			lh_MEM_free(mh);
808 809 810 811
			mh = NULL;
			}
		if (amih != NULL)
			{
B
Ben Laurie 已提交
812
			if (lh_APP_INFO_num_items(amih) == 0) 
813
				{
B
Ben Laurie 已提交
814
				lh_APP_INFO_free(amih);
815 816 817
				amih = NULL;
				}
			}
B
Bodo Möller 已提交
818 819

		mh_mode = old_mh_mode;
820 821
		CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
		}
822
	MemCheck_on(); /* release MALLOC2 lock */
823 824
	}

825
#ifndef OPENSSL_NO_FP_API
826 827 828 829 830
void CRYPTO_mem_leaks_fp(FILE *fp)
	{
	BIO *b;

	if (mh == NULL) return;
831 832 833 834
	/* Need to turn off memory checking when allocated BIOs ... especially
	 * as we're creating them at a time when we're trying to check we've not
	 * left anything un-free()'d!! */
	MemCheck_off();
835
	b = BIO_new(BIO_s_file());
836
	MemCheck_on();
837
	if(!b) return;
838 839 840 841 842 843
	BIO_set_fp(b,fp,BIO_NOCLOSE);
	CRYPTO_mem_leaks(b);
	BIO_free(b);
	}
#endif

844 845 846 847 848


/* FIXME: We really don't allow much to the callback.  For example, it has
   no chance of reaching the info stack for the item it processes.  Should
   it really be this way?  -- Richard Levitte */
849 850 851
/* NB: The prototypes have been typedef'd to CRYPTO_MEM_LEAK_CB inside crypto.h
 * If this code is restructured, remove the callback type if it is no longer
 * needed. -- Geoff Thorpe */
852 853 854 855 856 857 858 859 860

/* Can't pass CRYPTO_MEM_LEAK_CB directly to lh_MEM_doall_arg because it
 * is a function pointer and conversion to void * is prohibited. Instead
 * pass its address
 */

typedef CRYPTO_MEM_LEAK_CB *PCRYPTO_MEM_LEAK_CB;

static void cb_leak_doall_arg(const MEM *m, PCRYPTO_MEM_LEAK_CB *cb)
861
	{
862
	(*cb)(m->order,m->file,m->line,m->num,m->addr);
863 864
	}

865
static IMPLEMENT_LHASH_DOALL_ARG_FN(cb_leak, const MEM, PCRYPTO_MEM_LEAK_CB)
866

867
void CRYPTO_mem_leaks_cb(CRYPTO_MEM_LEAK_CB *cb)
868 869 870
	{
	if (mh == NULL) return;
	CRYPTO_w_lock(CRYPTO_LOCK_MALLOC2);
871 872
	lh_MEM_doall_arg(mh, LHASH_DOALL_ARG_FN(cb_leak), PCRYPTO_MEM_LEAK_CB,
			 &cb);
873 874
	CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
	}