]>
git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/malloctrace.cc
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #include "malloctrace.hh"
30 MallocTracer
* g_mtracer
;
34 vector
<void*> MallocTracer::makeBacktrace()
36 void *array
[20]; //only care about last 17 functions (3 taken with tracing support)
37 size_t size
= backtrace (array
, 20);
38 return vector
<void*>(array
, array
+size
);
43 extern void *__libc_malloc(size_t size
);
44 extern void __libc_free(void* ptr
);
46 void* malloc (size_t size
)
49 void *mem
= __libc_malloc(sizeof(MallocTracer
));
50 g_mtracer
= new(mem
) MallocTracer
;
52 return g_mtracer
->malloc(size
);
64 static thread_local
bool l_active
;
65 void* MallocTracer::malloc(size_t size
)
67 void* ret
= __libc_malloc(size
);
73 d_totAllocated
+= size
;
76 std::lock_guard
<std::mutex
> lock(d_mut
);
77 auto& ent
=d_stats
[makeBacktrace()];
87 void MallocTracer::free(void* ptr
)
92 std::lock_guard
<std::mutex
> lock(d_mut
);
93 auto f
= d_sizes
.find(ptr
);
94 if(f
!= d_sizes
.end()) {
95 d_totAllocated
-= f
->second
;
102 MallocTracer::allocators_t
MallocTracer::topAllocators(int num
)
106 for(const auto& e
: d_stats
) {
107 ret
.push_back(make_pair(e
.second
, e
.first
));
109 std::sort(ret
.begin(), ret
.end(),
110 [](const allocators_t::value_type
& a
,
111 const allocators_t::value_type
& b
) {
112 return a
.first
.count
< b
.first
.count
;
114 if((unsigned int)num
> ret
.size())
117 ret
.erase(ret
.begin(), ret
.begin() + (ret
.size() - num
));
122 std::string
MallocTracer::topAllocatorsString(int num
)
125 auto raw
= topAllocators(num
);
127 std::ostringstream ret
;
128 for(const auto& e
: raw
) {
129 ret
<<"Called "<<e
.first
.count
<<" times\n";
130 for(const auto& u
: e
.first
.sizes
)
131 ret
<<u
.first
<<"b: "<<u
.second
<<" times, ";
133 char** strings
= backtrace_symbols(&e
.second
[0], e
.second
.size());
134 for(unsigned int i
=0; i
< e
.second
.size(); ++i
)
135 ret
<<strings
[i
]<<'\n';
139 string str
=ret
.str();
144 void MallocTracer::clearAllocators()
147 std::lock_guard
<std::mutex
> lock(d_mut
);