Convert mem_dbg and mem_sec to the new Thread API
[openssl.git] / crypto / mem_dbg.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110
111 #include <stdio.h>
112 #include <stdlib.h>
113 #include <time.h>
114 #include "internal/cryptlib.h"
115 #include "internal/threads.h"
116 #include <openssl/crypto.h>
117 #include <openssl/buffer.h>
118 #include <openssl/bio.h>
119 #include <openssl/lhash.h>
120
121 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
122 # include <execinfo.h>
123 #endif
124
125 /*
126  * The state changes to CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE when
127  * the application asks for it (usually after library initialisation for
128  * which no book-keeping is desired). State CRYPTO_MEM_CHECK_ON exists only
129  * temporarily when the library thinks that certain allocations should not be
130  * checked (e.g. the data structures used for memory checking).  It is not
131  * suitable as an initial state: the library will unexpectedly enable memory
132  * checking when it executes one of those sections that want to disable
133  * checking temporarily. State CRYPTO_MEM_CHECK_ENABLE without ..._ON makes
134  * no sense whatsoever.
135  */
136 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
137 static int mh_mode = CRYPTO_MEM_CHECK_OFF;
138 #endif
139
140 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
141 static unsigned long order = 0; /* number of memory requests */
142
143 /*-
144  * For application-defined information (static C-string `info')
145  * to be displayed in memory leak list.
146  * Each thread has its own stack.  For applications, there is
147  *   OPENSSL_mem_debug_push("...")     to push an entry,
148  *   OPENSSL_mem_debug_pop()     to pop an entry,
149  */
150 struct app_mem_info_st {
151     CRYPTO_THREAD_ID threadid;
152     const char *file;
153     int line;
154     const char *info;
155     struct app_mem_info_st *next; /* tail of thread's stack */
156     int references;
157 };
158
159 static CRYPTO_ONCE memdbg_init = CRYPTO_ONCE_STATIC_INIT;
160 static CRYPTO_RWLOCK *malloc_lock = NULL;
161 static CRYPTO_RWLOCK *long_malloc_lock = NULL;
162 static CRYPTO_THREAD_LOCAL appinfokey;
163
164 /* memory-block description */
165 struct mem_st {
166     void *addr;
167     int num;
168     const char *file;
169     int line;
170     CRYPTO_THREAD_ID threadid;
171     unsigned long order;
172     time_t time;
173     APP_INFO *app_info;
174 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
175     void *array[30];
176     size_t array_siz;
177 #endif
178 };
179
180 static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
181                                   * key); access requires MALLOC2 lock */
182
183 /* num_disable > 0 iff mh_mode == CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
184 static unsigned int num_disable = 0;
185
186 /*
187  * Valid iff num_disable > 0.  long_malloc_lock is locked exactly in this
188  * case (by the thread named in disabling_thread).
189  */
190 static CRYPTO_THREAD_ID disabling_threadid;
191
192 static void do_memdbg_init(void)
193 {
194     malloc_lock = CRYPTO_THREAD_lock_new();
195     long_malloc_lock = CRYPTO_THREAD_lock_new();
196     CRYPTO_THREAD_init_local(&appinfokey, NULL);
197 }
198
199 static void app_info_free(APP_INFO *inf)
200 {
201     if (!inf)
202         return;
203     if (--(inf->references) <= 0) {
204         app_info_free(inf->next);
205         OPENSSL_free(inf);
206     }
207 }
208 #endif
209
210 int CRYPTO_mem_ctrl(int mode)
211 {
212 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
213     return mode - mode;
214 #else
215     int ret = mh_mode;
216
217     CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
218
219     CRYPTO_THREAD_write_lock(malloc_lock);
220     switch (mode) {
221     default:
222         break;
223
224     case CRYPTO_MEM_CHECK_ON:
225         mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
226         num_disable = 0;
227         break;
228
229     case CRYPTO_MEM_CHECK_OFF:
230         mh_mode = 0;
231         num_disable = 0;
232         break;
233
234     /* switch off temporarily (for library-internal use): */
235     case CRYPTO_MEM_CHECK_DISABLE:
236         if (mh_mode & CRYPTO_MEM_CHECK_ON) {
237             CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
238             /* see if we don't have long_malloc_lock already */
239             if (!num_disable
240                 || !CRYPTO_THREAD_compare_id(disabling_threadid, cur)) {
241                 /*
242                  * Long-time lock long_malloc_lock must not be claimed
243                  * while we're holding malloc_lock, or we'll deadlock
244                  * if somebody else holds long_malloc_lock (and cannot
245                  * release it because we block entry to this function). Give
246                  * them a chance, first, and then claim the locks in
247                  * appropriate order (long-time lock first).
248                  */
249                 CRYPTO_THREAD_unlock(malloc_lock);
250                 /*
251                  * Note that after we have waited for long_malloc_lock and
252                  * malloc_lock, we'll still be in the right "case" and
253                  * "if" branch because MemCheck_start and MemCheck_stop may
254                  * never be used while there are multiple OpenSSL threads.
255                  */
256                 CRYPTO_THREAD_write_lock(long_malloc_lock);
257                 CRYPTO_THREAD_write_lock(malloc_lock);
258                 mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
259                 disabling_threadid = cur;
260             }
261             num_disable++;
262         }
263         break;
264
265     case CRYPTO_MEM_CHECK_ENABLE:
266         if (mh_mode & CRYPTO_MEM_CHECK_ON) {
267             if (num_disable) {  /* always true, or something is going wrong */
268                 num_disable--;
269                 if (num_disable == 0) {
270                     mh_mode |= CRYPTO_MEM_CHECK_ENABLE;
271                     CRYPTO_THREAD_unlock(long_malloc_lock);
272                 }
273             }
274         }
275         break;
276     }
277     CRYPTO_THREAD_unlock(malloc_lock);
278     return (ret);
279 #endif
280 }
281
282 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
283
284 static int mem_check_on(void)
285 {
286     int ret = 0;
287
288     if (mh_mode & CRYPTO_MEM_CHECK_ON) {
289         CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
290
291         CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
292         CRYPTO_THREAD_read_lock(malloc_lock);
293
294         ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
295             || !CRYPTO_THREAD_compare_id(disabling_threadid, cur);
296
297         CRYPTO_THREAD_unlock(malloc_lock);
298     }
299     return (ret);
300 }
301
302 static int mem_cmp(const MEM *a, const MEM *b)
303 {
304 #ifdef _WIN64
305     const char *ap = (const char *)a->addr, *bp = (const char *)b->addr;
306     if (ap == bp)
307         return 0;
308     else if (ap > bp)
309         return 1;
310     else
311         return -1;
312 #else
313     return (const char *)a->addr - (const char *)b->addr;
314 #endif
315 }
316
317 static unsigned long mem_hash(const MEM *a)
318 {
319     size_t ret;
320
321     ret = (size_t)a->addr;
322
323     ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
324     return (ret);
325 }
326
327 /* returns 1 if there was an info to pop, 0 if the stack was empty. */
328 static int pop_info(void)
329 {
330     APP_INFO *current = NULL;
331
332     CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
333     current = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
334     if (current != NULL) {
335         APP_INFO *next = current->next;
336
337         if (next != NULL) {
338             next->references++;
339             CRYPTO_THREAD_set_local(&appinfokey, next);
340         } else {
341             CRYPTO_THREAD_set_local(&appinfokey, NULL);
342         }
343         if (--(current->references) <= 0) {
344             current->next = NULL;
345             if (next != NULL)
346                 next->references--;
347             OPENSSL_free(current);
348         }
349         return 1;
350     }
351     return 0;
352 }
353
354 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
355 {
356     APP_INFO *ami, *amim;
357     int ret = 0;
358
359     if (mem_check_on()) {
360         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
361
362         CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
363
364         if ((ami = OPENSSL_malloc(sizeof(*ami))) == NULL)
365             goto err;
366
367         ami->threadid = CRYPTO_THREAD_get_current_id();
368         ami->file = file;
369         ami->line = line;
370         ami->info = info;
371         ami->references = 1;
372         ami->next = NULL;
373
374         amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
375         CRYPTO_THREAD_set_local(&appinfokey, ami);
376
377         if (amim != NULL)
378             ami->next = amim;
379         ret = 1;
380  err:
381         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
382     }
383
384     return (ret);
385 }
386
387 int CRYPTO_mem_debug_pop(void)
388 {
389     int ret = 0;
390
391     if (mem_check_on()) {
392         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
393         ret = pop_info();
394         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
395     }
396     return (ret);
397 }
398
399 static unsigned long break_order_num = 0;
400
401 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int before_p,
402                              const char *file, int line)
403 {
404     MEM *m, *mm;
405     APP_INFO *amim;
406
407     switch (before_p & 127) {
408     case 0:
409         break;
410     case 1:
411         if (addr == NULL)
412             break;
413
414         if (mem_check_on()) {
415             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
416
417             CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
418
419             if ((m = OPENSSL_malloc(sizeof(*m))) == NULL) {
420                 OPENSSL_free(addr);
421                 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
422                 return;
423             }
424             if (mh == NULL) {
425                 if ((mh = lh_MEM_new(mem_hash, mem_cmp)) == NULL) {
426                     OPENSSL_free(addr);
427                     OPENSSL_free(m);
428                     addr = NULL;
429                     goto err;
430                 }
431             }
432
433             m->addr = addr;
434             m->file = file;
435             m->line = line;
436             m->num = num;
437             m->threadid = CRYPTO_THREAD_get_current_id();
438
439             if (order == break_order_num) {
440                 /* BREAK HERE */
441                 m->order = order;
442             }
443             m->order = order++;
444 # ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
445             m->array_siz = backtrace(m->array, OSSL_NELEM(m->array));
446 # endif
447             m->time = time(NULL);
448
449             amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
450             m->app_info = amim;
451             if (amim != NULL)
452                 amim->references++;
453
454             if ((mm = lh_MEM_insert(mh, m)) != NULL) {
455                 /* Not good, but don't sweat it */
456                 if (mm->app_info != NULL) {
457                     mm->app_info->references--;
458                 }
459                 OPENSSL_free(mm);
460             }
461  err:
462             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
463         }
464         break;
465     }
466     return;
467 }
468
469 void CRYPTO_mem_debug_free(void *addr, int before_p,
470         const char *file, int line)
471 {
472     MEM m, *mp;
473
474     switch (before_p) {
475     case 0:
476         if (addr == NULL)
477             break;
478
479         if (mem_check_on() && (mh != NULL)) {
480             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
481
482             m.addr = addr;
483             mp = lh_MEM_delete(mh, &m);
484             if (mp != NULL) {
485                 app_info_free(mp->app_info);
486                 OPENSSL_free(mp);
487             }
488
489             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
490         }
491         break;
492     case 1:
493         break;
494     }
495 }
496
497 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num,
498                               int before_p, const char *file, int line)
499 {
500     MEM m, *mp;
501
502     switch (before_p) {
503     case 0:
504         break;
505     case 1:
506         if (addr2 == NULL)
507             break;
508
509         if (addr1 == NULL) {
510             CRYPTO_mem_debug_malloc(addr2, num, 128 | before_p, file, line);
511             break;
512         }
513
514         if (mem_check_on()) {
515             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
516
517             m.addr = addr1;
518             mp = lh_MEM_delete(mh, &m);
519             if (mp != NULL) {
520                 mp->addr = addr2;
521                 mp->num = num;
522 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
523                 mp->array_siz = backtrace(mp->array, OSSL_NELEM(mp->array));
524 #endif
525                 (void)lh_MEM_insert(mh, mp);
526             }
527
528             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
529         }
530         break;
531     }
532     return;
533 }
534
535 typedef struct mem_leak_st {
536     BIO *bio;
537     int chunks;
538     int seen;
539     long bytes;
540 } MEM_LEAK;
541
542 static void print_leak(const MEM *m, MEM_LEAK *l)
543 {
544     char buf[1024];
545     char *bufp = buf;
546     APP_INFO *amip;
547     int ami_cnt;
548     struct tm *lcl = NULL;
549     /*
550      * Convert between CRYPTO_THREAD_ID (which could be anything at all) and
551      * a long. This may not be meaningful depending on what CRYPTO_THREAD_ID is
552      * but hopefully should give something sensible on most platforms
553      */
554     union {
555         CRYPTO_THREAD_ID tid;
556         unsigned long ltid;
557     } tid;
558     CRYPTO_THREAD_ID ti;
559
560 #define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))
561
562     /* Is one "leak" the BIO we were given? */
563     if (m->addr == (char *)l->bio) {
564         l->seen = 1;
565         return;
566     }
567
568     lcl = localtime(&m->time);
569     BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
570                  lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
571     bufp += strlen(bufp);
572
573     BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
574                  m->order, m->file, m->line);
575     bufp += strlen(bufp);
576
577     tid.ltid = 0;
578     tid.tid = m->threadid;
579     BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ", tid.ltid);
580     bufp += strlen(bufp);
581
582     BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%p\n",
583                  m->num, m->addr);
584     bufp += strlen(bufp);
585
586     BIO_puts(l->bio, buf);
587
588     l->chunks++;
589     l->bytes += m->num;
590
591     amip = m->app_info;
592     ami_cnt = 0;
593
594     if (amip) {
595         ti = amip->threadid;
596
597         do {
598             int buf_len;
599             int info_len;
600
601             ami_cnt++;
602             memset(buf, '>', ami_cnt);
603             tid.ltid = 0;
604             tid.tid = amip->threadid;
605             BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
606                          " thread=%lu, file=%s, line=%d, info=\"",
607                          tid.ltid, amip->file,
608                          amip->line);
609             buf_len = strlen(buf);
610             info_len = strlen(amip->info);
611             if (128 - buf_len - 3 < info_len) {
612                 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
613                 buf_len = 128 - 3;
614             } else {
615                 OPENSSL_strlcpy(buf + buf_len, amip->info, sizeof buf - buf_len);
616                 buf_len = strlen(buf);
617             }
618             BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
619
620             BIO_puts(l->bio, buf);
621
622             amip = amip->next;
623         }
624         while (amip && CRYPTO_THREAD_compare_id(amip->threadid, ti));
625     }
626
627 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
628     {
629         size_t i;
630         char **strings = backtrace_symbols(m->array, m->array_siz);
631
632         for (i = 0; i < m->array_siz; i++)
633             fprintf(stderr, "##> %s\n", strings[i]);
634         free(strings);
635     }
636 #endif
637 }
638
639 IMPLEMENT_LHASH_DOALL_ARG_CONST(MEM, MEM_LEAK);
640
641 int CRYPTO_mem_leaks(BIO *b)
642 {
643     MEM_LEAK ml;
644
645     /* Ensure all resources are released */
646     OPENSSL_cleanup();
647
648     CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
649
650     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
651
652     ml.bio = b;
653     ml.bytes = 0;
654     ml.chunks = 0;
655     ml.seen = 0;
656     if (mh != NULL)
657         lh_MEM_doall_MEM_LEAK(mh, print_leak, &ml);
658     /* Don't count the BIO that was passed in as a "leak" */
659     if (ml.seen && ml.chunks >= 1 && ml.bytes >= (int)sizeof (*b)) {
660         ml.chunks--;
661         ml.bytes -= (int)sizeof (*b);
662     }
663     if (ml.chunks != 0) {
664         BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks);
665     } else {
666         /*
667          * Make sure that, if we found no leaks, memory-leak debugging itself
668          * does not introduce memory leaks (which might irritate external
669          * debugging tools). (When someone enables leak checking, but does not
670          * call this function, we declare it to be their fault.)
671          */
672         int old_mh_mode;
673
674         CRYPTO_THREAD_write_lock(malloc_lock);
675
676         /*
677          * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses
678          * mem_check_on
679          */
680         old_mh_mode = mh_mode;
681         mh_mode = CRYPTO_MEM_CHECK_OFF;
682
683         lh_MEM_free(mh);
684         mh = NULL;
685
686         mh_mode = old_mh_mode;
687         CRYPTO_THREAD_unlock(malloc_lock);
688     }
689     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF);
690
691     /* Clean up locks etc */
692     CRYPTO_THREAD_cleanup_local(&appinfokey);
693     CRYPTO_THREAD_lock_free(malloc_lock);
694     CRYPTO_THREAD_lock_free(long_malloc_lock);
695     malloc_lock = NULL;
696     long_malloc_lock = NULL;
697
698     return ml.chunks == 0 ? 1 : 0;
699 }
700
701 # ifndef OPENSSL_NO_STDIO
702 int CRYPTO_mem_leaks_fp(FILE *fp)
703 {
704     BIO *b;
705     int ret;
706
707     /*
708      * Need to turn off memory checking when allocated BIOs ... especially as
709      * we're creating them at a time when we're trying to check we've not
710      * left anything un-free()'d!!
711      */
712     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
713     b = BIO_new(BIO_s_file());
714     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
715     if (b == NULL)
716         return -1;
717     BIO_set_fp(b, fp, BIO_NOCLOSE);
718     ret = CRYPTO_mem_leaks(b);
719     BIO_free(b);
720     return ret;
721 }
722 # endif
723
724 #endif