blob: d203394cde440801f2256430c0d4fbbd03f2edf1 [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.
Brian Silverman20350ac2021-11-17 18:19:55 -08004//
Austin Schuh745610d2015-09-06 18:19:50 -07005// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
Brian Silverman20350ac2021-11-17 18:19:55 -08008//
Austin Schuh745610d2015-09-06 18:19:50 -07009// * 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.
Brian Silverman20350ac2021-11-17 18:19:55 -080018//
Austin Schuh745610d2015-09-06 18:19:50 -070019// 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// Extra extensions exported by some malloc implementations. These
35// extensions are accessed through a virtual base class so an
36// application can link against a malloc that does not implement these
37// extensions, and it will get default versions that do nothing.
38//
39// NOTE FOR C USERS: If you wish to use this functionality from within
40// a C program, see malloc_extension_c.h.
41
42#ifndef BASE_MALLOC_EXTENSION_H_
43#define BASE_MALLOC_EXTENSION_H_
44
45#include <stddef.h>
46// I can't #include config.h in this public API file, but I should
47// really use configure (and make malloc_extension.h a .in file) to
48// figure out if the system has stdint.h or not. But I'm lazy, so
49// for now I'm assuming it's a problem only with MSVC.
50#ifndef _MSC_VER
51#include <stdint.h>
52#endif
53#include <string>
54#include <vector>
55
56// Annoying stuff for windows -- makes sure clients can import these functions
57#ifndef PERFTOOLS_DLL_DECL
58# ifdef _WIN32
59# define PERFTOOLS_DLL_DECL __declspec(dllimport)
60# else
61# define PERFTOOLS_DLL_DECL
62# endif
63#endif
64
65static const int kMallocHistogramSize = 64;
66
67// One day, we could support other types of writers (perhaps for C?)
68typedef std::string MallocExtensionWriter;
69
70namespace base {
71struct MallocRange;
72}
73
74// Interface to a pluggable system allocator.
75class PERFTOOLS_DLL_DECL SysAllocator {
76 public:
77 SysAllocator() {
78 }
79 virtual ~SysAllocator();
80
81 // Allocates "size"-byte of memory from system aligned with "alignment".
82 // Returns NULL if failed. Otherwise, the returned pointer p up to and
83 // including (p + actual_size -1) have been allocated.
84 virtual void* Alloc(size_t size, size_t *actual_size, size_t alignment) = 0;
85};
86
87// The default implementations of the following routines do nothing.
88// All implementations should be thread-safe; the current one
89// (TCMallocImplementation) is.
90class PERFTOOLS_DLL_DECL MallocExtension {
91 public:
92 virtual ~MallocExtension();
93
94 // Call this very early in the program execution -- say, in a global
95 // constructor -- to set up parameters and state needed by all
96 // instrumented malloc implemenatations. One example: this routine
97 // sets environemnt variables to tell STL to use libc's malloc()
98 // instead of doing its own memory management. This is safe to call
99 // multiple times, as long as each time is before threads start up.
100 static void Initialize();
101
102 // See "verify_memory.h" to see what these routines do
103 virtual bool VerifyAllMemory();
104 virtual bool VerifyNewMemory(const void* p);
105 virtual bool VerifyArrayNewMemory(const void* p);
106 virtual bool VerifyMallocMemory(const void* p);
107 virtual bool MallocMemoryStats(int* blocks, size_t* total,
108 int histogram[kMallocHistogramSize]);
109
Brian Silverman20350ac2021-11-17 18:19:55 -0800110 // Get a human readable description of the following malloc data structures.
111 // - Total inuse memory by application.
112 // - Free memory(thread, central and page heap),
113 // - Freelist of central cache, each class.
114 // - Page heap freelist.
115 // The state is stored as a null-terminated string
Austin Schuh745610d2015-09-06 18:19:50 -0700116 // in a prefix of "buffer[0,buffer_length-1]".
117 // REQUIRES: buffer_length > 0.
118 virtual void GetStats(char* buffer, int buffer_length);
119
120 // Outputs to "writer" a sample of live objects and the stack traces
121 // that allocated these objects. The format of the returned output
122 // is equivalent to the output of the heap profiler and can
123 // therefore be passed to "pprof". This function is equivalent to
124 // ReadStackTraces. The main difference is that this function returns
125 // serialized data appropriately formatted for use by the pprof tool.
Brian Silverman20350ac2021-11-17 18:19:55 -0800126 //
127 // Since gperftools 2.8 heap samples are not de-duplicated by the
128 // library anymore.
129 //
Austin Schuh745610d2015-09-06 18:19:50 -0700130 // NOTE: by default, tcmalloc does not do any heap sampling, and this
131 // function will always return an empty sample. To get useful
132 // data from GetHeapSample, you must also set the environment
133 // variable TCMALLOC_SAMPLE_PARAMETER to a value such as 524288.
134 virtual void GetHeapSample(MallocExtensionWriter* writer);
135
136 // Outputs to "writer" the stack traces that caused growth in the
137 // address space size. The format of the returned output is
138 // equivalent to the output of the heap profiler and can therefore
139 // be passed to "pprof". This function is equivalent to
140 // ReadHeapGrowthStackTraces. The main difference is that this function
141 // returns serialized data appropriately formatted for use by the
142 // pprof tool. (This does not depend on, or require,
143 // TCMALLOC_SAMPLE_PARAMETER.)
144 virtual void GetHeapGrowthStacks(MallocExtensionWriter* writer);
145
146 // Invokes func(arg, range) for every controlled memory
147 // range. *range is filled in with information about the range.
148 //
149 // This is a best-effort interface useful only for performance
150 // analysis. The implementation may not call func at all.
151 typedef void (RangeFunction)(void*, const base::MallocRange*);
152 virtual void Ranges(void* arg, RangeFunction func);
153
154 // -------------------------------------------------------------------
155 // Control operations for getting and setting malloc implementation
156 // specific parameters. Some currently useful properties:
157 //
158 // generic
159 // -------
160 // "generic.current_allocated_bytes"
161 // Number of bytes currently allocated by application
162 // This property is not writable.
163 //
164 // "generic.heap_size"
165 // Number of bytes in the heap ==
166 // current_allocated_bytes +
167 // fragmentation +
168 // freed memory regions
169 // This property is not writable.
170 //
Brian Silverman20350ac2021-11-17 18:19:55 -0800171 // "generic.total_physical_bytes"
172 // Estimate of total bytes of the physical memory usage by the
173 // allocator ==
174 // current_allocated_bytes +
175 // fragmentation +
176 // metadata
177 // This property is not writable.
178 //
Austin Schuh745610d2015-09-06 18:19:50 -0700179 // tcmalloc
180 // --------
181 // "tcmalloc.max_total_thread_cache_bytes"
182 // Upper limit on total number of bytes stored across all
183 // per-thread caches. Default: 16MB.
184 //
185 // "tcmalloc.current_total_thread_cache_bytes"
186 // Number of bytes used across all thread caches.
187 // This property is not writable.
188 //
189 // "tcmalloc.central_cache_free_bytes"
190 // Number of free bytes in the central cache that have been
191 // assigned to size classes. They always count towards virtual
192 // memory usage, and unless the underlying memory is swapped out
193 // by the OS, they also count towards physical memory usage.
194 // This property is not writable.
195 //
196 // "tcmalloc.transfer_cache_free_bytes"
197 // Number of free bytes that are waiting to be transfered between
198 // the central cache and a thread cache. They always count
199 // towards virtual memory usage, and unless the underlying memory
200 // is swapped out by the OS, they also count towards physical
201 // memory usage. This property is not writable.
202 //
203 // "tcmalloc.thread_cache_free_bytes"
204 // Number of free bytes in thread caches. They always count
205 // towards virtual memory usage, and unless the underlying memory
206 // is swapped out by the OS, they also count towards physical
207 // memory usage. This property is not writable.
208 //
209 // "tcmalloc.pageheap_free_bytes"
210 // Number of bytes in free, mapped pages in page heap. These
211 // bytes can be used to fulfill allocation requests. They
212 // always count towards virtual memory usage, and unless the
213 // underlying memory is swapped out by the OS, they also count
214 // towards physical memory usage. This property is not writable.
215 //
216 // "tcmalloc.pageheap_unmapped_bytes"
217 // Number of bytes in free, unmapped pages in page heap.
218 // These are bytes that have been released back to the OS,
219 // possibly by one of the MallocExtension "Release" calls.
220 // They can be used to fulfill allocation requests, but
221 // typically incur a page fault. They always count towards
222 // virtual memory usage, and depending on the OS, typically
223 // do not count towards physical memory usage. This property
224 // is not writable.
225 // -------------------------------------------------------------------
226
227 // Get the named "property"'s value. Returns true if the property
228 // is known. Returns false if the property is not a valid property
229 // name for the current malloc implementation.
230 // REQUIRES: property != NULL; value != NULL
231 virtual bool GetNumericProperty(const char* property, size_t* value);
232
233 // Set the named "property"'s value. Returns true if the property
234 // is known and writable. Returns false if the property is not a
235 // valid property name for the current malloc implementation, or
236 // is not writable.
237 // REQUIRES: property != NULL
238 virtual bool SetNumericProperty(const char* property, size_t value);
239
240 // Mark the current thread as "idle". This routine may optionally
241 // be called by threads as a hint to the malloc implementation that
242 // any thread-specific resources should be released. Note: this may
243 // be an expensive routine, so it should not be called too often.
244 //
245 // Also, if the code that calls this routine will go to sleep for
246 // a while, it should take care to not allocate anything between
247 // the call to this routine and the beginning of the sleep.
248 //
249 // Most malloc implementations ignore this routine.
250 virtual void MarkThreadIdle();
251
252 // Mark the current thread as "busy". This routine should be
253 // called after MarkThreadIdle() if the thread will now do more
254 // work. If this method is not called, performance may suffer.
255 //
256 // Most malloc implementations ignore this routine.
257 virtual void MarkThreadBusy();
258
259 // Gets the system allocator used by the malloc extension instance. Returns
260 // NULL for malloc implementations that do not support pluggable system
261 // allocators.
262 virtual SysAllocator* GetSystemAllocator();
263
264 // Sets the system allocator to the specified.
265 //
266 // Users could register their own system allocators for malloc implementation
267 // that supports pluggable system allocators, such as TCMalloc, by doing:
268 // alloc = new MyOwnSysAllocator();
269 // MallocExtension::instance()->SetSystemAllocator(alloc);
270 // It's up to users whether to fall back (recommended) to the default
271 // system allocator (use GetSystemAllocator() above) or not. The caller is
272 // responsible to any necessary locking.
273 // See tcmalloc/system-alloc.h for the interface and
274 // tcmalloc/memfs_malloc.cc for the examples.
275 //
276 // It's a no-op for malloc implementations that do not support pluggable
277 // system allocators.
278 virtual void SetSystemAllocator(SysAllocator *a);
279
280 // Try to release num_bytes of free memory back to the operating
281 // system for reuse. Use this extension with caution -- to get this
282 // memory back may require faulting pages back in by the OS, and
283 // that may be slow. (Currently only implemented in tcmalloc.)
284 virtual void ReleaseToSystem(size_t num_bytes);
285
286 // Same as ReleaseToSystem() but release as much memory as possible.
287 virtual void ReleaseFreeMemory();
288
289 // Sets the rate at which we release unused memory to the system.
290 // Zero means we never release memory back to the system. Increase
291 // this flag to return memory faster; decrease it to return memory
292 // slower. Reasonable rates are in the range [0,10]. (Currently
293 // only implemented in tcmalloc).
294 virtual void SetMemoryReleaseRate(double rate);
295
296 // Gets the release rate. Returns a value < 0 if unknown.
297 virtual double GetMemoryReleaseRate();
298
299 // Returns the estimated number of bytes that will be allocated for
300 // a request of "size" bytes. This is an estimate: an allocation of
301 // SIZE bytes may reserve more bytes, but will never reserve less.
302 // (Currently only implemented in tcmalloc, other implementations
303 // always return SIZE.)
304 // This is equivalent to malloc_good_size() in OS X.
305 virtual size_t GetEstimatedAllocatedSize(size_t size);
306
307 // Returns the actual number N of bytes reserved by tcmalloc for the
308 // pointer p. The client is allowed to use the range of bytes
309 // [p, p+N) in any way it wishes (i.e. N is the "usable size" of this
310 // allocation). This number may be equal to or greater than the number
311 // of bytes requested when p was allocated.
312 // p must have been allocated by this malloc implementation,
313 // must not be an interior pointer -- that is, must be exactly
314 // the pointer returned to by malloc() et al., not some offset
315 // from that -- and should not have been freed yet. p may be NULL.
316 // (Currently only implemented in tcmalloc; other implementations
317 // will return 0.)
318 // This is equivalent to malloc_size() in OS X, malloc_usable_size()
319 // in glibc, and _msize() for windows.
320 virtual size_t GetAllocatedSize(const void* p);
321
322 // Returns kOwned if this malloc implementation allocated the memory
323 // pointed to by p, or kNotOwned if some other malloc implementation
324 // allocated it or p is NULL. May also return kUnknownOwnership if
325 // the malloc implementation does not keep track of ownership.
326 // REQUIRES: p must be a value returned from a previous call to
327 // malloc(), calloc(), realloc(), memalign(), posix_memalign(),
328 // valloc(), pvalloc(), new, or new[], and must refer to memory that
329 // is currently allocated (so, for instance, you should not pass in
330 // a pointer after having called free() on it).
331 enum Ownership {
332 // NOTE: Enum values MUST be kept in sync with the version in
333 // malloc_extension_c.h
334 kUnknownOwnership = 0,
335 kOwned,
336 kNotOwned
337 };
338 virtual Ownership GetOwnership(const void* p);
339
340 // The current malloc implementation. Always non-NULL.
341 static MallocExtension* instance();
342
343 // Change the malloc implementation. Typically called by the
344 // malloc implementation during initialization.
345 static void Register(MallocExtension* implementation);
346
347 // Returns detailed information about malloc's freelists. For each list,
348 // return a FreeListInfo:
349 struct FreeListInfo {
350 size_t min_object_size;
351 size_t max_object_size;
352 size_t total_bytes_free;
353 const char* type;
354 };
355 // Each item in the vector refers to a different freelist. The lists
356 // are identified by the range of allocations that objects in the
357 // list can satisfy ([min_object_size, max_object_size]) and the
358 // type of freelist (see below). The current size of the list is
359 // returned in total_bytes_free (which count against a processes
360 // resident and virtual size).
361 //
362 // Currently supported types are:
363 //
364 // "tcmalloc.page{_unmapped}" - tcmalloc's page heap. An entry for each size
365 // class in the page heap is returned. Bytes in "page_unmapped"
366 // are no longer backed by physical memory and do not count against
367 // the resident size of a process.
368 //
369 // "tcmalloc.large{_unmapped}" - tcmalloc's list of objects larger
370 // than the largest page heap size class. Only one "large"
371 // entry is returned. There is no upper-bound on the size
372 // of objects in the large free list; this call returns
373 // kint64max for max_object_size. Bytes in
374 // "large_unmapped" are no longer backed by physical memory
375 // and do not count against the resident size of a process.
376 //
377 // "tcmalloc.central" - tcmalloc's central free-list. One entry per
378 // size-class is returned. Never unmapped.
379 //
380 // "debug.free_queue" - free objects queued by the debug allocator
381 // and not returned to tcmalloc.
382 //
383 // "tcmalloc.thread" - tcmalloc's per-thread caches. Never unmapped.
384 virtual void GetFreeListSizes(std::vector<FreeListInfo>* v);
385
386 // Get a list of stack traces of sampled allocation points. Returns
387 // a pointer to a "new[]-ed" result array, and stores the sample
388 // period in "sample_period".
389 //
390 // The state is stored as a sequence of adjacent entries
391 // in the returned array. Each entry has the following form:
392 // uintptr_t count; // Number of objects with following trace
393 // uintptr_t size; // Total size of objects with following trace
394 // uintptr_t depth; // Number of PC values in stack trace
395 // void* stack[depth]; // PC values that form the stack trace
396 //
397 // The list of entries is terminated by a "count" of 0.
398 //
399 // It is the responsibility of the caller to "delete[]" the returned array.
400 //
401 // May return NULL to indicate no results.
402 //
403 // This is an internal extension. Callers should use the more
404 // convenient "GetHeapSample(string*)" method defined above.
405 virtual void** ReadStackTraces(int* sample_period);
406
407 // Like ReadStackTraces(), but returns stack traces that caused growth
408 // in the address space size.
409 virtual void** ReadHeapGrowthStackTraces();
Brian Silverman20350ac2021-11-17 18:19:55 -0800410
411 // Returns the size in bytes of the calling threads cache.
412 virtual size_t GetThreadCacheSize();
413
414 // Like MarkThreadIdle, but does not destroy the internal data
415 // structures of the thread cache. When the thread resumes, it wil
416 // have an empty cache but will not need to pay to reconstruct the
417 // cache data structures.
418 virtual void MarkThreadTemporarilyIdle();
Austin Schuh745610d2015-09-06 18:19:50 -0700419};
420
421namespace base {
422
423// Information passed per range. More fields may be added later.
424struct MallocRange {
425 enum Type {
426 INUSE, // Application is using this range
427 FREE, // Range is currently free
428 UNMAPPED, // Backing physical memory has been returned to the OS
429 UNKNOWN
430 // More enum values may be added in the future
431 };
432
433 uintptr_t address; // Address of range
434 size_t length; // Byte length of range
435 Type type; // Type of this range
436 double fraction; // Fraction of range that is being used (0 if !INUSE)
437
438 // Perhaps add the following:
439 // - stack trace if this range was sampled
440 // - heap growth stack trace if applicable to this range
441 // - age when allocated (for inuse) or freed (if not in use)
442};
443
444} // namespace base
445
446#endif // BASE_MALLOC_EXTENSION_H_