Undo commit d420ac2
[openssl.git] / crypto / mem_dbg.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <time.h>
13 #include "internal/cryptlib.h"
14 #include "internal/thread_once.h"
15 #include <openssl/crypto.h>
16 #include <openssl/buffer.h>
17 #include "internal/bio.h"
18 #include <openssl/lhash.h>
19
20 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
21 # include <execinfo.h>
22 #endif
23
24 /*
25  * The state changes to CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE when
26  * the application asks for it (usually after library initialisation for
27  * which no book-keeping is desired). State CRYPTO_MEM_CHECK_ON exists only
28  * temporarily when the library thinks that certain allocations should not be
29  * checked (e.g. the data structures used for memory checking).  It is not
30  * suitable as an initial state: the library will unexpectedly enable memory
31  * checking when it executes one of those sections that want to disable
32  * checking temporarily. State CRYPTO_MEM_CHECK_ENABLE without ..._ON makes
33  * no sense whatsoever.
34  */
35 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
36 static int mh_mode = CRYPTO_MEM_CHECK_OFF;
37 #endif
38
39 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
40 static unsigned long order = 0; /* number of memory requests */
41
42 /*-
43  * For application-defined information (static C-string `info')
44  * to be displayed in memory leak list.
45  * Each thread has its own stack.  For applications, there is
46  *   OPENSSL_mem_debug_push("...")     to push an entry,
47  *   OPENSSL_mem_debug_pop()     to pop an entry,
48  */
49 struct app_mem_info_st {
50     CRYPTO_THREAD_ID threadid;
51     const char *file;
52     int line;
53     const char *info;
54     struct app_mem_info_st *next; /* tail of thread's stack */
55     int references;
56 };
57
58 static CRYPTO_ONCE memdbg_init = CRYPTO_ONCE_STATIC_INIT;
59 static CRYPTO_RWLOCK *malloc_lock = NULL;
60 static CRYPTO_RWLOCK *long_malloc_lock = NULL;
61 static CRYPTO_THREAD_LOCAL appinfokey;
62
63 /* memory-block description */
64 struct mem_st {
65     void *addr;
66     int num;
67     const char *file;
68     int line;
69     CRYPTO_THREAD_ID threadid;
70     unsigned long order;
71     time_t time;
72     APP_INFO *app_info;
73 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
74     void *array[30];
75     size_t array_siz;
76 #endif
77 };
78
79 static LHASH_OF(MEM) *mh = NULL; /* hash-table of memory requests (address as
80                                   * key); access requires MALLOC2 lock */
81
82 /* num_disable > 0 iff mh_mode == CRYPTO_MEM_CHECK_ON (w/o ..._ENABLE) */
83 static unsigned int num_disable = 0;
84
85 /*
86  * Valid iff num_disable > 0.  long_malloc_lock is locked exactly in this
87  * case (by the thread named in disabling_thread).
88  */
89 static CRYPTO_THREAD_ID disabling_threadid;
90
91 DEFINE_RUN_ONCE_STATIC(do_memdbg_init)
92 {
93     malloc_lock = CRYPTO_THREAD_lock_new();
94     long_malloc_lock = CRYPTO_THREAD_lock_new();
95     if (malloc_lock == NULL || long_malloc_lock == NULL
96         || !CRYPTO_THREAD_init_local(&appinfokey, NULL)) {
97         CRYPTO_THREAD_lock_free(malloc_lock);
98         malloc_lock = NULL;
99         CRYPTO_THREAD_lock_free(long_malloc_lock);
100         long_malloc_lock = NULL;
101         return 0;
102     }
103     return 1;
104 }
105
106 static void app_info_free(APP_INFO *inf)
107 {
108     if (!inf)
109         return;
110     if (--(inf->references) <= 0) {
111         app_info_free(inf->next);
112         OPENSSL_free(inf);
113     }
114 }
115 #endif
116
117 int CRYPTO_mem_ctrl(int mode)
118 {
119 #ifdef OPENSSL_NO_CRYPTO_MDEBUG
120     return mode - mode;
121 #else
122     int ret = mh_mode;
123
124     if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
125         return -1;
126
127     CRYPTO_THREAD_write_lock(malloc_lock);
128     switch (mode) {
129     default:
130         break;
131
132     case CRYPTO_MEM_CHECK_ON:
133         mh_mode = CRYPTO_MEM_CHECK_ON | CRYPTO_MEM_CHECK_ENABLE;
134         num_disable = 0;
135         break;
136
137     case CRYPTO_MEM_CHECK_OFF:
138         mh_mode = 0;
139         num_disable = 0;
140         break;
141
142     /* switch off temporarily (for library-internal use): */
143     case CRYPTO_MEM_CHECK_DISABLE:
144         if (mh_mode & CRYPTO_MEM_CHECK_ON) {
145             CRYPTO_THREAD_ID cur = CRYPTO_THREAD_get_current_id();
146             /* see if we don't have long_malloc_lock already */
147             if (!num_disable
148                 || !CRYPTO_THREAD_compare_id(disabling_threadid, cur)) {
149                 /*
150                  * Long-time lock long_malloc_lock must not be claimed
151                  * while we're holding malloc_lock, or we'll deadlock
152                  * if somebody else holds long_malloc_lock (and cannot
153                  * release it because we block entry to this function). Give
154                  * them a chance, first, and then claim the locks in
155                  * appropriate order (long-time lock first).
156                  */
157                 CRYPTO_THREAD_unlock(malloc_lock);
158                 /*
159                  * Note that after we have waited for long_malloc_lock and
160                  * malloc_lock, we'll still be in the right "case" and
161                  * "if" branch because MemCheck_start and MemCheck_stop may
162                  * never be used while there are multiple OpenSSL threads.
163                  */
164                 CRYPTO_THREAD_write_lock(long_malloc_lock);
165                 CRYPTO_THREAD_write_lock(malloc_lock);
166                 mh_mode &= ~CRYPTO_MEM_CHECK_ENABLE;
167                 disabling_threadid = cur;
168             }
169             num_disable++;
170         }
171         break;
172
173     case CRYPTO_MEM_CHECK_ENABLE:
174         if (mh_mode & CRYPTO_MEM_CHECK_ON) {
175             if (num_disable) {  /* always true, or something is going wrong */
176                 num_disable--;
177                 if (num_disable == 0) {
178                     mh_mode |= CRYPTO_MEM_CHECK_ENABLE;
179                     CRYPTO_THREAD_unlock(long_malloc_lock);
180                 }
181             }
182         }
183         break;
184     }
185     CRYPTO_THREAD_unlock(malloc_lock);
186     return (ret);
187 #endif
188 }
189
190 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
191
192 static int mem_check_on(void)
193 {
194     int ret = 0;
195     CRYPTO_THREAD_ID cur;
196
197     if (mh_mode & CRYPTO_MEM_CHECK_ON) {
198         if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
199             return 0;
200
201         cur = CRYPTO_THREAD_get_current_id();
202         CRYPTO_THREAD_read_lock(malloc_lock);
203
204         ret = (mh_mode & CRYPTO_MEM_CHECK_ENABLE)
205             || !CRYPTO_THREAD_compare_id(disabling_threadid, cur);
206
207         CRYPTO_THREAD_unlock(malloc_lock);
208     }
209     return (ret);
210 }
211
212 static int mem_cmp(const MEM *a, const MEM *b)
213 {
214 #ifdef _WIN64
215     const char *ap = (const char *)a->addr, *bp = (const char *)b->addr;
216     if (ap == bp)
217         return 0;
218     else if (ap > bp)
219         return 1;
220     else
221         return -1;
222 #else
223     return (const char *)a->addr - (const char *)b->addr;
224 #endif
225 }
226
227 static unsigned long mem_hash(const MEM *a)
228 {
229     size_t ret;
230
231     ret = (size_t)a->addr;
232
233     ret = ret * 17851 + (ret >> 14) * 7 + (ret >> 4) * 251;
234     return (ret);
235 }
236
237 /* returns 1 if there was an info to pop, 0 if the stack was empty. */
238 static int pop_info(void)
239 {
240     APP_INFO *current = NULL;
241
242     if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
243         return 0;
244
245     current = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
246     if (current != NULL) {
247         APP_INFO *next = current->next;
248
249         if (next != NULL) {
250             next->references++;
251             CRYPTO_THREAD_set_local(&appinfokey, next);
252         } else {
253             CRYPTO_THREAD_set_local(&appinfokey, NULL);
254         }
255         if (--(current->references) <= 0) {
256             current->next = NULL;
257             if (next != NULL)
258                 next->references--;
259             OPENSSL_free(current);
260         }
261         return 1;
262     }
263     return 0;
264 }
265
266 int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
267 {
268     APP_INFO *ami, *amim;
269     int ret = 0;
270
271     if (mem_check_on()) {
272         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
273
274         if (!RUN_ONCE(&memdbg_init, do_memdbg_init)
275             || (ami = OPENSSL_malloc(sizeof(*ami))) == NULL)
276             goto err;
277
278         ami->threadid = CRYPTO_THREAD_get_current_id();
279         ami->file = file;
280         ami->line = line;
281         ami->info = info;
282         ami->references = 1;
283         ami->next = NULL;
284
285         amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
286         CRYPTO_THREAD_set_local(&appinfokey, ami);
287
288         if (amim != NULL)
289             ami->next = amim;
290         ret = 1;
291  err:
292         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
293     }
294
295     return (ret);
296 }
297
298 int CRYPTO_mem_debug_pop(void)
299 {
300     int ret = 0;
301
302     if (mem_check_on()) {
303         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
304         ret = pop_info();
305         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
306     }
307     return (ret);
308 }
309
310 static unsigned long break_order_num = 0;
311
312 void CRYPTO_mem_debug_malloc(void *addr, size_t num, int before_p,
313                              const char *file, int line)
314 {
315     MEM *m, *mm;
316     APP_INFO *amim;
317
318     switch (before_p & 127) {
319     case 0:
320         break;
321     case 1:
322         if (addr == NULL)
323             break;
324
325         if (mem_check_on()) {
326             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
327
328             if (!RUN_ONCE(&memdbg_init, do_memdbg_init)
329                 || (m = OPENSSL_malloc(sizeof(*m))) == NULL) {
330                 OPENSSL_free(addr);
331                 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
332                 return;
333             }
334             if (mh == NULL) {
335                 if ((mh = lh_MEM_new(mem_hash, mem_cmp)) == NULL) {
336                     OPENSSL_free(addr);
337                     OPENSSL_free(m);
338                     addr = NULL;
339                     goto err;
340                 }
341             }
342
343             m->addr = addr;
344             m->file = file;
345             m->line = line;
346             m->num = num;
347             m->threadid = CRYPTO_THREAD_get_current_id();
348
349             if (order == break_order_num) {
350                 /* BREAK HERE */
351                 m->order = order;
352             }
353             m->order = order++;
354 # ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
355             m->array_siz = backtrace(m->array, OSSL_NELEM(m->array));
356 # endif
357             m->time = time(NULL);
358
359             amim = (APP_INFO *)CRYPTO_THREAD_get_local(&appinfokey);
360             m->app_info = amim;
361             if (amim != NULL)
362                 amim->references++;
363
364             if ((mm = lh_MEM_insert(mh, m)) != NULL) {
365                 /* Not good, but don't sweat it */
366                 if (mm->app_info != NULL) {
367                     mm->app_info->references--;
368                 }
369                 OPENSSL_free(mm);
370             }
371  err:
372             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
373         }
374         break;
375     }
376     return;
377 }
378
379 void CRYPTO_mem_debug_free(void *addr, int before_p,
380         const char *file, int line)
381 {
382     MEM m, *mp;
383
384     switch (before_p) {
385     case 0:
386         if (addr == NULL)
387             break;
388
389         if (mem_check_on() && (mh != NULL)) {
390             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
391
392             m.addr = addr;
393             mp = lh_MEM_delete(mh, &m);
394             if (mp != NULL) {
395                 app_info_free(mp->app_info);
396                 OPENSSL_free(mp);
397             }
398
399             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
400         }
401         break;
402     case 1:
403         break;
404     }
405 }
406
407 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num,
408                               int before_p, const char *file, int line)
409 {
410     MEM m, *mp;
411
412     switch (before_p) {
413     case 0:
414         break;
415     case 1:
416         if (addr2 == NULL)
417             break;
418
419         if (addr1 == NULL) {
420             CRYPTO_mem_debug_malloc(addr2, num, 128 | before_p, file, line);
421             break;
422         }
423
424         if (mem_check_on()) {
425             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
426
427             m.addr = addr1;
428             mp = lh_MEM_delete(mh, &m);
429             if (mp != NULL) {
430                 mp->addr = addr2;
431                 mp->num = num;
432 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
433                 mp->array_siz = backtrace(mp->array, OSSL_NELEM(mp->array));
434 #endif
435                 (void)lh_MEM_insert(mh, mp);
436             }
437
438             CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
439         }
440         break;
441     }
442     return;
443 }
444
445 typedef struct mem_leak_st {
446     int (*print_cb) (const char *str, size_t len, void *u);
447     void *print_cb_arg;
448     int chunks;
449     long bytes;
450 } MEM_LEAK;
451
452 static void print_leak(const MEM *m, MEM_LEAK *l)
453 {
454     char buf[1024];
455     char *bufp = buf;
456     APP_INFO *amip;
457     int ami_cnt;
458     struct tm *lcl = NULL;
459     /*
460      * Convert between CRYPTO_THREAD_ID (which could be anything at all) and
461      * a long. This may not be meaningful depending on what CRYPTO_THREAD_ID is
462      * but hopefully should give something sensible on most platforms
463      */
464     union {
465         CRYPTO_THREAD_ID tid;
466         unsigned long ltid;
467     } tid;
468     CRYPTO_THREAD_ID ti;
469
470     lcl = localtime(&m->time);
471     sprintf(bufp, "[%02d:%02d:%02d] ", lcl->tm_hour, lcl->tm_min, lcl->tm_sec);
472     bufp += strlen(bufp);
473
474     sprintf(bufp, "%5lu file=%s, line=%d, ", m->order, m->file, m->line);
475     bufp += strlen(bufp);
476
477     tid.ltid = 0;
478     tid.tid = m->threadid;
479     sprintf(bufp, "thread=%lu, ", tid.ltid);
480     bufp += strlen(bufp);
481
482     sprintf(bufp, "number=%d, address=%p\n", m->num, m->addr);
483     bufp += strlen(bufp);
484
485     l->print_cb(buf, strlen(buf), l->print_cb_arg);
486
487     l->chunks++;
488     l->bytes += m->num;
489
490     amip = m->app_info;
491     ami_cnt = 0;
492
493     if (amip) {
494         ti = amip->threadid;
495
496         do {
497             int buf_len;
498             int info_len;
499
500             ami_cnt++;
501             memset(buf, '>', ami_cnt);
502             tid.ltid = 0;
503             tid.tid = amip->threadid;
504             sprintf(buf + ami_cnt, " thread=%lu, file=%s, line=%d, info=\"",
505                     tid.ltid, amip->file, amip->line);
506             buf_len = strlen(buf);
507             info_len = strlen(amip->info);
508             if (128 - buf_len - 3 < info_len) {
509                 memcpy(buf + buf_len, amip->info, 128 - buf_len - 3);
510                 buf_len = 128 - 3;
511             } else {
512                 strcpy(buf + buf_len, amip->info);
513                 buf_len = strlen(buf);
514             }
515             sprintf(buf + buf_len, "\"\n");
516
517             l->print_cb(buf, strlen(buf), l->print_cb_arg);
518
519             amip = amip->next;
520         }
521         while (amip && CRYPTO_THREAD_compare_id(amip->threadid, ti));
522     }
523
524 #ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
525     {
526         size_t i;
527         char **strings = backtrace_symbols(m->array, m->array_siz);
528
529         for (i = 0; i < m->array_siz; i++)
530             fprintf(stderr, "##> %s\n", strings[i]);
531         free(strings);
532     }
533 #endif
534 }
535
536 IMPLEMENT_LHASH_DOALL_ARG_CONST(MEM, MEM_LEAK);
537
538 int CRYPTO_mem_leaks_cb(int (*cb) (const char *str, size_t len, void *u),
539                         void *u)
540 {
541     MEM_LEAK ml;
542
543     /* Ensure all resources are released */
544     OPENSSL_cleanup();
545
546     if (!RUN_ONCE(&memdbg_init, do_memdbg_init))
547         return -1;
548
549     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
550
551     ml.print_cb = cb;
552     ml.print_cb_arg = u;
553     ml.bytes = 0;
554     ml.chunks = 0;
555     if (mh != NULL)
556         lh_MEM_doall_MEM_LEAK(mh, print_leak, &ml);
557
558     if (ml.chunks != 0) {
559         char buf[256];
560
561         BIO_snprintf(buf, sizeof(buf), "%ld bytes leaked in %d chunks\n",
562                      ml.bytes, ml.chunks);
563         cb(buf, strlen(buf), u);
564     } else {
565         /*
566          * Make sure that, if we found no leaks, memory-leak debugging itself
567          * does not introduce memory leaks (which might irritate external
568          * debugging tools). (When someone enables leak checking, but does not
569          * call this function, we declare it to be their fault.)
570          */
571         int old_mh_mode;
572
573         CRYPTO_THREAD_write_lock(malloc_lock);
574
575         /*
576          * avoid deadlock when lh_free() uses CRYPTO_mem_debug_free(), which uses
577          * mem_check_on
578          */
579         old_mh_mode = mh_mode;
580         mh_mode = CRYPTO_MEM_CHECK_OFF;
581
582         lh_MEM_free(mh);
583         mh = NULL;
584
585         mh_mode = old_mh_mode;
586         CRYPTO_THREAD_unlock(malloc_lock);
587     }
588     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF);
589
590     /* Clean up locks etc */
591     CRYPTO_THREAD_cleanup_local(&appinfokey);
592     CRYPTO_THREAD_lock_free(malloc_lock);
593     CRYPTO_THREAD_lock_free(long_malloc_lock);
594     malloc_lock = NULL;
595     long_malloc_lock = NULL;
596
597     return ml.chunks == 0 ? 1 : 0;
598 }
599
600 static int print_bio(const char *str, size_t len, void *b)
601 {
602     return BIO_write((BIO *)b, str, len);
603 }
604
605 int CRYPTO_mem_leaks(BIO *b)
606 {
607     /*
608      * OPENSSL_cleanup() will free the ex_data locks so we can't have any
609      * ex_data hanging around
610      */
611     bio_free_ex_data(b);
612
613     return CRYPTO_mem_leaks_cb(print_bio, b);
614 }
615
616 # ifndef OPENSSL_NO_STDIO
617 int CRYPTO_mem_leaks_fp(FILE *fp)
618 {
619     BIO *b;
620     int ret;
621
622     /*
623      * Need to turn off memory checking when allocated BIOs ... especially as
624      * we're creating them at a time when we're trying to check we've not
625      * left anything un-free()'d!!
626      */
627     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_DISABLE);
628     b = BIO_new(BIO_s_file());
629     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ENABLE);
630     if (b == NULL)
631         return -1;
632     BIO_set_fp(b, fp, BIO_NOCLOSE);
633     ret = CRYPTO_mem_leaks_cb(print_bio, b);
634     BIO_free(b);
635     return ret;
636 }
637 # endif
638
639 #endif