/src/google/malloc_extension.h

http://google-perftools.googlecode.com/
C Header | 402 lines | 87 code | 41 blank | 274 comment | 0 complexity | 40eb9ff141f6a34a3a01f14b6525cc8e MD5 | raw file

✨ Summary
  1. // Copyright (c) 2005, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // ---
  30. // Author: Sanjay Ghemawat <opensource@google.com>
  31. //
  32. // Extra extensions exported by some malloc implementations. These
  33. // extensions are accessed through a virtual base class so an
  34. // application can link against a malloc that does not implement these
  35. // extensions, and it will get default versions that do nothing.
  36. //
  37. // NOTE FOR C USERS: If you wish to use this functionality from within
  38. // a C program, see malloc_extension_c.h.
  39. #ifndef BASE_MALLOC_EXTENSION_H_
  40. #define BASE_MALLOC_EXTENSION_H_
  41. #include <stddef.h>
  42. // I can't #include config.h in this public API file, but I should
  43. // really use configure (and make malloc_extension.h a .in file) to
  44. // figure out if the system has stdint.h or not. But I'm lazy, so
  45. // for now I'm assuming it's a problem only with MSVC.
  46. #ifndef _MSC_VER
  47. #include <stdint.h>
  48. #endif
  49. #include <string>
  50. #include <vector>
  51. // Annoying stuff for windows -- makes sure clients can import these functions
  52. #ifndef PERFTOOLS_DLL_DECL
  53. # ifdef _WIN32
  54. # define PERFTOOLS_DLL_DECL __declspec(dllimport)
  55. # else
  56. # define PERFTOOLS_DLL_DECL
  57. # endif
  58. #endif
  59. static const int kMallocHistogramSize = 64;
  60. // One day, we could support other types of writers (perhaps for C?)
  61. typedef std::string MallocExtensionWriter;
  62. namespace base {
  63. struct MallocRange;
  64. }
  65. // Interface to a pluggable system allocator.
  66. class SysAllocator {
  67. public:
  68. SysAllocator() {
  69. }
  70. virtual ~SysAllocator();
  71. // Allocates "size"-byte of memory from system aligned with "alignment".
  72. // Returns NULL if failed. Otherwise, the returned pointer p up to and
  73. // including (p + actual_size -1) have been allocated.
  74. virtual void* Alloc(size_t size, size_t *actual_size, size_t alignment) = 0;
  75. };
  76. // The default implementations of the following routines do nothing.
  77. // All implementations should be thread-safe; the current one
  78. // (TCMallocImplementation) is.
  79. class PERFTOOLS_DLL_DECL MallocExtension {
  80. public:
  81. virtual ~MallocExtension();
  82. // Call this very early in the program execution -- say, in a global
  83. // constructor -- to set up parameters and state needed by all
  84. // instrumented malloc implemenatations. One example: this routine
  85. // sets environemnt variables to tell STL to use libc's malloc()
  86. // instead of doing its own memory management. This is safe to call
  87. // multiple times, as long as each time is before threads start up.
  88. static void Initialize();
  89. // See "verify_memory.h" to see what these routines do
  90. virtual bool VerifyAllMemory();
  91. // TODO(csilvers): change these to const void*.
  92. virtual bool VerifyNewMemory(void* p);
  93. virtual bool VerifyArrayNewMemory(void* p);
  94. virtual bool VerifyMallocMemory(void* p);
  95. virtual bool MallocMemoryStats(int* blocks, size_t* total,
  96. int histogram[kMallocHistogramSize]);
  97. // Get a human readable description of the current state of the malloc
  98. // data structures. The state is stored as a null-terminated string
  99. // in a prefix of "buffer[0,buffer_length-1]".
  100. // REQUIRES: buffer_length > 0.
  101. virtual void GetStats(char* buffer, int buffer_length);
  102. // Outputs to "writer" a sample of live objects and the stack traces
  103. // that allocated these objects. The format of the returned output
  104. // is equivalent to the output of the heap profiler and can
  105. // therefore be passed to "pprof". This function is equivalent to
  106. // ReadStackTraces. The main difference is that this function returns
  107. // serialized data appropriately formatted for use by the pprof tool.
  108. // NOTE: by default, tcmalloc does not do any heap sampling, and this
  109. // function will always return an empty sample. To get useful
  110. // data from GetHeapSample, you must also set the environment
  111. // variable TCMALLOC_SAMPLE_PARAMETER to a value such as 524288.
  112. virtual void GetHeapSample(MallocExtensionWriter* writer);
  113. // Outputs to "writer" the stack traces that caused growth in the
  114. // address space size. The format of the returned output is
  115. // equivalent to the output of the heap profiler and can therefore
  116. // be passed to "pprof". This function is equivalent to
  117. // ReadHeapGrowthStackTraces. The main difference is that this function
  118. // returns serialized data appropriately formatted for use by the
  119. // pprof tool. (This does not depend on, or require,
  120. // TCMALLOC_SAMPLE_PARAMETER.)
  121. virtual void GetHeapGrowthStacks(MallocExtensionWriter* writer);
  122. // Invokes func(arg, range) for every controlled memory
  123. // range. *range is filled in with information about the range.
  124. //
  125. // This is a best-effort interface useful only for performance
  126. // analysis. The implementation may not call func at all.
  127. typedef void (RangeFunction)(void*, const base::MallocRange*);
  128. virtual void Ranges(void* arg, RangeFunction func);
  129. // -------------------------------------------------------------------
  130. // Control operations for getting and setting malloc implementation
  131. // specific parameters. Some currently useful properties:
  132. //
  133. // generic
  134. // -------
  135. // "generic.current_allocated_bytes"
  136. // Number of bytes currently allocated by application
  137. // This property is not writable.
  138. //
  139. // "generic.heap_size"
  140. // Number of bytes in the heap ==
  141. // current_allocated_bytes +
  142. // fragmentation +
  143. // freed memory regions
  144. // This property is not writable.
  145. //
  146. // tcmalloc
  147. // --------
  148. // "tcmalloc.max_total_thread_cache_bytes"
  149. // Upper limit on total number of bytes stored across all
  150. // per-thread caches. Default: 16MB.
  151. //
  152. // "tcmalloc.current_total_thread_cache_bytes"
  153. // Number of bytes used across all thread caches.
  154. // This property is not writable.
  155. //
  156. // "tcmalloc.pageheap_free_bytes"
  157. // Number of bytes in free, mapped pages in page heap. These
  158. // bytes can be used to fulfill allocation requests. They
  159. // always count towards virtual memory usage, and unless the
  160. // underlying memory is swapped out by the OS, they also count
  161. // towards physical memory usage. This property is not writable.
  162. //
  163. // "tcmalloc.pageheap_unmapped_bytes"
  164. // Number of bytes in free, unmapped pages in page heap.
  165. // These are bytes that have been released back to the OS,
  166. // possibly by one of the MallocExtension "Release" calls.
  167. // They can be used to fulfill allocation requests, but
  168. // typically incur a page fault. They always count towards
  169. // virtual memory usage, and depending on the OS, typically
  170. // do not count towards physical memory usage. This property
  171. // is not writable.
  172. // -------------------------------------------------------------------
  173. // Get the named "property"'s value. Returns true if the property
  174. // is known. Returns false if the property is not a valid property
  175. // name for the current malloc implementation.
  176. // REQUIRES: property != NULL; value != NULL
  177. virtual bool GetNumericProperty(const char* property, size_t* value);
  178. // Set the named "property"'s value. Returns true if the property
  179. // is known and writable. Returns false if the property is not a
  180. // valid property name for the current malloc implementation, or
  181. // is not writable.
  182. // REQUIRES: property != NULL
  183. virtual bool SetNumericProperty(const char* property, size_t value);
  184. // Mark the current thread as "idle". This routine may optionally
  185. // be called by threads as a hint to the malloc implementation that
  186. // any thread-specific resources should be released. Note: this may
  187. // be an expensive routine, so it should not be called too often.
  188. //
  189. // Also, if the code that calls this routine will go to sleep for
  190. // a while, it should take care to not allocate anything between
  191. // the call to this routine and the beginning of the sleep.
  192. //
  193. // Most malloc implementations ignore this routine.
  194. virtual void MarkThreadIdle();
  195. // Mark the current thread as "busy". This routine should be
  196. // called after MarkThreadIdle() if the thread will now do more
  197. // work. If this method is not called, performance may suffer.
  198. //
  199. // Most malloc implementations ignore this routine.
  200. virtual void MarkThreadBusy();
  201. // Gets the system allocator used by the malloc extension instance. Returns
  202. // NULL for malloc implementations that do not support pluggable system
  203. // allocators.
  204. virtual SysAllocator* GetSystemAllocator();
  205. // Sets the system allocator to the specified.
  206. //
  207. // Users could register their own system allocators for malloc implementation
  208. // that supports pluggable system allocators, such as TCMalloc, by doing:
  209. // alloc = new MyOwnSysAllocator();
  210. // MallocExtension::instance()->SetSystemAllocator(alloc);
  211. // It's up to users whether to fall back (recommended) to the default
  212. // system allocator (use GetSystemAllocator() above) or not. The caller is
  213. // responsible to any necessary locking.
  214. // See tcmalloc/system-alloc.h for the interface and
  215. // tcmalloc/memfs_malloc.cc for the examples.
  216. //
  217. // It's a no-op for malloc implementations that do not support pluggable
  218. // system allocators.
  219. virtual void SetSystemAllocator(SysAllocator *a);
  220. // Try to release num_bytes of free memory back to the operating
  221. // system for reuse. Use this extension with caution -- to get this
  222. // memory back may require faulting pages back in by the OS, and
  223. // that may be slow. (Currently only implemented in tcmalloc.)
  224. virtual void ReleaseToSystem(size_t num_bytes);
  225. // Same as ReleaseToSystem() but release as much memory as possible.
  226. virtual void ReleaseFreeMemory();
  227. // Sets the rate at which we release unused memory to the system.
  228. // Zero means we never release memory back to the system. Increase
  229. // this flag to return memory faster; decrease it to return memory
  230. // slower. Reasonable rates are in the range [0,10]. (Currently
  231. // only implemented in tcmalloc).
  232. virtual void SetMemoryReleaseRate(double rate);
  233. // Gets the release rate. Returns a value < 0 if unknown.
  234. virtual double GetMemoryReleaseRate();
  235. // Returns the estimated number of bytes that will be allocated for
  236. // a request of "size" bytes. This is an estimate: an allocation of
  237. // SIZE bytes may reserve more bytes, but will never reserve less.
  238. // (Currently only implemented in tcmalloc, other implementations
  239. // always return SIZE.)
  240. // This is equivalent to malloc_good_size() in OS X.
  241. virtual size_t GetEstimatedAllocatedSize(size_t size);
  242. // Returns the actual number N of bytes reserved by tcmalloc for the
  243. // pointer p. The client is allowed to use the range of bytes
  244. // [p, p+N) in any way it wishes (i.e. N is the "usable size" of this
  245. // allocation). This number may be equal to or greater than the number
  246. // of bytes requested when p was allocated.
  247. // p must have been allocated by this malloc implementation,
  248. // must not be an interior pointer -- that is, must be exactly
  249. // the pointer returned to by malloc() et al., not some offset
  250. // from that -- and should not have been freed yet. p may be NULL.
  251. // (Currently only implemented in tcmalloc; other implementations
  252. // will return 0.)
  253. // This is equivalent to malloc_size() in OS X, malloc_usable_size()
  254. // in glibc, and _msize() for windows.
  255. // TODO(csilvers): change to const void*.
  256. virtual size_t GetAllocatedSize(void* p);
  257. // Returns kOwned if this malloc implementation allocated the memory
  258. // pointed to by p, or kNotOwned if some other malloc implementation
  259. // allocated it or p is NULL. May also return kUnknownOwnership if
  260. // the malloc implementation does not keep track of ownership.
  261. // REQUIRES: p must be a value returned from a previous call to
  262. // malloc(), calloc(), realloc(), memalign(), posix_memalign(),
  263. // valloc(), pvalloc(), new, or new[], and must refer to memory that
  264. // is currently allocated (so, for instance, you should not pass in
  265. // a pointer after having called free() on it).
  266. enum Ownership {
  267. // NOTE: Enum values MUST be kept in sync with the version in
  268. // malloc_extension_c.h
  269. kUnknownOwnership = 0,
  270. kOwned,
  271. kNotOwned
  272. };
  273. virtual Ownership GetOwnership(const void* p);
  274. // The current malloc implementation. Always non-NULL.
  275. static MallocExtension* instance();
  276. // Change the malloc implementation. Typically called by the
  277. // malloc implementation during initialization.
  278. static void Register(MallocExtension* implementation);
  279. // Returns detailed information about malloc's freelists. For each list,
  280. // return a FreeListInfo:
  281. struct FreeListInfo {
  282. size_t min_object_size;
  283. size_t max_object_size;
  284. size_t total_bytes_free;
  285. const char* type;
  286. };
  287. // Each item in the vector refers to a different freelist. The lists
  288. // are identified by the range of allocations that objects in the
  289. // list can satisfy ([min_object_size, max_object_size]) and the
  290. // type of freelist (see below). The current size of the list is
  291. // returned in total_bytes_free (which count against a processes
  292. // resident and virtual size).
  293. //
  294. // Currently supported types are:
  295. //
  296. // "tcmalloc.page{_unmapped}" - tcmalloc's page heap. An entry for each size
  297. // class in the page heap is returned. Bytes in "page_unmapped"
  298. // are no longer backed by physical memory and do not count against
  299. // the resident size of a process.
  300. //
  301. // "tcmalloc.large{_unmapped}" - tcmalloc's list of objects larger
  302. // than the largest page heap size class. Only one "large"
  303. // entry is returned. There is no upper-bound on the size
  304. // of objects in the large free list; this call returns
  305. // kint64max for max_object_size. Bytes in
  306. // "large_unmapped" are no longer backed by physical memory
  307. // and do not count against the resident size of a process.
  308. //
  309. // "tcmalloc.central" - tcmalloc's central free-list. One entry per
  310. // size-class is returned. Never unmapped.
  311. //
  312. // "debug.free_queue" - free objects queued by the debug allocator
  313. // and not returned to tcmalloc.
  314. //
  315. // "tcmalloc.thread" - tcmalloc's per-thread caches. Never unmapped.
  316. virtual void GetFreeListSizes(std::vector<FreeListInfo>* v);
  317. // Get a list of stack traces of sampled allocation points. Returns
  318. // a pointer to a "new[]-ed" result array, and stores the sample
  319. // period in "sample_period".
  320. //
  321. // The state is stored as a sequence of adjacent entries
  322. // in the returned array. Each entry has the following form:
  323. // uintptr_t count; // Number of objects with following trace
  324. // uintptr_t size; // Total size of objects with following trace
  325. // uintptr_t depth; // Number of PC values in stack trace
  326. // void* stack[depth]; // PC values that form the stack trace
  327. //
  328. // The list of entries is terminated by a "count" of 0.
  329. //
  330. // It is the responsibility of the caller to "delete[]" the returned array.
  331. //
  332. // May return NULL to indicate no results.
  333. //
  334. // This is an internal extension. Callers should use the more
  335. // convenient "GetHeapSample(string*)" method defined above.
  336. virtual void** ReadStackTraces(int* sample_period);
  337. // Like ReadStackTraces(), but returns stack traces that caused growth
  338. // in the address space size.
  339. virtual void** ReadHeapGrowthStackTraces();
  340. };
  341. namespace base {
  342. // Information passed per range. More fields may be added later.
  343. struct MallocRange {
  344. enum Type {
  345. INUSE, // Application is using this range
  346. FREE, // Range is currently free
  347. UNMAPPED, // Backing physical memory has been returned to the OS
  348. UNKNOWN,
  349. // More enum values may be added in the future
  350. };
  351. uintptr_t address; // Address of range
  352. size_t length; // Byte length of range
  353. Type type; // Type of this range
  354. double fraction; // Fraction of range that is being used (0 if !INUSE)
  355. // Perhaps add the following:
  356. // - stack trace if this range was sampled
  357. // - heap growth stack trace if applicable to this range
  358. // - age when allocated (for inuse) or freed (if not in use)
  359. };
  360. } // namespace base
  361. #endif // BASE_MALLOC_EXTENSION_H_