blob: 4ff719c84b452a9a2245a55db5e8440025ee1a3b [file] [log] [blame]
Austin Schuh745610d2015-09-06 18:19:50 -07001// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
2// Copyright (c) 2005, Google Inc.
3// All rights reserved.
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9// * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11// * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15// * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31// ---
32// Author: Sanjay Ghemawat <opensource@google.com>
33
34#include <config.h>
35#include <assert.h>
36#include <string.h>
37#include <stdio.h>
38#if defined HAVE_STDINT_H
39#include <stdint.h>
40#elif defined HAVE_INTTYPES_H
41#include <inttypes.h>
42#else
43#include <sys/types.h>
44#endif
45#include <string>
46#include "base/dynamic_annotations.h"
47#include "base/sysinfo.h" // for FillProcSelfMaps
48#ifndef NO_HEAP_CHECK
49#include "gperftools/heap-checker.h"
50#endif
51#include "gperftools/malloc_extension.h"
52#include "gperftools/malloc_extension_c.h"
53#include "maybe_threads.h"
54#include "base/googleinit.h"
55
56using STL_NAMESPACE::string;
57using STL_NAMESPACE::vector;
58
59static void DumpAddressMap(string* result) {
60 *result += "\nMAPPED_LIBRARIES:\n";
61 // We keep doubling until we get a fit
62 const size_t old_resultlen = result->size();
63 for (int amap_size = 10240; amap_size < 10000000; amap_size *= 2) {
64 result->resize(old_resultlen + amap_size);
65 bool wrote_all = false;
66 const int bytes_written =
67 tcmalloc::FillProcSelfMaps(&((*result)[old_resultlen]), amap_size,
68 &wrote_all);
69 if (wrote_all) { // we fit!
70 (*result)[old_resultlen + bytes_written] = '\0';
71 result->resize(old_resultlen + bytes_written);
72 return;
73 }
74 }
75 result->reserve(old_resultlen); // just don't print anything
76}
77
78// Note: this routine is meant to be called before threads are spawned.
79void MallocExtension::Initialize() {
80 static bool initialize_called = false;
81
82 if (initialize_called) return;
83 initialize_called = true;
84
85#ifdef __GLIBC__
86 // GNU libc++ versions 3.3 and 3.4 obey the environment variables
87 // GLIBCPP_FORCE_NEW and GLIBCXX_FORCE_NEW respectively. Setting
88 // one of these variables forces the STL default allocator to call
89 // new() or delete() for each allocation or deletion. Otherwise
90 // the STL allocator tries to avoid the high cost of doing
91 // allocations by pooling memory internally. However, tcmalloc
92 // does allocations really fast, especially for the types of small
93 // items one sees in STL, so it's better off just using us.
94 // TODO: control whether we do this via an environment variable?
95 setenv("GLIBCPP_FORCE_NEW", "1", false /* no overwrite*/);
96 setenv("GLIBCXX_FORCE_NEW", "1", false /* no overwrite*/);
97
98 // Now we need to make the setenv 'stick', which it may not do since
99 // the env is flakey before main() is called. But luckily stl only
100 // looks at this env var the first time it tries to do an alloc, and
101 // caches what it finds. So we just cause an stl alloc here.
102 string dummy("I need to be allocated");
103 dummy += "!"; // so the definition of dummy isn't optimized out
104#endif /* __GLIBC__ */
105}
106
107// SysAllocator implementation
108SysAllocator::~SysAllocator() {}
109
110// Default implementation -- does nothing
111MallocExtension::~MallocExtension() { }
112bool MallocExtension::VerifyAllMemory() { return true; }
113bool MallocExtension::VerifyNewMemory(const void* p) { return true; }
114bool MallocExtension::VerifyArrayNewMemory(const void* p) { return true; }
115bool MallocExtension::VerifyMallocMemory(const void* p) { return true; }
116
117bool MallocExtension::GetNumericProperty(const char* property, size_t* value) {
118 return false;
119}
120
121bool MallocExtension::SetNumericProperty(const char* property, size_t value) {
122 return false;
123}
124
125void MallocExtension::GetStats(char* buffer, int length) {
126 assert(length > 0);
127 buffer[0] = '\0';
128}
129
130bool MallocExtension::MallocMemoryStats(int* blocks, size_t* total,
131 int histogram[kMallocHistogramSize]) {
132 *blocks = 0;
133 *total = 0;
134 memset(histogram, 0, sizeof(*histogram) * kMallocHistogramSize);
135 return true;
136}
137
138void** MallocExtension::ReadStackTraces(int* sample_period) {
139 return NULL;
140}
141
142void** MallocExtension::ReadHeapGrowthStackTraces() {
143 return NULL;
144}
145
146void MallocExtension::MarkThreadIdle() {
147 // Default implementation does nothing
148}
149
150void MallocExtension::MarkThreadBusy() {
151 // Default implementation does nothing
152}
153
154SysAllocator* MallocExtension::GetSystemAllocator() {
155 return NULL;
156}
157
158void MallocExtension::SetSystemAllocator(SysAllocator *a) {
159 // Default implementation does nothing
160}
161
162void MallocExtension::ReleaseToSystem(size_t num_bytes) {
163 // Default implementation does nothing
164}
165
166void MallocExtension::ReleaseFreeMemory() {
167 ReleaseToSystem(static_cast<size_t>(-1)); // SIZE_T_MAX
168}
169
170void MallocExtension::SetMemoryReleaseRate(double rate) {
171 // Default implementation does nothing
172}
173
174double MallocExtension::GetMemoryReleaseRate() {
175 return -1.0;
176}
177
178size_t MallocExtension::GetEstimatedAllocatedSize(size_t size) {
179 return size;
180}
181
182size_t MallocExtension::GetAllocatedSize(const void* p) {
183 assert(GetOwnership(p) != kNotOwned);
184 return 0;
185}
186
187MallocExtension::Ownership MallocExtension::GetOwnership(const void* p) {
188 return kUnknownOwnership;
189}
190
191void MallocExtension::GetFreeListSizes(
192 vector<MallocExtension::FreeListInfo>* v) {
193 v->clear();
194}
195
196// The current malloc extension object.
197
198static MallocExtension* current_instance;
199
200static void InitModule() {
201 if (current_instance != NULL) {
202 return;
203 }
204 current_instance = new MallocExtension;
205#ifndef NO_HEAP_CHECK
206 HeapLeakChecker::IgnoreObject(current_instance);
207#endif
208}
209
210REGISTER_MODULE_INITIALIZER(malloc_extension_init, InitModule())
211
212MallocExtension* MallocExtension::instance() {
213 InitModule();
214 return current_instance;
215}
216
217void MallocExtension::Register(MallocExtension* implementation) {
218 InitModule();
219 // When running under valgrind, our custom malloc is replaced with
220 // valgrind's one and malloc extensions will not work. (Note:
221 // callers should be responsible for checking that they are the
222 // malloc that is really being run, before calling Register. This
223 // is just here as an extra sanity check.)
224 if (!RunningOnValgrind()) {
225 current_instance = implementation;
226 }
227}
228
229// -----------------------------------------------------------------------
230// Heap sampling support
231// -----------------------------------------------------------------------
232
233namespace {
234
235// Accessors
236uintptr_t Count(void** entry) {
237 return reinterpret_cast<uintptr_t>(entry[0]);
238}
239uintptr_t Size(void** entry) {
240 return reinterpret_cast<uintptr_t>(entry[1]);
241}
242uintptr_t Depth(void** entry) {
243 return reinterpret_cast<uintptr_t>(entry[2]);
244}
245void* PC(void** entry, int i) {
246 return entry[3+i];
247}
248
249void PrintCountAndSize(MallocExtensionWriter* writer,
250 uintptr_t count, uintptr_t size) {
251 char buf[100];
252 snprintf(buf, sizeof(buf),
253 "%6" PRIu64 ": %8" PRIu64 " [%6" PRIu64 ": %8" PRIu64 "] @",
254 static_cast<uint64>(count),
255 static_cast<uint64>(size),
256 static_cast<uint64>(count),
257 static_cast<uint64>(size));
258 writer->append(buf, strlen(buf));
259}
260
261void PrintHeader(MallocExtensionWriter* writer,
262 const char* label, void** entries) {
263 // Compute the total count and total size
264 uintptr_t total_count = 0;
265 uintptr_t total_size = 0;
266 for (void** entry = entries; Count(entry) != 0; entry += 3 + Depth(entry)) {
267 total_count += Count(entry);
268 total_size += Size(entry);
269 }
270
271 const char* const kTitle = "heap profile: ";
272 writer->append(kTitle, strlen(kTitle));
273 PrintCountAndSize(writer, total_count, total_size);
274 writer->append(" ", 1);
275 writer->append(label, strlen(label));
276 writer->append("\n", 1);
277}
278
279void PrintStackEntry(MallocExtensionWriter* writer, void** entry) {
280 PrintCountAndSize(writer, Count(entry), Size(entry));
281
282 for (int i = 0; i < Depth(entry); i++) {
283 char buf[32];
284 snprintf(buf, sizeof(buf), " %p", PC(entry, i));
285 writer->append(buf, strlen(buf));
286 }
287 writer->append("\n", 1);
288}
289
290}
291
292void MallocExtension::GetHeapSample(MallocExtensionWriter* writer) {
293 int sample_period = 0;
294 void** entries = ReadStackTraces(&sample_period);
295 if (entries == NULL) {
296 const char* const kErrorMsg =
297 "This malloc implementation does not support sampling.\n"
298 "As of 2005/01/26, only tcmalloc supports sampling, and\n"
299 "you are probably running a binary that does not use\n"
300 "tcmalloc.\n";
301 writer->append(kErrorMsg, strlen(kErrorMsg));
302 return;
303 }
304
305 char label[32];
306 sprintf(label, "heap_v2/%d", sample_period);
307 PrintHeader(writer, label, entries);
308 for (void** entry = entries; Count(entry) != 0; entry += 3 + Depth(entry)) {
309 PrintStackEntry(writer, entry);
310 }
311 delete[] entries;
312
313 DumpAddressMap(writer);
314}
315
316void MallocExtension::GetHeapGrowthStacks(MallocExtensionWriter* writer) {
317 void** entries = ReadHeapGrowthStackTraces();
318 if (entries == NULL) {
319 const char* const kErrorMsg =
320 "This malloc implementation does not support "
321 "ReadHeapGrowthStackTraces().\n"
322 "As of 2005/09/27, only tcmalloc supports this, and you\n"
323 "are probably running a binary that does not use tcmalloc.\n";
324 writer->append(kErrorMsg, strlen(kErrorMsg));
325 return;
326 }
327
328 // Do not canonicalize the stack entries, so that we get a
329 // time-ordered list of stack traces, which may be useful if the
330 // client wants to focus on the latest stack traces.
331 PrintHeader(writer, "growth", entries);
332 for (void** entry = entries; Count(entry) != 0; entry += 3 + Depth(entry)) {
333 PrintStackEntry(writer, entry);
334 }
335 delete[] entries;
336
337 DumpAddressMap(writer);
338}
339
340void MallocExtension::Ranges(void* arg, RangeFunction func) {
341 // No callbacks by default
342}
343
344// These are C shims that work on the current instance.
345
346#define C_SHIM(fn, retval, paramlist, arglist) \
347 extern "C" PERFTOOLS_DLL_DECL retval MallocExtension_##fn paramlist { \
348 return MallocExtension::instance()->fn arglist; \
349 }
350
351C_SHIM(VerifyAllMemory, int, (void), ());
352C_SHIM(VerifyNewMemory, int, (const void* p), (p));
353C_SHIM(VerifyArrayNewMemory, int, (const void* p), (p));
354C_SHIM(VerifyMallocMemory, int, (const void* p), (p));
355C_SHIM(MallocMemoryStats, int,
356 (int* blocks, size_t* total, int histogram[kMallocHistogramSize]),
357 (blocks, total, histogram));
358
359C_SHIM(GetStats, void,
360 (char* buffer, int buffer_length), (buffer, buffer_length));
361C_SHIM(GetNumericProperty, int,
362 (const char* property, size_t* value), (property, value));
363C_SHIM(SetNumericProperty, int,
364 (const char* property, size_t value), (property, value));
365
366C_SHIM(MarkThreadIdle, void, (void), ());
367C_SHIM(MarkThreadBusy, void, (void), ());
368C_SHIM(ReleaseFreeMemory, void, (void), ());
369C_SHIM(ReleaseToSystem, void, (size_t num_bytes), (num_bytes));
370C_SHIM(GetEstimatedAllocatedSize, size_t, (size_t size), (size));
371C_SHIM(GetAllocatedSize, size_t, (const void* p), (p));
372
373// Can't use the shim here because of the need to translate the enums.
374extern "C"
375MallocExtension_Ownership MallocExtension_GetOwnership(const void* p) {
376 return static_cast<MallocExtension_Ownership>(
377 MallocExtension::instance()->GetOwnership(p));
378}