Fold threads.h into crypto.h making API public
[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 <openssl/crypto.h>
116 #include <openssl/buffer.h>
117 #include "internal/bio.h"
118 #include <openssl/lhash.h>
119
120 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
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_THREAD_ID 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 static CRYPTO_ONCE memdbg_init = CRYPTO_ONCE_STATIC_INIT;
159 static CRYPTO_RWLOCK *malloc_lock = NULL;
160 static CRYPTO_RWLOCK *long_malloc_lock = NULL;
161 static CRYPTO_THREAD_LOCAL appinfokey;
162
163 /* memory-block description */
164 struct mem_st {
165     void *addr;
166     int num;
167     const char *file;
168     int line;
169     CRYPTO_THREAD_ID threadid;
170     unsigned long order;
171     time_t time;
172     APP_INFO *app_info;
173 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
174     void *array[30];
175     size_t array_siz;
176 #endif
177 };
178
179 static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
180                                   * key); access requires MALLOC2 lock */
181
182 /* num_disable > 0 iff mh_mode == CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
183 static unsigned int num_disable = 0;
184
185 /*
186  * Valid iff num_disable > 0.  long_malloc_lock is locked exactly in this
187  * case (by the thread named in disabling_thread).
188  */
189 static CRYPTO_THREAD_ID disabling_threadid;
190
191 static void do_memdbg_init(void)
192 {
193     malloc_lock = CRYPTO_THREAD_lock_new();
194     long_malloc_lock = CRYPTO_THREAD_lock_new();
195     CRYPTO_THREAD_init_local(&appinfokey, NULL);
196 }
197
198 static void app_info_free(APP_INFO *inf)
199 {
200     if (!inf)
201         return;
202     if (--(inf->references) <= 0) {
203         app_info_free(inf->next);
204         OPENSSL_free(inf);
205     }
206 }
207 #endif
208
209 int CRYPTO_mem_ctrl(int mode)
210 {
211 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
212     return mode - mode;
213 #else
214     int ret = mh_mode;
215
216     CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
217
218     CRYPTO_THREAD_write_lock(malloc_lock);
219     switch (mode) {
220     default:
221         break;
222
223     case CRYPTO_MEM_CHECK_ON:
224         mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
225         num_disable = 0;
226         break;
227
228     case CRYPTO_MEM_CHECK_OFF:
229         mh_mode = 0;
230         num_disable = 0;
231         break;
232
233     /* switch off temporarily (for library-internal use): */
234     case CRYPTO_MEM_CHECK_DISABLE:
235         if (mh_mode & CRYPTO_MEM_CHECK_ON) {
236             CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
237             /* see if we don't have long_malloc_lock already */
238             if (!num_disable
239                 || !CRYPTO_THREAD_compare_id(disabling_threadid, cur)) {
240                 /*
241                  * Long-time lock long_malloc_lock must not be claimed
242                  * while we're holding malloc_lock, or we'll deadlock
243                  * if somebody else holds long_malloc_lock (and cannot
244                  * release it because we block entry to this function). Give
245                  * them a chance, first, and then claim the locks in
246                  * appropriate order (long-time lock first).
247                  */
248                 CRYPTO_THREAD_unlock(malloc_lock);
249                 /*
250                  * Note that after we have waited for long_malloc_lock and
251                  * malloc_lock, we'll still be in the right "case" and
252                  * "if" branch because MemCheck_start and MemCheck_stop may
253                  * never be used while there are multiple OpenSSL threads.
254                  */
255                 CRYPTO_THREAD_write_lock(long_malloc_lock);
256                 CRYPTO_THREAD_write_lock(malloc_lock);
257                 mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
258                 disabling_threadid = cur;
259             }
260             num_disable++;
261         }
262         break;
263
264     case CRYPTO_MEM_CHECK_ENABLE:
265         if (mh_mode & CRYPTO_MEM_CHECK_ON) {
266             if (num_disable) {  /* always true, or something is going wrong */
267                 num_disable--;
268                 if (num_disable == 0) {
269                     mh_mode |= CRYPTO_MEM_CHECK_ENABLE;
270                     CRYPTO_THREAD_unlock(long_malloc_lock);
271                 }
272             }
273         }
274         break;
275     }
276     CRYPTO_THREAD_unlock(malloc_lock);
277     return (ret);
278 #endif
279 }
280
281 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
282
283 static int mem_check_on(void)
284 {
285     int ret = 0;
286     CRYPTO_THREAD_ID cur;
287
288     if (mh_mode & CRYPTO_MEM_CHECK_ON) {
289         CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
290
291         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     long bytes;
539 } MEM_LEAK;
540
541 static void print_leak(const MEM *m, MEM_LEAK *l)
542 {
543     char buf[1024];
544     char *bufp = buf;
545     APP_INFO *amip;
546     int ami_cnt;
547     struct tm *lcl = NULL;
548     /*
549      * Convert between CRYPTO_THREAD_ID (which could be anything at all) and
550      * a long. This may not be meaningful depending on what CRYPTO_THREAD_ID is
551      * but hopefully should give something sensible on most platforms
552      */
553     union {
554         CRYPTO_THREAD_ID tid;
555         unsigned long ltid;
556     } tid;
557     CRYPTO_THREAD_ID ti;
558
559 #define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))
560
561     lcl = localtime(&m->time);
562     BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
563                  lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
564     bufp += strlen(bufp);
565
566     BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
567                  m->order, m->file, m->line);
568     bufp += strlen(bufp);
569
570     tid.ltid = 0;
571     tid.tid = m->threadid;
572     BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ", tid.ltid);
573     bufp += strlen(bufp);
574
575     BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%p\n",
576                  m->num, m->addr);
577     bufp += strlen(bufp);
578
579     BIO_puts(l->bio, buf);
580
581     l->chunks++;
582     l->bytes += m->num;
583
584     amip = m->app_info;
585     ami_cnt = 0;
586
587     if (amip) {
588         ti = amip->threadid;
589
590         do {
591             int buf_len;
592             int info_len;
593
594             ami_cnt++;
595             memset(buf, '>', ami_cnt);
596             tid.ltid = 0;
597             tid.tid = amip->threadid;
598             BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
599                          " thread=%lu, file=%s, line=%d, info=\"",
600                          tid.ltid, 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_THREAD_compare_id(amip->threadid, ti));
618     }
619
620 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
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     /*
639      * OPENSSL_cleanup() will free the ex_data locks so we can't have any
640      * ex_data hanging around
641      */
642     bio_free_ex_data(b);
643
644     /* Ensure all resources are released */
645     OPENSSL_cleanup();
646
647     CRYPTO_THREAD_run_once(&memdbg_init, do_memdbg_init);
648
649     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
650
651     ml.bio = b;
652     ml.bytes = 0;
653     ml.chunks = 0;
654     if (mh != NULL)
655         lh_MEM_doall_MEM_LEAK(mh, print_leak, &ml);
656
657     if (ml.chunks != 0) {
658         BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks);
659     } else {
660         /*
661          * Make sure that, if we found no leaks, memory-leak debugging itself
662          * does not introduce memory leaks (which might irritate external
663          * debugging tools). (When someone enables leak checking, but does not
664          * call this function, we declare it to be their fault.)
665          */
666         int old_mh_mode;
667
668         CRYPTO_THREAD_write_lock(malloc_lock);
669
670         /*
671          * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses
672          * mem_check_on
673          */
674         old_mh_mode = mh_mode;
675         mh_mode = CRYPTO_MEM_CHECK_OFF;
676
677         lh_MEM_free(mh);
678         mh = NULL;
679
680         mh_mode = old_mh_mode;
681         CRYPTO_THREAD_unlock(malloc_lock);
682     }
683     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF);
684
685     /* Clean up locks etc */
686     CRYPTO_THREAD_cleanup_local(&appinfokey);
687     CRYPTO_THREAD_lock_free(malloc_lock);
688     CRYPTO_THREAD_lock_free(long_malloc_lock);
689     malloc_lock = NULL;
690     long_malloc_lock = NULL;
691
692     return ml.chunks == 0 ? 1 : 0;
693 }
694
695 # ifndef OPENSSL_NO_STDIO
696 int CRYPTO_mem_leaks_fp(FILE *fp)
697 {
698     BIO *b;
699     int ret;
700
701     /*
702      * Need to turn off memory checking when allocated BIOs ... especially as
703      * we're creating them at a time when we're trying to check we've not
704      * left anything un-free()'d!!
705      */
706     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
707     b = BIO_new(BIO_s_file());
708     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
709     if (b == NULL)
710         return -1;
711     BIO_set_fp(b, fp, BIO_NOCLOSE);
712     ret = CRYPTO_mem_leaks(b);
713     BIO_free(b);
714     return ret;
715 }
716 # endif
717
718 #endif