Add lh_doall_arg inlining
[openssl.git] / crypto / mem_dbg.c
1 /* crypto/mem_dbg.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
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.
8  *
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).
15  *
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.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
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)"
40  *
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
51  * SUCH DAMAGE.
52  *
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.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
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
71  *    distribution.
72  *
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/)"
77  *
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.
82  *
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.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
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  * ====================================================================
105  *
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).
109  *
110  */
111
112 #include <stdio.h>
113 #include <stdlib.h>
114 #include <time.h>
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>
122 #endif
123
124 /*
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.
134  */
135 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
136 static int mh_mode = CRYPTO_MEM_CHECK_OFF;
137 #endif
138
139 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
140 static unsigned long order = 0; /* number of memory requests */
141
142 /*-
143  * For application-defined information (static C-string `info')
144  * to be displayed in memory leak list.
145  * Each thread has its own stack.  For applications, there is
146  *   OPENSSL_mem_debug_push("...")     to push an entry,
147  *   OPENSSL_mem_debug_pop()     to pop an entry,
148  */
149 struct app_mem_info_st {
150     CRYPTO_THREADID threadid;
151     const char *file;
152     int line;
153     const char *info;
154     struct app_mem_info_st *next; /* tail of thread's stack */
155     int references;
156 };
157
158 /*
159  * hash-table with those app_mem_info_st's that are at the
160  * top of their thread's stack (with `thread' as key); access requires
161  * MALLOC2 lock
162  */
163 static LHASH_OF(APP_INFO) *amih = NULL;
164
165 /* memory-block description */
166 struct mem_st {
167     void *addr;
168     int num;
169     const char *file;
170     int line;
171     CRYPTO_THREADID threadid;
172     unsigned long order;
173     time_t time;
174     APP_INFO *app_info;
175 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
176     void *array[30];
177     size_t array_siz;
178 #endif
179 };
180
181 static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
182                                   * key); access requires MALLOC2 lock */
183
184 /* num_disable > 0 iff mh_mode == CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
185 static unsigned int num_disable = 0;
186
187 /*
188  * Valid iff num_disable > 0.  CRYPTO_LOCK_MALLOC2 is locked exactly in this
189  * case (by the thread named in disabling_thread).
190  */
191 static CRYPTO_THREADID disabling_threadid;
192
193 static void app_info_free(APP_INFO *inf)
194 {
195     if (!inf)
196         return;
197     if (--(inf->references) <= 0) {
198         app_info_free(inf->next);
199         OPENSSL_free(inf);
200     }
201 }
202 #endif
203
204 int CRYPTO_mem_ctrl(int mode)
205 {
206 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
207     return mode - mode;
208 #else
209     int ret = mh_mode;
210
211     CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
212     switch (mode) {
213     default:
214         break;
215
216     case CRYPTO_MEM_CHECK_ON:
217         mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
218         num_disable = 0;
219         break;
220
221     case CRYPTO_MEM_CHECK_OFF:
222         mh_mode = 0;
223         num_disable = 0;
224         break;
225
226     /* switch off temporarily (for library-internal use): */
227     case CRYPTO_MEM_CHECK_DISABLE:
228         if (mh_mode & CRYPTO_MEM_CHECK_ON) {
229             CRYPTO_THREADID cur;
230             CRYPTO_THREADID_current(&cur);
231             /* see if we don't have the MALLOC2 lock already */
232             if (!num_disable
233                 || CRYPTO_THREADID_cmp(&disabling_threadid, &cur)) {
234                 /*
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).
241                  */
242                 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
243                 /*
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.
248                  */
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);
253             }
254             num_disable++;
255         }
256         break;
257
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 */
261                 num_disable--;
262                 if (num_disable == 0) {
263                     mh_mode |= CRYPTO_MEM_CHECK_ENABLE;
264                     CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
265                 }
266             }
267         }
268         break;
269     }
270     CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
271     return (ret);
272 #endif
273 }
274
275 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
276
277 static int mem_check_on(void)
278 {
279     int ret = 0;
280
281     if (mh_mode & CRYPTO_MEM_CHECK_ON) {
282         CRYPTO_THREADID cur;
283         CRYPTO_THREADID_current(&cur);
284         CRYPTO_r_lock(CRYPTO_LOCK_MALLOC);
285
286         ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
287             || CRYPTO_THREADID_cmp(&disabling_threadid, &cur);
288
289         CRYPTO_r_unlock(CRYPTO_LOCK_MALLOC);
290     }
291     return (ret);
292 }
293
294 static int mem_cmp(const MEM *a, const MEM *b)
295 {
296 #ifdef _WIN64
297     const char *ap = (const char *)a->addr, *bp = (const char *)b->addr;
298     if (ap == bp)
299         return 0;
300     else if (ap > bp)
301         return 1;
302     else
303         return -1;
304 #else
305     return (const char *)a->addr - (const char *)b->addr;
306 #endif
307 }
308
309 static unsigned long mem_hash(const MEM *a)
310 {
311     size_t ret;
312
313     ret = (size_t)a->addr;
314
315     ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
316     return (ret);
317 }
318
319 static int app_info_cmp(const APP_INFO *a, const APP_INFO *b)
320 {
321     return CRYPTO_THREADID_cmp(&a->threadid, &b->threadid);
322 }
323
324 static unsigned long app_info_hash(const APP_INFO *a)
325 {
326     unsigned long ret;
327
328     ret = CRYPTO_THREADID_hash(&a->threadid);
329     /* This is left in as a "who am I to question legacy?" measure */
330     ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
331     return (ret);
332 }
333
334 static APP_INFO *pop_info(void)
335 {
336     APP_INFO tmp;
337     APP_INFO *ret = NULL;
338
339     if (amih != NULL) {
340         CRYPTO_THREADID_current(&tmp.threadid);
341         if ((ret = lh_APP_INFO_delete(amih, &tmp)) != NULL) {
342             APP_INFO *next = ret->next;
343
344             if (next != NULL) {
345                 next->references++;
346                 (void)lh_APP_INFO_insert(amih, next);
347             }
348             if (--(ret->references) <= 0) {
349                 ret->next = NULL;
350                 if (next != NULL)
351                     next->references--;
352                 OPENSSL_free(ret);
353             }
354         }
355     }
356     return (ret);
357 }
358
359 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
360 {
361     APP_INFO *ami, *amim;
362     int ret = 0;
363
364     if (mem_check_on()) {
365         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
366
367         if ((ami = OPENSSL_malloc(sizeof(*ami))) == NULL)
368             goto err;
369         if (amih == NULL) {
370             if ((amih = lh_APP_INFO_new(app_info_hash, app_info_cmp)) == NULL) {
371                 OPENSSL_free(ami);
372                 goto err;
373             }
374         }
375
376         CRYPTO_THREADID_current(&ami->threadid);
377         ami->file = file;
378         ami->line = line;
379         ami->info = info;
380         ami->references = 1;
381         ami->next = NULL;
382
383         if ((amim = lh_APP_INFO_insert(amih, ami)) != NULL)
384             ami->next = amim;
385         ret = 1;
386  err:
387         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
388     }
389
390     return (ret);
391 }
392
393 int CRYPTO_mem_debug_pop(void)
394 {
395     int ret = 0;
396
397     if (mem_check_on()) {
398         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
399         ret = (pop_info() != NULL);
400         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
401     }
402     return (ret);
403 }
404
405 static unsigned long break_order_num = 0;
406
407 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int before_p,
408                              const char *file, int line)
409 {
410     MEM *m, *mm;
411     APP_INFO tmp, *amim;
412
413     switch (before_p & 127) {
414     case 0:
415         break;
416     case 1:
417         if (addr == NULL)
418             break;
419
420         if (mem_check_on()) {
421             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
422             if ((m = OPENSSL_malloc(sizeof(*m))) == NULL) {
423                 OPENSSL_free(addr);
424                 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
425                 return;
426             }
427             if (mh == NULL) {
428                 if ((mh = lh_MEM_new(mem_hash, mem_cmp)) == NULL) {
429                     OPENSSL_free(addr);
430                     OPENSSL_free(m);
431                     addr = NULL;
432                     goto err;
433                 }
434             }
435
436             m->addr = addr;
437             m->file = file;
438             m->line = line;
439             m->num = num;
440             CRYPTO_THREADID_current(&m->threadid);
441
442             if (order == break_order_num) {
443                 /* BREAK HERE */
444                 m->order = order;
445             }
446             m->order = order++;
447 # if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
448             m->array_siz = backtrace(m->array, OSSL_NELEM(m->array));
449 # endif
450             m->time = time(NULL);
451
452             CRYPTO_THREADID_current(&tmp.threadid);
453             m->app_info = NULL;
454             if (amih != NULL
455                 && (amim = lh_APP_INFO_retrieve(amih, &tmp)) != NULL) {
456                 m->app_info = amim;
457                 amim->references++;
458             }
459
460             if ((mm = lh_MEM_insert(mh, m)) != NULL) {
461                 /* Not good, but don't sweat it */
462                 if (mm->app_info != NULL) {
463                     mm->app_info->references--;
464                 }
465                 OPENSSL_free(mm);
466             }
467  err:
468             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
469         }
470         break;
471     }
472     return;
473 }
474
475 void CRYPTO_mem_debug_free(void *addr, int before_p)
476 {
477     MEM m, *mp;
478
479     switch (before_p) {
480     case 0:
481         if (addr == NULL)
482             break;
483
484         if (mem_check_on() && (mh != NULL)) {
485             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
486
487             m.addr = addr;
488             mp = lh_MEM_delete(mh, &m);
489             if (mp != NULL) {
490                 app_info_free(mp->app_info);
491                 OPENSSL_free(mp);
492             }
493
494             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
495         }
496         break;
497     case 1:
498         break;
499     }
500 }
501
502 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num,
503                               int before_p, const char *file, int line)
504 {
505     MEM m, *mp;
506
507     switch (before_p) {
508     case 0:
509         break;
510     case 1:
511         if (addr2 == NULL)
512             break;
513
514         if (addr1 == NULL) {
515             CRYPTO_mem_debug_malloc(addr2, num, 128 | before_p, file, line);
516             break;
517         }
518
519         if (mem_check_on()) {
520             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
521
522             m.addr = addr1;
523             mp = lh_MEM_delete(mh, &m);
524             if (mp != NULL) {
525                 mp->addr = addr2;
526                 mp->num = num;
527 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
528                 mp->array_siz = backtrace(mp->array, OSSL_NELEM(mp->array));
529 #endif
530                 (void)lh_MEM_insert(mh, mp);
531             }
532
533             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
534         }
535         break;
536     }
537     return;
538 }
539
540 typedef struct mem_leak_st {
541     BIO *bio;
542     int chunks;
543     int seen;
544     long bytes;
545 } MEM_LEAK;
546
547 static void print_leak(const MEM *m, MEM_LEAK *l)
548 {
549     char buf[1024];
550     char *bufp = buf;
551     APP_INFO *amip;
552     int ami_cnt;
553     struct tm *lcl = NULL;
554     CRYPTO_THREADID ti;
555
556 #define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))
557
558     /* Is one "leak" the BIO we were given? */
559     if (m->addr == (char *)l->bio) {
560         l->seen = 1;
561         return;
562     }
563
564     lcl = localtime(&m->time);
565     BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
566                  lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
567     bufp += strlen(bufp);
568
569     BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
570                  m->order, m->file, m->line);
571     bufp += strlen(bufp);
572
573     BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ",
574                  CRYPTO_THREADID_hash(&m->threadid));
575     bufp += strlen(bufp);
576
577     BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%p\n",
578                  m->num, m->addr);
579     bufp += strlen(bufp);
580
581     BIO_puts(l->bio, buf);
582
583     l->chunks++;
584     l->bytes += m->num;
585
586     amip = m->app_info;
587     ami_cnt = 0;
588
589     if (amip) {
590         CRYPTO_THREADID_cpy(&ti, &amip->threadid);
591
592         do {
593             int buf_len;
594             int info_len;
595
596             ami_cnt++;
597             memset(buf, '>', ami_cnt);
598             BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
599                          " thread=%lu, file=%s, line=%d, info=\"",
600                          CRYPTO_THREADID_hash(&amip->threadid), amip->file,
601                          amip->line);
602             buf_len = strlen(buf);
603             info_len = strlen(amip->info);
604             if (128 - buf_len - 3 < info_len) {
605                 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
606                 buf_len = 128 - 3;
607             } else {
608                 OPENSSL_strlcpy(buf + buf_len, amip->info, sizeof buf - buf_len);
609                 buf_len = strlen(buf);
610             }
611             BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
612
613             BIO_puts(l->bio, buf);
614
615             amip = amip->next;
616         }
617         while (amip && !CRYPTO_THREADID_cmp(&amip->threadid, &ti));
618     }
619
620 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
621     {
622         size_t i;
623         char **strings = backtrace_symbols(m->array, m->array_siz);
624
625         for (i = 0; i < m->array_siz; i++)
626             fprintf(stderr, "##> %s\n", strings[i]);
627         free(strings);
628     }
629 #endif
630 }
631
632 IMPLEMENT_LHASH_DOALL_ARG_CONST(MEM, MEM_LEAK);
633
634 int CRYPTO_mem_leaks(BIO *b)
635 {
636     MEM_LEAK ml;
637
638     if (mh == NULL && amih == NULL)
639         return 1;
640
641     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
642
643     ml.bio = b;
644     ml.bytes = 0;
645     ml.chunks = 0;
646     ml.seen = 0;
647     if (mh != NULL)
648         lh_MEM_doall_MEM_LEAK(mh, print_leak, &ml);
649     /* Don't count the BIO that was passed in as a "leak" */
650     if (ml.seen && ml.chunks >= 1 && ml.bytes >= (int)sizeof (*b)) {
651         ml.chunks--;
652         ml.bytes -= (int)sizeof (*b);
653     }
654     if (ml.chunks != 0) {
655         BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks);
656     } else {
657         /*
658          * Make sure that, if we found no leaks, memory-leak debugging itself
659          * does not introduce memory leaks (which might irritate external
660          * debugging tools). (When someone enables leak checking, but does not
661          * call this function, we declare it to be their fault.)
662          */
663         int old_mh_mode;
664
665         CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
666
667         /*
668          * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses
669          * mem_check_on
670          */
671         old_mh_mode = mh_mode;
672         mh_mode = CRYPTO_MEM_CHECK_OFF;
673
674         lh_MEM_free(mh);
675         mh = NULL;
676         if (amih != NULL) {
677             if (lh_APP_INFO_num_items(amih) == 0) {
678                 lh_APP_INFO_free(amih);
679                 amih = NULL;
680             }
681         }
682
683         mh_mode = old_mh_mode;
684         CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
685     }
686     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
687     return ml.chunks == 0 ? 1 : 0;
688 }
689
690 # ifndef OPENSSL_NO_STDIO
691 int CRYPTO_mem_leaks_fp(FILE *fp)
692 {
693     BIO *b;
694     int ret;
695
696     if (mh == NULL)
697         return 0;
698     /*
699      * Need to turn off memory checking when allocated BIOs ... especially as
700      * we're creating them at a time when we're trying to check we've not
701      * left anything un-free()'d!!
702      */
703     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
704     b = BIO_new(BIO_s_file());
705     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
706     if (b == NULL)
707         return -1;
708     BIO_set_fp(b, fp, BIO_NOCLOSE);
709     ret = CRYPTO_mem_leaks(b);
710     BIO_free(b);
711     return ret;
712 }
713 # endif
714
715 #endif