update JACK backend to use new inheritance structure for AudioBackend
[ardour.git] / libs / pbd / debug_rt_alloc.c
1 /*
2     Copyright (C) 2011 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifdef DEBUG_RT_ALLOC
21
22 #define _GNU_SOURCE
23 #include <dlfcn.h>
24 #include <stdio.h>
25 #include <pthread.h>
26 #include <stdlib.h>
27
28 int (*pbd_alloc_allowed) () = 0;
29
30 /** Thread-local key whose value is set to 1 if malloc checking is disabled
31  *  for this thread, 0 otherwise.
32  */
33
34 static pthread_key_t disabled;
35
36 static pthread_once_t once;
37
38 static void
39 make_key (void)
40 {
41         (void) pthread_key_create (&disabled, NULL);
42 }
43
44 /** This is our malloc which overrides the system one */
45 void* malloc (size_t s)
46 {
47         static void * (*real_malloc) (size_t) = NULL;
48         if (!real_malloc) {
49                 /* find the system malloc */
50                 real_malloc = dlsym (RTLD_NEXT, "malloc");
51         }
52
53         (void) pthread_once (&once, make_key);
54
55         if (pthread_getspecific (disabled) == NULL && pbd_alloc_allowed && !pbd_alloc_allowed ()) {
56                 /* pbd_alloc_allowed says that this malloc is not permitted */
57                 abort ();
58         }
59
60         /* Pass through to the system malloc */
61         return real_malloc (s);
62 }
63
64 void
65 suspend_rt_malloc_checks ()
66 {
67         (void) pthread_once (&once, make_key);
68         pthread_setspecific (disabled, (void *) 1);
69 }
70
71 void
72 resume_rt_malloc_checks ()
73 {
74         (void) pthread_once (&once, make_key);
75         pthread_setspecific (disabled, (void *) 0);
76 }
77
78 #endif