Check for missing DSA parameters.
[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 static int mh_mode = CRYPTO_MEM_CHECK_OFF;
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
137 static unsigned long order = 0; /* number of memory requests */
138
139 DECLARE_LHASH_OF(MEM);
140 static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
141                                   * key); access requires MALLOC2 lock */
142
143 typedef struct app_mem_info_st
144 /*-
145  * For application-defined information (static C-string `info')
146  * to be displayed in memory leak list.
147  * Each thread has its own stack.  For applications, there is
148  *   OPENSSL_mem_debug_push("...")     to push an entry,
149  *   OPENSSL_mem_debug_pop()     to pop an entry,
150  */
151 {
152     CRYPTO_THREADID threadid;
153     const char *file;
154     int line;
155     const char *info;
156     struct app_mem_info_st *next; /* tail of thread's stack */
157     int references;
158 } APP_INFO;
159
160 static void app_info_free(APP_INFO *);
161
162 DECLARE_LHASH_OF(APP_INFO);
163 static LHASH_OF(APP_INFO) *amih = NULL; /* hash-table with those
164                                          * app_mem_info_st's that are at the
165                                          * top of their thread's stack (with
166                                          * `thread' as key); access requires
167                                          * MALLOC2 lock */
168
169 typedef struct mem_st
170 /* memory-block description */
171 {
172     void *addr;
173     int num;
174     const char *file;
175     int line;
176     CRYPTO_THREADID threadid;
177     unsigned long order;
178     time_t time;
179     APP_INFO *app_info;
180 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
181     void *array[30];
182     size_t array_siz;
183 #endif
184 } MEM;
185
186 static long options =           /* extra information to be recorded */
187 #if defined(CRYPTO_MDEBUG_TIME) || defined(CRYPTO_MDEBUG_ALL)
188     V_CRYPTO_MDEBUG_TIME |
189 #endif
190 #if defined(CRYPTO_MDEBUG_THREAD) || defined(CRYPTO_MDEBUG_ALL)
191     V_CRYPTO_MDEBUG_THREAD |
192 #endif
193     0;
194
195 static unsigned int num_disable = 0; /* num_disable > 0 iff mh_mode ==
196                                       * CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
197
198 /*
199  * Valid iff num_disable > 0.  CRYPTO_LOCK_MALLOC2 is locked exactly in this
200  * case (by the thread named in disabling_thread).
201  */
202 static CRYPTO_THREADID disabling_threadid;
203
204 static void app_info_free(APP_INFO *inf)
205 {
206     if (!inf)
207         return;
208     if (--(inf->references) <= 0) {
209         app_info_free(inf->next);
210         OPENSSL_free(inf);
211     }
212 }
213
214 int CRYPTO_mem_ctrl(int mode)
215 {
216     int ret = mh_mode;
217
218     CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
219     switch (mode) {
220         /*
221          * for applications (not to be called while multiple threads use the
222          * library):
223          */
224     case CRYPTO_MEM_CHECK_ON:  /* aka MemCheck_start() */
225         mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
226         num_disable = 0;
227         break;
228     case CRYPTO_MEM_CHECK_OFF: /* aka MemCheck_stop() */
229         mh_mode = 0;
230         num_disable = 0;        /* should be true *before* MemCheck_stop is
231                                  * used, or there'll be a lot of confusion */
232         break;
233
234         /* switch off temporarily (for library-internal use): */
235     case CRYPTO_MEM_CHECK_DISABLE: /* aka MemCheck_off() */
236         if (mh_mode & CRYPTO_MEM_CHECK_ON) {
237             CRYPTO_THREADID cur;
238             CRYPTO_THREADID_current(&cur);
239             /* see if we don't have the MALLOC2 lock already */
240             if (!num_disable
241                 || CRYPTO_THREADID_cmp(&disabling_threadid, &cur)) {
242                 /*
243                  * Long-time lock CRYPTO_LOCK_MALLOC2 must not be claimed
244                  * while we're holding CRYPTO_LOCK_MALLOC, or we'll deadlock
245                  * if somebody else holds CRYPTO_LOCK_MALLOC2 (and cannot
246                  * release it because we block entry to this function). Give
247                  * them a chance, first, and then claim the locks in
248                  * appropriate order (long-time lock first).
249                  */
250                 CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
251                 /*
252                  * Note that after we have waited for CRYPTO_LOCK_MALLOC2 and
253                  * CRYPTO_LOCK_MALLOC, we'll still be in the right "case" and
254                  * "if" branch because MemCheck_start and MemCheck_stop may
255                  * never be used while there are multiple OpenSSL threads.
256                  */
257                 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC2);
258                 CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
259                 mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
260                 CRYPTO_THREADID_cpy(&disabling_threadid, &cur);
261             }
262             num_disable++;
263         }
264         break;
265     case CRYPTO_MEM_CHECK_ENABLE: /* aka MemCheck_on() */
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_w_unlock(CRYPTO_LOCK_MALLOC2);
272                 }
273             }
274         }
275         break;
276
277     default:
278         break;
279     }
280     CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
281     return (ret);
282 }
283
284 int CRYPTO_is_mem_check_on(void)
285 {
286     int ret = 0;
287
288     if (mh_mode & CRYPTO_MEM_CHECK_ON) {
289         CRYPTO_THREADID cur;
290         CRYPTO_THREADID_current(&cur);
291         CRYPTO_r_lock(CRYPTO_LOCK_MALLOC);
292
293         ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
294             || CRYPTO_THREADID_cmp(&disabling_threadid, &cur);
295
296         CRYPTO_r_unlock(CRYPTO_LOCK_MALLOC);
297     }
298     return (ret);
299 }
300
301 void CRYPTO_dbg_set_options(long bits)
302 {
303     options = bits;
304 }
305
306 long CRYPTO_dbg_get_options(void)
307 {
308     return options;
309 }
310
311 static int mem_cmp(const MEM *a, const MEM *b)
312 {
313 #ifdef _WIN64
314     const char *ap = (const char *)a->addr, *bp = (const char *)b->addr;
315     if (ap == bp)
316         return 0;
317     else if (ap > bp)
318         return 1;
319     else
320         return -1;
321 #else
322     return (const char *)a->addr - (const char *)b->addr;
323 #endif
324 }
325
326 static IMPLEMENT_LHASH_COMP_FN(mem, MEM)
327
328 static unsigned long mem_hash(const MEM *a)
329 {
330     size_t ret;
331
332     ret = (size_t)a->addr;
333
334     ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
335     return (ret);
336 }
337
338 static IMPLEMENT_LHASH_HASH_FN(mem, MEM)
339
340 /* static int app_info_cmp(APP_INFO *a, APP_INFO *b) */
341 static int app_info_cmp(const void *a_void, const void *b_void)
342 {
343     return CRYPTO_THREADID_cmp(&((const APP_INFO *)a_void)->threadid,
344                                &((const APP_INFO *)b_void)->threadid);
345 }
346
347 static IMPLEMENT_LHASH_COMP_FN(app_info, APP_INFO)
348
349 static unsigned long app_info_hash(const APP_INFO *a)
350 {
351     unsigned long ret;
352
353     ret = CRYPTO_THREADID_hash(&a->threadid);
354     /* This is left in as a "who am I to question legacy?" measure */
355     ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
356     return (ret);
357 }
358
359 static IMPLEMENT_LHASH_HASH_FN(app_info, APP_INFO)
360
361 static APP_INFO *pop_info(void)
362 {
363     APP_INFO tmp;
364     APP_INFO *ret = NULL;
365
366     if (amih != NULL) {
367         CRYPTO_THREADID_current(&tmp.threadid);
368         if ((ret = lh_APP_INFO_delete(amih, &tmp)) != NULL) {
369             APP_INFO *next = ret->next;
370
371             if (next != NULL) {
372                 next->references++;
373                 (void)lh_APP_INFO_insert(amih, next);
374             }
375             if (--(ret->references) <= 0) {
376                 ret->next = NULL;
377                 if (next != NULL)
378                     next->references--;
379                 OPENSSL_free(ret);
380             }
381         }
382     }
383     return (ret);
384 }
385
386 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
387 {
388     APP_INFO *ami, *amim;
389     int ret = 0;
390
391     if (is_MemCheck_on()) {
392         MemCheck_off();         /* obtain MALLOC2 lock */
393
394         if ((ami = OPENSSL_malloc(sizeof(*ami))) == NULL) {
395             ret = 0;
396             goto err;
397         }
398         if (amih == NULL) {
399             if ((amih = lh_APP_INFO_new()) == NULL) {
400                 OPENSSL_free(ami);
401                 ret = 0;
402                 goto err;
403             }
404         }
405
406         CRYPTO_THREADID_current(&ami->threadid);
407         ami->file = file;
408         ami->line = line;
409         ami->info = info;
410         ami->references = 1;
411         ami->next = NULL;
412
413         if ((amim = lh_APP_INFO_insert(amih, ami)) != NULL)
414             ami->next = amim;
415  err:
416         MemCheck_on();          /* release MALLOC2 lock */
417     }
418
419     return (ret);
420 }
421
422 int CRYPTO_mem_debug_pop(void)
423 {
424     int ret = 0;
425
426     if (is_MemCheck_on()) {     /* _must_ be true, or something went severely
427                                  * wrong */
428         MemCheck_off();         /* obtain MALLOC2 lock */
429
430         ret = (pop_info() != NULL);
431
432         MemCheck_on();          /* release MALLOC2 lock */
433     }
434     return (ret);
435 }
436
437 static unsigned long break_order_num = 0;
438 void CRYPTO_dbg_malloc(void *addr, size_t num, const char *file, int line,
439                        int before_p)
440 {
441     MEM *m, *mm;
442     APP_INFO tmp, *amim;
443
444     switch (before_p & 127) {
445     case 0:
446         break;
447     case 1:
448         if (addr == NULL)
449             break;
450
451         if (is_MemCheck_on()) {
452             MemCheck_off();     /* make sure we hold MALLOC2 lock */
453             if ((m = OPENSSL_malloc(sizeof(*m))) == NULL) {
454                 OPENSSL_free(addr);
455                 MemCheck_on();  /* release MALLOC2 lock if num_disabled drops
456                                  * to 0 */
457                 return;
458             }
459             if (mh == NULL) {
460                 if ((mh = lh_MEM_new()) == NULL) {
461                     OPENSSL_free(addr);
462                     OPENSSL_free(m);
463                     addr = NULL;
464                     goto err;
465                 }
466             }
467
468             m->addr = addr;
469             m->file = file;
470             m->line = line;
471             m->num = num;
472             if (options & V_CRYPTO_MDEBUG_THREAD)
473                 CRYPTO_THREADID_current(&m->threadid);
474             else
475                 memset(&m->threadid, 0, sizeof(m->threadid));
476
477             if (order == break_order_num) {
478                 /* BREAK HERE */
479                 m->order = order;
480             }
481             m->order = order++;
482             if (options & V_CRYPTO_MDEBUG_TIME)
483                 m->time = time(NULL);
484             else
485                 m->time = 0;
486 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
487             m->array_siz = backtrace(m->array, OSSL_NELEM(m->array));
488 #endif
489
490             CRYPTO_THREADID_current(&tmp.threadid);
491             m->app_info = NULL;
492             if (amih != NULL
493                 && (amim = lh_APP_INFO_retrieve(amih, &tmp)) != NULL) {
494                 m->app_info = amim;
495                 amim->references++;
496             }
497
498             if ((mm = lh_MEM_insert(mh, m)) != NULL) {
499                 /* Not good, but don't sweat it */
500                 if (mm->app_info != NULL) {
501                     mm->app_info->references--;
502                 }
503                 OPENSSL_free(mm);
504             }
505  err:
506             MemCheck_on();      /* release MALLOC2 lock if num_disabled drops
507                                  * to 0 */
508         }
509         break;
510     }
511     return;
512 }
513
514 void CRYPTO_dbg_free(void *addr, int before_p)
515 {
516     MEM m, *mp;
517
518     switch (before_p) {
519     case 0:
520         if (addr == NULL)
521             break;
522
523         if (is_MemCheck_on() && (mh != NULL)) {
524             MemCheck_off();     /* make sure we hold MALLOC2 lock */
525
526             m.addr = addr;
527             mp = lh_MEM_delete(mh, &m);
528             if (mp != NULL) {
529                 app_info_free(mp->app_info);
530                 OPENSSL_free(mp);
531             }
532
533             MemCheck_on();      /* release MALLOC2 lock if num_disabled drops
534                                  * to 0 */
535         }
536         break;
537     case 1:
538         break;
539     }
540 }
541
542 void CRYPTO_dbg_realloc(void *addr1, void *addr2, size_t num,
543                         const char *file, int line, int before_p)
544 {
545     MEM m, *mp;
546
547     switch (before_p) {
548     case 0:
549         break;
550     case 1:
551         if (addr2 == NULL)
552             break;
553
554         if (addr1 == NULL) {
555             CRYPTO_dbg_malloc(addr2, num, file, line, 128 | before_p);
556             break;
557         }
558
559         if (is_MemCheck_on()) {
560             MemCheck_off();     /* make sure we hold MALLOC2 lock */
561
562             m.addr = addr1;
563             mp = lh_MEM_delete(mh, &m);
564             if (mp != NULL) {
565                 mp->addr = addr2;
566                 mp->num = num;
567 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
568                 mp->array_siz = backtrace(mp->array, OSSL_NELEM(mp->array));
569 #endif
570                 (void)lh_MEM_insert(mh, mp);
571             }
572
573             MemCheck_on();      /* release MALLOC2 lock if num_disabled drops
574                                  * to 0 */
575         }
576         break;
577     }
578     return;
579 }
580
581 typedef struct mem_leak_st {
582     BIO *bio;
583     int chunks;
584     int seen;
585     long bytes;
586 } MEM_LEAK;
587
588 static void print_leak_doall_arg(const MEM *m, MEM_LEAK *l)
589 {
590     char buf[1024];
591     char *bufp = buf;
592     APP_INFO *amip;
593     int ami_cnt;
594     struct tm *lcl = NULL;
595     CRYPTO_THREADID ti;
596
597 #define BUF_REMAIN (sizeof buf - (size_t)(bufp - buf))
598
599     /* Is one "leak" the BIO we were given? */
600     if (m->addr == (char *)l->bio) {
601         l->seen = 1;
602         return;
603     }
604
605     if (options & V_CRYPTO_MDEBUG_TIME) {
606         lcl = localtime(&m->time);
607
608         BIO_snprintf(bufp, BUF_REMAIN, "[%02d:%02d:%02d] ",
609                      lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
610         bufp += strlen(bufp);
611     }
612
613     BIO_snprintf(bufp, BUF_REMAIN, "%5lu file=%s, line=%d, ",
614                  m->order, m->file, m->line);
615     bufp += strlen(bufp);
616
617     if (options & V_CRYPTO_MDEBUG_THREAD) {
618         BIO_snprintf(bufp, BUF_REMAIN, "thread=%lu, ",
619                      CRYPTO_THREADID_hash(&m->threadid));
620         bufp += strlen(bufp);
621     }
622
623     BIO_snprintf(bufp, BUF_REMAIN, "number=%d, address=%p\n",
624                  m->num, m->addr);
625     bufp += strlen(bufp);
626
627     BIO_puts(l->bio, buf);
628
629     l->chunks++;
630     l->bytes += m->num;
631
632     amip = m->app_info;
633     ami_cnt = 0;
634     if (amip) {
635         CRYPTO_THREADID_cpy(&ti, &amip->threadid);
636
637         do {
638             int buf_len;
639             int info_len;
640
641             ami_cnt++;
642             memset(buf, '>', ami_cnt);
643             BIO_snprintf(buf + ami_cnt, sizeof buf - ami_cnt,
644                          " thread=%lu, file=%s, line=%d, info=\"",
645                          CRYPTO_THREADID_hash(&amip->threadid), amip->file,
646                          amip->line);
647             buf_len = strlen(buf);
648             info_len = strlen(amip->info);
649             if (128 - buf_len - 3 < info_len) {
650                 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
651                 buf_len = 128 - 3;
652             } else {
653                 OPENSSL_strlcpy(buf + buf_len, amip->info, sizeof buf - buf_len);
654                 buf_len = strlen(buf);
655             }
656             BIO_snprintf(buf + buf_len, sizeof buf - buf_len, "\"\n");
657
658             BIO_puts(l->bio, buf);
659
660             amip = amip->next;
661         }
662         while (amip && !CRYPTO_THREADID_cmp(&amip->threadid, &ti));
663     }
664
665 #if defined(CRYPTO_MDEBUG_BACKTRACE) && defined(__GNUC__)
666     {
667         size_t i;
668         char **strings = backtrace_symbols(m->array, m->array_siz);
669         for (i = 0; i < m->array_siz; i++)
670             fprintf(stderr, "##> %s\n", strings[i]);
671
672         free(strings);
673     }
674 #endif
675 }
676
677 static IMPLEMENT_LHASH_DOALL_ARG_FN(print_leak, const MEM, MEM_LEAK)
678
679 void CRYPTO_mem_leaks(BIO *b)
680 {
681     MEM_LEAK ml;
682
683     if (mh == NULL && amih == NULL)
684         return;
685
686     MemCheck_off();             /* obtain MALLOC2 lock */
687
688     ml.bio = b;
689     ml.bytes = 0;
690     ml.chunks = 0;
691     ml.seen = 0;
692     if (mh != NULL)
693         lh_MEM_doall_arg(mh, LHASH_DOALL_ARG_FN(print_leak), MEM_LEAK, &ml);
694     /* Don't count the BIO that was passed in as a "leak" */
695     if (ml.seen && ml.chunks >= 1 && ml.bytes >= (int)sizeof (*b)) {
696         ml.chunks--;
697         ml.bytes -= (int)sizeof (*b);
698     }
699     if (ml.chunks != 0) {
700         BIO_printf(b, "%ld bytes leaked in %d chunks\n", ml.bytes, ml.chunks);
701 #ifdef CRYPTO_MDEBUG_ABORT
702         abort();
703 #endif
704     } else {
705         /*
706          * Make sure that, if we found no leaks, memory-leak debugging itself
707          * does not introduce memory leaks (which might irritate external
708          * debugging tools). (When someone enables leak checking, but does not
709          * call this function, we declare it to be their fault.) XXX This
710          * should be in CRYPTO_mem_leaks_cb, and CRYPTO_mem_leaks should be
711          * implemented by using CRYPTO_mem_leaks_cb. (Also there should be a
712          * variant of lh_doall_arg that takes a function pointer instead of a
713          * void *; this would obviate the ugly and illegal void_fn_to_char
714          * kludge in CRYPTO_mem_leaks_cb. Otherwise the code police will come
715          * and get us.)
716          */
717         int old_mh_mode;
718
719         CRYPTO_w_lock(CRYPTO_LOCK_MALLOC);
720
721         /*
722          * avoid deadlock when lh_free() uses CRYPTO_dbg_free(), which uses
723          * CRYPTO_is_mem_check_on
724          */
725         old_mh_mode = mh_mode;
726         mh_mode = CRYPTO_MEM_CHECK_OFF;
727
728         lh_MEM_free(mh);
729         mh = NULL;
730         if (amih != NULL) {
731             if (lh_APP_INFO_num_items(amih) == 0) {
732                 lh_APP_INFO_free(amih);
733                 amih = NULL;
734             }
735         }
736
737         mh_mode = old_mh_mode;
738         CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC);
739     }
740     MemCheck_on();              /* release MALLOC2 lock */
741 }
742
743 #ifndef OPENSSL_NO_STDIO
744 void CRYPTO_mem_leaks_fp(FILE *fp)
745 {
746     BIO *b;
747
748     if (mh == NULL)
749         return;
750     /*
751      * Need to turn off memory checking when allocated BIOs ... especially as
752      * we're creating them at a time when we're trying to check we've not
753      * left anything un-free()'d!!
754      */
755     MemCheck_off();
756     b = BIO_new(BIO_s_file());
757     MemCheck_on();
758     if (b == NULL)
759         return;
760     BIO_set_fp(b, fp, BIO_NOCLOSE);
761     CRYPTO_mem_leaks(b);
762     BIO_free(b);
763 }
764 #endif
765
766 /*
767  * FIXME: We really don't allow much to the callback.  For example, it has no
768  * chance of reaching the info stack for the item it processes.  Should it
769  * really be this way? -- Richard Levitte
770  */
771 /*
772  * NB: The prototypes have been typedef'd to CRYPTO_MEM_LEAK_CB inside
773  * crypto.h If this code is restructured, remove the callback type if it is
774  * no longer needed. -- Geoff Thorpe
775  */
776
777 /*
778  * Can't pass CRYPTO_MEM_LEAK_CB directly to lh_MEM_doall_arg because it is a
779  * function pointer and conversion to void * is prohibited. Instead pass its
780  * address
781  */
782
783 typedef CRYPTO_MEM_LEAK_CB *PCRYPTO_MEM_LEAK_CB;
784
785 static void cb_leak_doall_arg(const MEM *m, PCRYPTO_MEM_LEAK_CB *cb)
786 {
787     (*cb) (m->order, m->file, m->line, m->num, m->addr);
788 }
789
790 static IMPLEMENT_LHASH_DOALL_ARG_FN(cb_leak, const MEM, PCRYPTO_MEM_LEAK_CB)
791
792 void CRYPTO_mem_leaks_cb(CRYPTO_MEM_LEAK_CB *cb)
793 {
794     if (mh == NULL)
795         return;
796     CRYPTO_w_lock(CRYPTO_LOCK_MALLOC2);
797     lh_MEM_doall_arg(mh, LHASH_DOALL_ARG_FN(cb_leak), PCRYPTO_MEM_LEAK_CB,
798                      &cb);
799     CRYPTO_w_unlock(CRYPTO_LOCK_MALLOC2);
800 }