1+ #include < dlfcn.h>
2+ #include < pthread.h>
3+ #include < cstddef>
4+ #include < type_traits>
5+
6+ #include " DebugData.h"
7+ #include " PointerData.h"
8+ #include " malloc_debug.h"
9+
10+ class AllocHook {
11+ public:
12+ AllocHook () {
13+ void * ptr [2 ] = { &Db_storage, &Pd_storage };
14+ debug_initialize (ptr);
15+ }
16+ ~AllocHook () { debug_finalize (); }
17+
18+ void * malloc (size_t size) { return debug_malloc (size); }
19+ void free (void * ptr) { debug_free (ptr); }
20+ void * calloc (size_t a, size_t b) { return debug_calloc (a, b); }
21+ void * realloc (void * ptr, size_t size) { return debug_realloc (ptr, size); }
22+ int posix_memalign (void ** ptr, size_t alignment, size_t size) { return debug_posix_memalign (ptr, alignment, size); }
23+ int ioctl (int fd, int request, void * arg) { return debug_ioctl (fd, request, arg); }
24+ int close (int fd) { return debug_close (fd); }
25+
26+ static AllocHook& inst ();
27+
28+ private:
29+ static std::aligned_storage<sizeof (DebugData), alignof (DebugData)>::type Db_storage;
30+ static std::aligned_storage<sizeof (PointerData), alignof (PointerData)>::type Pd_storage;
31+ };
32+ std::aligned_storage<sizeof (DebugData), alignof (DebugData)>::type AllocHook::Db_storage;
33+ std::aligned_storage<sizeof (PointerData), alignof (PointerData)>::type AllocHook::Pd_storage;
34+
35+ AllocHook& AllocHook::inst () {
36+ static AllocHook hook;
37+ return hook;
38+ }
39+
40+ extern " C" {
41+ void * malloc (size_t size) {
42+ return AllocHook::inst ().malloc (size);
43+ }
44+
45+ void free (void * ptr) {
46+ AllocHook::inst ().free (ptr);
47+ }
48+
49+ void * calloc (size_t a, size_t b) {
50+ return AllocHook::inst ().calloc (a, b);
51+ }
52+
53+ void * realloc (void * ptr, size_t size) {
54+ return AllocHook::inst ().realloc (ptr, size);
55+ }
56+
57+ int posix_memalign (void ** ptr, size_t alignment, size_t size) {
58+ return AllocHook::inst ().posix_memalign (ptr, alignment, size);
59+ }
60+
61+ int ioctl (int fd, int request, ...) {
62+ va_list ap;
63+ va_start (ap, request);
64+ void * arg = va_arg (ap, void *);
65+ va_end (ap);
66+
67+ return AllocHook::inst ().ioctl (fd, request, arg);
68+ }
69+
70+ int close (int fd) {
71+ return AllocHook::inst ().close (fd);
72+ }
73+
74+ }
0 commit comments