edit scripts
[c11concurrency-benchmarks.git] / silo / memory.cc
1 #include "macros.h" // for TRAP_LARGE_ALLOOCATIONS
2
3 #ifdef TRAP_LARGE_ALLOOCATIONS
4
5 #include <new>
6 #include <iostream>
7 #include <stdlib.h>
8 #include <stdint.h>
9 #include <execinfo.h>
10 #include <unistd.h>
11
12 static void *
13 do_allocation(size_t sz, bool do_throw)
14 {
15   if (unlikely(sz > (1 << 20))) { // allocations more than 1MB are suspect
16     // print stacktrace:
17     std::cerr << "Warning: Large memory allocation (" << sz << " bytes)" << std::endl;
18     void *addrs[128];
19     const size_t naddrs = backtrace(addrs, ARRAY_NELEMS(addrs));
20     backtrace_symbols_fd(addrs, naddrs, STDERR_FILENO);
21   }
22   void *ret = malloc(sz);
23   if (unlikely(!ret && do_throw))
24     throw std::bad_alloc();
25   return ret;
26 }
27
28 static inline void
29 do_deletion(void *p)
30 {
31   free(p);
32 }
33
34 void*
35 operator new(size_t sz) throw (std::bad_alloc)
36 {
37   return do_allocation(sz, true);
38 }
39
40 void*
41 operator new(size_t sz, const std::nothrow_t&) throw ()
42 {
43   return do_allocation(sz, false);
44 }
45
46 void*
47 operator new[](size_t sz) throw (std::bad_alloc)
48 {
49   return do_allocation(sz, true);
50 }
51
52 void*
53 operator new[](size_t sz, std::nothrow_t &) throw ()
54 {
55   return do_allocation(sz, false);
56 }
57
58 void
59 operator delete(void *p) throw ()
60 {
61   return do_deletion(p);
62 }
63
64 void
65 operator delete(void *p, const std::nothrow_t &) throw ()
66 {
67   return do_deletion(p);
68 }
69
70 void
71 operator delete[](void *p) throw ()
72 {
73   return do_deletion(p);
74 }
75
76 void
77 operator delete[](void *p, const std::nothrow_t &) throw ()
78 {
79   return do_deletion(p);
80 }
81
82 #endif