Android build fixes.
[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 "internal/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     CRYPTO_THREAD_ID cur;
288
289     if (mh_mode & CRYPTO_MEM_CHECK_ON) {
290         CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
291
292         cur = CRYPTO_THREAD_get_current_id();
293         CRYPTO_THREAD_read_lock(malloc_lock);
294
295         ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
296             || !CRYPTO_THREAD_compare_id(disabling_threadid, cur);
297
298         CRYPTO_THREAD_unlock(malloc_lock);
299     }
300     return (ret);
301 }
302
303 static int mem_cmp(const MEM *a, const MEM *b)
304 {
305 #ifdef _WIN64
306     const char *ap = (const char *)a->addr, *bp = (const char *)b->addr;
307     if (ap == bp)
308         return 0;
309     else if (ap > bp)
310         return 1;
311     else
312         return -1;
313 #else
314     return (const char *)a->addr - (const char *)b->addr;
315 #endif
316 }
317
318 static unsigned long mem_hash(const MEM *a)
319 {
320     size_t ret;
321
322     ret = (size_t)a->addr;
323
324     ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
325     return (ret);
326 }
327
328 /* returns 1 if there was an info to pop, 0 if the stack was empty. */
329 static int pop_info(void)
330 {
331     APP_INFO *current = NULL;
332
333     CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
334     current = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
335     if (current != NULL) {
336         APP_INFO *next = current->next;
337
338         if (next != NULL) {
339             next->references++;
340             CRYPTO_THREAD_set_local(&appinfokey, next);
341         } else {
342             CRYPTO_THREAD_set_local(&appinfokey, NULL);
343         }
344         if (--(current->references) <= 0) {
345             current->next = NULL;
346             if (next != NULL)
347                 next->references--;
348             OPENSSL_free(current);
349         }
350         return 1;
351     }
352     return 0;
353 }
354
355 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
356 {
357     APP_INFO *ami, *amim;
358     int ret = 0;
359
360     if (mem_check_on()) {
361         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
362
363         CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
364
365         if ((ami = OPENSSL_malloc(sizeof(*ami))) == NULL)
366             goto err;
367
368         ami->threadid = CRYPTO_THREAD_get_current_id();
369         ami->file = file;
370         ami->line = line;
371         ami->info = info;
372         ami->references = 1;
373         ami->next = NULL;
374
375         amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
376         CRYPTO_THREAD_set_local(&appinfokey, ami);
377
378         if (amim != NULL)
379             ami->next = amim;
380         ret = 1;
381  err:
382         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
383     }
384
385     return (ret);
386 }
387
388 int CRYPTO_mem_debug_pop(void)
389 {
390     int ret = 0;
391
392     if (mem_check_on()) {
393         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
394         ret = pop_info();
395         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
396     }
397     return (ret);
398 }
399
400 static unsigned long break_order_num = 0;
401
402 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int before_p,
403                              const char *file, int line)
404 {
405     MEM *m, *mm;
406     APP_INFO *amim;
407
408     switch (before_p & 127) {
409     case 0:
410         break;
411     case 1:
412         if (addr == NULL)
413             break;
414
415         if (mem_check_on()) {
416             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
417
418             CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
419
420             if ((m = OPENSSL_malloc(sizeof(*m))) == NULL) {
421                 OPENSSL_free(addr);
422                 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
423                 return;
424             }
425             if (mh == NULL) {
426                 if ((mh = lh_MEM_new(mem_hash, mem_cmp)) == NULL) {
427                     OPENSSL_free(addr);
428                     OPENSSL_free(m);
429                     addr = NULL;
430                     goto err;
431                 }
432             }
433
434             m->addr = addr;
435             m->file = file;
436             m->line = line;
437             m->num = num;
438             m->threadid = CRYPTO_THREAD_get_current_id();
439
440             if (order == break_order_num) {
441                 /* BREAK HERE */
442                 m->order = order;
443             }
444             m->order = order++;
445 # ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
446             m->array_siz = backtrace(m->array, OSSL_NELEM(m->array));
447 # endif
448             m->time = time(NULL);
449
450             amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
451             m->app_info = amim;
452             if (amim != NULL)
453                 amim->references++;
454
455             if ((mm = lh_MEM_insert(mh, m)) != NULL) {
456                 /* Not good, but don't sweat it */
457                 if (mm->app_info != NULL) {
458                     mm->app_info->references--;
459                 }
460                 OPENSSL_free(mm);
461             }
462  err:
463             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
464         }
465         break;
466     }
467     return;
468 }
469
470 void CRYPTO_mem_debug_free(void *addr, int before_p,
471         const char *file, int line)
472 {
473     MEM m, *mp;
474
475     switch (before_p) {
476     case 0:
477         if (addr == NULL)
478             break;
479
480         if (mem_check_on() && (mh != NULL)) {
481             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
482
483             m.addr = addr;
484             mp = lh_MEM_delete(mh, &m);
485             if (mp != NULL) {
486                 app_info_free(mp->app_info);
487                 OPENSSL_free(mp);
488             }
489
490             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
491         }
492         break;
493     case 1:
494         break;
495     }
496 }
497
498 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num,
499                               int before_p, const char *file, int line)
500 {
501     MEM m, *mp;
502
503     switch (before_p) {
504     case 0:
505         break;
506     case 1:
507         if (addr2 == NULL)
508             break;
509
510         if (addr1 == NULL) {
511             CRYPTO_mem_debug_malloc(addr2, num, 128 | before_p, file, line);
512             break;
513         }
514
515         if (mem_check_on()) {
516             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
517
518             m.addr = addr1;
519             mp = lh_MEM_delete(mh, &m);
520             if (mp != NULL) {
521                 mp->addr = addr2;
522                 mp->num = num;
523 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
524                 mp->array_siz = backtrace(mp->array, OSSL_NELEM(mp->array));
525 #endif
526                 (void)lh_MEM_insert(mh, mp);
527             }
528
529             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
530         }
531         break;
532     }
533     return;
534 }
535
536 typedef struct mem_leak_st {
537     BIO *bio;
538     int chunks;
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     lcl = localtime(&m->time);
563     BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
564                  lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
565     bufp += strlen(bufp);
566
567     BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
568                  m->order, m->file, m->line);
569     bufp += strlen(bufp);
570
571     tid.ltid = 0;
572     tid.tid = m->threadid;
573     BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ", tid.ltid);
574     bufp += strlen(bufp);
575
576     BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%p\n",
577                  m->num, m->addr);
578     bufp += strlen(bufp);
579
580     BIO_puts(l->bio, buf);
581
582     l->chunks++;
583     l->bytes += m->num;
584
585     amip = m->app_info;
586     ami_cnt = 0;
587
588     if (amip) {
589         ti = amip->threadid;
590
591         do {
592             int buf_len;
593             int info_len;
594
595             ami_cnt++;
596             memset(buf, '>', ami_cnt);
597             tid.ltid = 0;
598             tid.tid = amip->threadid;
599             BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
600                          " thread=%lu, file=%s, line=%d, info=\"",
601                          tid.ltid, amip->file,
602                          amip->line);
603             buf_len = strlen(buf);
604             info_len = strlen(amip->info);
605             if (128 - buf_len - 3 < info_len) {
606                 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
607                 buf_len = 128 - 3;
608             } else {
609                 OPENSSL_strlcpy(buf + buf_len, amip->info, sizeof buf - buf_len);
610                 buf_len = strlen(buf);
611             }
612             BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
613
614             BIO_puts(l->bio, buf);
615
616             amip = amip->next;
617         }
618         while (amip && CRYPTO_THREAD_compare_id(amip->threadid, ti));
619     }
620
621 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
622     {
623         size_t i;
624         char **strings = backtrace_symbols(m->array, m->array_siz);
625
626         for (i = 0; i < m->array_siz; i++)
627             fprintf(stderr, "##> %s\n", strings[i]);
628         free(strings);
629     }
630 #endif
631 }
632
633 IMPLEMENT_LHASH_DOALL_ARG_CONST(MEM, MEM_LEAK);
634
635 int CRYPTO_mem_leaks(BIO *b)
636 {
637     MEM_LEAK ml;
638
639     /*
640      * OPENSSL_cleanup() will free the ex_data locks so we can't have any
641      * ex_data hanging around
642      */
643     bio_free_ex_data(b);
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     if (mh != NULL)
656         lh_MEM_doall_MEM_LEAK(mh, print_leak, &ml);
657
658     if (ml.chunks != 0) {
659         BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks);
660     } else {
661         /*
662          * Make sure that, if we found no leaks, memory-leak debugging itself
663          * does not introduce memory leaks (which might irritate external
664          * debugging tools). (When someone enables leak checking, but does not
665          * call this function, we declare it to be their fault.)
666          */
667         int old_mh_mode;
668
669         CRYPTO_THREAD_write_lock(malloc_lock);
670
671         /*
672          * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses
673          * mem_check_on
674          */
675         old_mh_mode = mh_mode;
676         mh_mode = CRYPTO_MEM_CHECK_OFF;
677
678         lh_MEM_free(mh);
679         mh = NULL;
680
681         mh_mode = old_mh_mode;
682         CRYPTO_THREAD_unlock(malloc_lock);
683     }
684     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF);
685
686     /* Clean up locks etc */
687     CRYPTO_THREAD_cleanup_local(&appinfokey);
688     CRYPTO_THREAD_lock_free(malloc_lock);
689     CRYPTO_THREAD_lock_free(long_malloc_lock);
690     malloc_lock = NULL;
691     long_malloc_lock = NULL;
692
693     return ml.chunks == 0 ? 1 : 0;
694 }
695
696 # ifndef OPENSSL_NO_STDIO
697 int CRYPTO_mem_leaks_fp(FILE *fp)
698 {
699     BIO *b;
700     int ret;
701
702     /*
703      * Need to turn off memory checking when allocated BIOs ... especially as
704      * we're creating them at a time when we're trying to check we've not
705      * left anything un-free()'d!!
706      */
707     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
708     b = BIO_new(BIO_s_file());
709     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
710     if (b == NULL)
711         return -1;
712     BIO_set_fp(b, fp, BIO_NOCLOSE);
713     ret = CRYPTO_mem_leaks(b);
714     BIO_free(b);
715     return ret;
716 }
717 # endif
718
719 #endif