mem_dbg.c 23.2 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 154
	unsigned long thread_id;
	void *thread_idptr;
155 156 157
	const char *file;
	int line;
	const char *info;
158
	struct app_mem_info_st *next; /* tail of thread's stack */
159 160 161
	int references;
	} APP_INFO;

162 163
static void app_info_free(APP_INFO *);

B
Ben Laurie 已提交
164 165 166 167 168 169 170
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 */
171 172

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

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

195

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

201 202 203 204 205 206
/* The following two variables, disabling_thread_id and disabling_thread_idptr,
 * are valid iff num_disable > 0.  CRYPTO_LOCK_MALLOC2 is locked exactly in
 * this case (by the thread named in disabling_thread_id / disabling_thread_idptr).
 */
static unsigned long disabling_thread_id = 0;
static void *disabling_thread_idptr = NULL;
207

208 209 210 211 212 213 214 215 216 217 218 219
static void app_info_free(APP_INFO *inf)
	{
	if (--(inf->references) <= 0)
		{
		if (inf->next != NULL)
			{
			app_info_free(inf->next);
			}
		OPENSSL_free(inf);
		}
	}

220 221 222 223 224 225 226
int CRYPTO_mem_ctrl(int mode)
	{
	int ret=mh_mode;

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

	/* switch off temporarily (for library-internal use): */
	case CRYPTO_MEM_CHECK_DISABLE: /* aka MemCheck_off() */
		if (mh_mode & CRYPTO_MEM_CHECK_ON)
			{
243 244 245
			if (!num_disable
			    || (disabling_thread_id != CRYPTO_thread_id())
			    || (disabling_thread_idptr != CRYPTO_thread_idptr())) /* otherwise we already have the MALLOC2 lock */
246 247 248
				{
				/* Long-time lock CRYPTO_LOCK_MALLOC2 must not be claimed while
				 * we're holding CRYPTO_LOCK_MALLOC, or we'll deadlock if
249 250
				 * somebody else holds CRYPTO_LOCK_MALLOC2 (and cannot release
				 * it because we block entry to this function).
251 252 253 254 255 256 257 258 259 260 261
				 * 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);
262
				mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
263 264
				disabling_thread_id=CRYPTO_thread_id();
				disabling_thread_idptr=CRYPTO_thread_idptr();
265
				}
266
			num_disable++;
267 268 269 270 271
			}
		break;
	case CRYPTO_MEM_CHECK_ENABLE: /* aka MemCheck_on() */
		if (mh_mode & CRYPTO_MEM_CHECK_ON)
			{
272
			if (num_disable) /* always true, or something is going wrong */
273
				{
274 275 276 277 278 279
				num_disable--;
				if (num_disable == 0)
					{
					mh_mode|=CRYPTO_MEM_CHECK_ENABLE;
					CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
					}
280 281 282 283 284 285 286 287 288 289 290
				}
			}
		break;

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

291
int CRYPTO_is_mem_check_on(void)
292 293 294 295 296
	{
	int ret = 0;

	if (mh_mode & CRYPTO_MEM_CHECK_ON)
		{
297
		CRYPTO_r_lock(CRYPTO_LOCK_MALLOC);
298

299 300 301
		ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
		        || (disabling_thread_id != CRYPTO_thread_id())
		        || (disabling_thread_idptr != CRYPTO_thread_idptr());
302

303
		CRYPTO_r_unlock(CRYPTO_LOCK_MALLOC);
304 305 306 307 308
		}
	return(ret);
	}	


309
void CRYPTO_dbg_set_options(long bits)
310 311 312 313
	{
	options = bits;
	}

314
long CRYPTO_dbg_get_options(void)
315 316 317 318
	{
	return options;
	}

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

B
Ben Laurie 已提交
333
static unsigned long mem_hash(const MEM *a)
334 335 336
	{
	unsigned long ret;

B
Ben Laurie 已提交
337
	ret=(unsigned long)a->addr;
338 339 340 341

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

344
/* static int app_info_cmp(APP_INFO *a, APP_INFO *b) */
345
static int app_info_cmp(const void *a_void, const void *b_void)
346
	{
347 348
	return (((const APP_INFO *)a_void)->thread_id != ((const APP_INFO *)b_void)->thread_id)
	       || (((const APP_INFO *)a_void)->thread_idptr != ((const APP_INFO *)b_void)->thread_idptr);
349
	}
B
Ben Laurie 已提交
350
static IMPLEMENT_LHASH_COMP_FN(app_info, APP_INFO)
351

B
Ben Laurie 已提交
352
static unsigned long app_info_hash(const APP_INFO *a)
353
	{
354
	unsigned long id1, id2;
355
	unsigned long ret;
356 357 358 359 360

	id1=(unsigned long)a->thread_id;
	id2=(unsigned long)a->thread_idptr;
	ret = id1 + id2;

361 362 363
	ret=ret*17851+(ret>>14)*7+(ret>>4)*251;
	return(ret);
	}
B
Ben Laurie 已提交
364
static IMPLEMENT_LHASH_HASH_FN(app_info, APP_INFO)
365

U
Ulf Möller 已提交
366
static APP_INFO *pop_info(void)
367 368 369 370 371 372
	{
	APP_INFO tmp;
	APP_INFO *ret = NULL;

	if (amih != NULL)
		{
373 374
		tmp.thread_id=CRYPTO_thread_id();
		tmp.thread_idptr=CRYPTO_thread_idptr();
B
Ben Laurie 已提交
375
		if ((ret=lh_APP_INFO_delete(amih,&tmp)) != NULL)
376 377 378 379 380 381
			{
			APP_INFO *next=ret->next;

			if (next != NULL)
				{
				next->references++;
B
Ben Laurie 已提交
382
				lh_APP_INFO_insert(amih,next);
383
				}
384
#ifdef LEVITTE_DEBUG_MEM
385
			if (ret->thread_id != tmp.thread_id || ret->thread_idptr != tmp.thread_idptr)
386
				{
387 388
				fprintf(stderr, "pop_info(): deleted info has other thread ID (%lu/%p) than the current thread (%lu/%p)!!!!\n",
					ret->thread_id, ret->thread_idptr, tmp.thread_id, tmp.thread_idptr);
389 390 391 392 393 394 395 396
				abort();
				}
#endif
			if (--(ret->references) <= 0)
				{
				ret->next = NULL;
				if (next != NULL)
					next->references--;
397
				OPENSSL_free(ret);
398 399 400 401 402 403
				}
			}
		}
	return(ret);
	}

B
Rename  
Bodo Möller 已提交
404
int CRYPTO_push_info_(const char *info, const char *file, int line)
405 406 407 408 409 410
	{
	APP_INFO *ami, *amim;
	int ret=0;

	if (is_MemCheck_on())
		{
411
		MemCheck_off(); /* obtain MALLOC2 lock */
412

413
		if ((ami = (APP_INFO *)OPENSSL_malloc(sizeof(APP_INFO))) == NULL)
414 415 416 417 418 419
			{
			ret=0;
			goto err;
			}
		if (amih == NULL)
			{
B
Ben Laurie 已提交
420
			if ((amih=lh_APP_INFO_new()) == NULL)
421
				{
422
				OPENSSL_free(ami);
423 424 425 426 427
				ret=0;
				goto err;
				}
			}

428 429
		ami->thread_id=CRYPTO_thread_id();
		ami->thread_idptr=CRYPTO_thread_idptr();
430 431 432 433 434 435
		ami->file=file;
		ami->line=line;
		ami->info=info;
		ami->references=1;
		ami->next=NULL;

B
Ben Laurie 已提交
436
		if ((amim=lh_APP_INFO_insert(amih,ami)) != NULL)
437
			{
438
#ifdef LEVITTE_DEBUG_MEM
439
			if (ami->thread_id != amim->thread_id || ami->thread_idptr != amim->thread_idptr)
440
				{
441 442
				fprintf(stderr, "CRYPTO_push_info(): previous info has other thread ID (%lu/%p) than the current thread (%lu/%p)!!!!\n",
					amim->thread_id, amim->thread_idptr, ami->thread_id, ami->thread_idptr);
443 444 445 446 447 448
				abort();
				}
#endif
			ami->next=amim;
			}
 err:
449
		MemCheck_on(); /* release MALLOC2 lock */
450 451 452 453 454
		}

	return(ret);
	}

B
Rename  
Bodo Möller 已提交
455
int CRYPTO_pop_info(void)
456 457 458
	{
	int ret=0;

459
	if (is_MemCheck_on()) /* _must_ be true, or something went severely wrong */
460
		{
461
		MemCheck_off(); /* obtain MALLOC2 lock */
462

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

465
		MemCheck_on(); /* release MALLOC2 lock */
466 467 468 469 470 471 472 473
		}
	return(ret);
	}

int CRYPTO_remove_all_info(void)
	{
	int ret=0;

474
	if (is_MemCheck_on()) /* _must_ be true */
475
		{
476
		MemCheck_off(); /* obtain MALLOC2 lock */
477

B
Rename  
Bodo Möller 已提交
478
		while(pop_info() != NULL)
479 480
			ret++;

481
		MemCheck_on(); /* release MALLOC2 lock */
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
		}
	return(ret);
	}


static unsigned long break_order_num=0;
void CRYPTO_dbg_malloc(void *addr, int num, const char *file, int line,
	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())
			{
504
			MemCheck_off(); /* make sure we hold MALLOC2 lock */
505
			if ((m=(MEM *)OPENSSL_malloc(sizeof(MEM))) == NULL)
506
				{
507
				OPENSSL_free(addr);
508 509
				MemCheck_on(); /* release MALLOC2 lock
				                * if num_disabled drops to 0 */
510 511 512 513
				return;
				}
			if (mh == NULL)
				{
B
Ben Laurie 已提交
514
				if ((mh=lh_MEM_new()) == NULL)
515
					{
516 517
					OPENSSL_free(addr);
					OPENSSL_free(m);
518 519 520 521 522 523 524 525 526
					addr=NULL;
					goto err;
					}
				}

			m->addr=addr;
			m->file=file;
			m->line=line;
			m->num=num;
527 528 529 530 531 532 533 534 535 536
			if (options & V_CRYPTO_MDEBUG_THREAD)
				{
				m->thread_id=CRYPTO_thread_id();
				m->thread_idptr=CRYPTO_thread_idptr();
				}
			else
				{
				m->thread_id=0;
				m->thread_idptr=NULL;
				}
537 538 539 540 541 542 543

			if (order == break_order_num)
				{
				/* BREAK HERE */
				m->order=order;
				}
			m->order=order++;
544
#ifdef LEVITTE_DEBUG_MEM
545
			fprintf(stderr, "LEVITTE_DEBUG_MEM: [%5ld] %c 0x%p (%d)\n",
546 547 548 549 550 551 552 553 554
				m->order,
				(before_p & 128) ? '*' : '+',
				m->addr, m->num);
#endif
			if (options & V_CRYPTO_MDEBUG_TIME)
				m->time=time(NULL);
			else
				m->time=0;

555 556
			tmp.thread_id=CRYPTO_thread_id();
			tmp.thread_idptr=CRYPTO_thread_idptr();
557 558
			m->app_info=NULL;
			if (amih != NULL
B
Ben Laurie 已提交
559
			    && (amim=lh_APP_INFO_retrieve(amih,&tmp)) != NULL)
560 561 562 563 564
				{
				m->app_info = amim;
				amim->references++;
				}

B
Ben Laurie 已提交
565
			if ((mm=lh_MEM_insert(mh, m)) != NULL)
566 567 568 569 570 571
				{
				/* Not good, but don't sweat it */
				if (mm->app_info != NULL)
					{
					mm->app_info->references--;
					}
572
				OPENSSL_free(mm);
573 574
				}
		err:
575 576
			MemCheck_on(); /* release MALLOC2 lock
			                * if num_disabled drops to 0 */
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
			}
		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))
			{
595
			MemCheck_off(); /* make sure we hold MALLOC2 lock */
596 597

			m.addr=addr;
B
Ben Laurie 已提交
598
			mp=lh_MEM_delete(mh,&m);
599 600
			if (mp != NULL)
				{
601
#ifdef LEVITTE_DEBUG_MEM
602
			fprintf(stderr, "LEVITTE_DEBUG_MEM: [%5ld] - 0x%p (%d)\n",
603 604 605
				mp->order, mp->addr, mp->num);
#endif
				if (mp->app_info != NULL)
606
					app_info_free(mp->app_info);
607
				OPENSSL_free(mp);
608 609
				}

610 611
			MemCheck_on(); /* release MALLOC2 lock
			                * if num_disabled drops to 0 */
612 613 614 615 616 617 618 619 620 621 622 623
			}
		break;
	case 1:
		break;
		}
	}

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

624 625
#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",
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
		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())
			{
645
			MemCheck_off(); /* make sure we hold MALLOC2 lock */
646 647

			m.addr=addr1;
B
Ben Laurie 已提交
648
			mp=lh_MEM_delete(mh,&m);
649 650
			if (mp != NULL)
				{
651
#ifdef LEVITTE_DEBUG_MEM
652
				fprintf(stderr, "LEVITTE_DEBUG_MEM: [%5ld] * 0x%p (%d) -> 0x%p (%d)\n",
653 654 655 656 657 658
					mp->order,
					mp->addr, mp->num,
					addr2, num);
#endif
				mp->addr=addr2;
				mp->num=num;
B
Ben Laurie 已提交
659
				lh_MEM_insert(mh,mp);
660 661
				}

662 663
			MemCheck_on(); /* release MALLOC2 lock
			                * if num_disabled drops to 0 */
664 665 666 667 668 669 670 671 672 673 674 675 676 677
			}
		break;
		}
	return;
	}


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

B
Ben Laurie 已提交
678
static void print_leak_doall_arg(const MEM *m, MEM_LEAK *l)
679 680 681 682 683 684
	{
	char buf[1024];
	char *bufp = buf;
	APP_INFO *amip;
	int ami_cnt;
	struct tm *lcl = NULL;
685 686
	unsigned long ti;
	void *tip;
687

688 689
#define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))

690 691 692 693 694 695 696
	if(m->addr == (char *)l->bio)
	    return;

	if (options & V_CRYPTO_MDEBUG_TIME)
		{
		lcl = localtime(&m->time);
	
697
		BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
698 699 700 701
			lcl->tm_hour,lcl->tm_min,lcl->tm_sec);
		bufp += strlen(bufp);
		}

702
	BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
703 704 705 706 707
		m->order,m->file,m->line);
	bufp += strlen(bufp);

	if (options & V_CRYPTO_MDEBUG_THREAD)
		{
708
		BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu/%p, ", m->thread_id, m->thread_idptr);
709 710 711
		bufp += strlen(bufp);
		}

712
	BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%08lX\n",
713 714 715 716 717 718 719 720 721 722
		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;
723 724
	if (!amip)
		return;
725 726
	ti=amip->thread_id;
	tip=amip->thread_idptr;
727 728
	
	do
729 730 731 732 733 734
		{
		int buf_len;
		int info_len;

		ami_cnt++;
		memset(buf,'>',ami_cnt);
735
		BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
736 737
			" thread=%lu/%p, file=%s, line=%d, info=\"",
			amip->thread_id, amip->thread_idptr, amip->file, amip->line);
738 739 740 741 742 743 744 745 746
		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
			{
747 748
			BUF_strlcpy(buf + buf_len, amip->info,
				    sizeof buf - buf_len);
749 750
			buf_len = strlen(buf);
			}
751
		BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
752 753 754 755 756
		
		BIO_puts(l->bio,buf);

		amip = amip->next;
		}
757
	while(amip && amip->thread_id == ti && amip->thread_idptr == tip);
758

759
#ifdef LEVITTE_DEBUG_MEM
760 761
	if (amip)
		{
R
Typo...  
Richard Levitte 已提交
762
		fprintf(stderr, "Thread switch detected in backtrace!!!!\n");
763 764 765 766 767
		abort();
		}
#endif
	}

B
Ben Laurie 已提交
768
static IMPLEMENT_LHASH_DOALL_ARG_FN(print_leak, const MEM, MEM_LEAK)
769

770 771 772 773
void CRYPTO_mem_leaks(BIO *b)
	{
	MEM_LEAK ml;

774 775
	if (mh == NULL && amih == NULL)
		return;
776 777 778

	MemCheck_off(); /* obtain MALLOC2 lock */

779 780 781
	ml.bio=b;
	ml.bytes=0;
	ml.chunks=0;
782
	if (mh != NULL)
B
Ben Laurie 已提交
783 784
		lh_MEM_doall_arg(mh, LHASH_DOALL_ARG_FN(print_leak), MEM_LEAK,
				 &ml);
785 786
	if (ml.chunks != 0)
		{
787 788
		BIO_printf(b,"%ld bytes leaked in %d chunks\n",
			   ml.bytes,ml.chunks);
789
		}
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
	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 已提交
807 808
		int old_mh_mode;

809
		CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
B
Bodo Möller 已提交
810 811 812 813 814 815

		/* 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;

816 817
		if (mh != NULL)
			{
B
Ben Laurie 已提交
818
			lh_MEM_free(mh);
819 820 821 822
			mh = NULL;
			}
		if (amih != NULL)
			{
B
Ben Laurie 已提交
823
			if (lh_APP_INFO_num_items(amih) == 0) 
824
				{
B
Ben Laurie 已提交
825
				lh_APP_INFO_free(amih);
826 827 828
				amih = NULL;
				}
			}
B
Bodo Möller 已提交
829 830

		mh_mode = old_mh_mode;
831 832
		CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
		}
833
	MemCheck_on(); /* release MALLOC2 lock */
834 835
	}

836
#ifndef OPENSSL_NO_FP_API
837 838 839 840 841
void CRYPTO_mem_leaks_fp(FILE *fp)
	{
	BIO *b;

	if (mh == NULL) return;
842 843 844 845
	/* 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();
846
	b = BIO_new(BIO_s_file());
847
	MemCheck_on();
848
	if(!b) return;
849 850 851 852 853 854
	BIO_set_fp(b,fp,BIO_NOCLOSE);
	CRYPTO_mem_leaks(b);
	BIO_free(b);
	}
#endif

855 856 857 858 859


/* 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 */
860 861 862
/* 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 */
B
Ben Laurie 已提交
863
static void cb_leak_doall_arg(const MEM *m, CRYPTO_MEM_LEAK_CB *cb)
864
	{
B
Ben Laurie 已提交
865
	cb(m->order,m->file,m->line,m->num,m->addr);
866 867
	}

B
Ben Laurie 已提交
868
static IMPLEMENT_LHASH_DOALL_ARG_FN(cb_leak, const MEM, CRYPTO_MEM_LEAK_CB)
869

870
void CRYPTO_mem_leaks_cb(CRYPTO_MEM_LEAK_CB *cb)
871 872 873
	{
	if (mh == NULL) return;
	CRYPTO_w_lock(CRYPTO_LOCK_MALLOC2);
B
Ben Laurie 已提交
874 875
	lh_MEM_doall_arg(mh, LHASH_DOALL_ARG_FN(cb_leak), CRYPTO_MEM_LEAK_CB,
			 cb);
876 877
	CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
	}