blob: 9ec663e25b4be5e25111073490b4bc6a87229955 [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// A malloc that uses a per-thread cache to satisfy small malloc requests.
35// (The time for malloc/free of a small object drops from 300 ns to 50 ns.)
36//
Brian Silverman20350ac2021-11-17 18:19:55 -080037// See docs/tcmalloc.html for a high-level
Austin Schuh745610d2015-09-06 18:19:50 -070038// description of how this malloc works.
39//
40// SYNCHRONIZATION
41// 1. The thread-specific lists are accessed without acquiring any locks.
42// This is safe because each such list is only accessed by one thread.
43// 2. We have a lock per central free-list, and hold it while manipulating
44// the central free list for a particular size.
45// 3. The central page allocator is protected by "pageheap_lock".
46// 4. The pagemap (which maps from page-number to descriptor),
47// can be read without holding any locks, and written while holding
48// the "pageheap_lock".
49// 5. To improve performance, a subset of the information one can get
50// from the pagemap is cached in a data structure, pagemap_cache_,
51// that atomically reads and writes its entries. This cache can be
52// read and written without locking.
53//
54// This multi-threaded access to the pagemap is safe for fairly
55// subtle reasons. We basically assume that when an object X is
56// allocated by thread A and deallocated by thread B, there must
57// have been appropriate synchronization in the handoff of object
58// X from thread A to thread B. The same logic applies to pagemap_cache_.
59//
60// THE PAGEID-TO-SIZECLASS CACHE
61// Hot PageID-to-sizeclass mappings are held by pagemap_cache_. If this cache
62// returns 0 for a particular PageID then that means "no information," not that
63// the sizeclass is 0. The cache may have stale information for pages that do
64// not hold the beginning of any free()'able object. Staleness is eliminated
65// in Populate() for pages with sizeclass > 0 objects, and in do_malloc() and
66// do_memalign() for all other relevant pages.
67//
68// PAGEMAP
69// -------
70// Page map contains a mapping from page id to Span.
71//
72// If Span s occupies pages [p..q],
73// pagemap[p] == s
74// pagemap[q] == s
75// pagemap[p+1..q-1] are undefined
76// pagemap[p-1] and pagemap[q+1] are defined:
77// NULL if the corresponding page is not yet in the address space.
78// Otherwise it points to a Span. This span may be free
79// or allocated. If free, it is in one of pageheap's freelist.
80//
81// TODO: Bias reclamation to larger addresses
82// TODO: implement mallinfo/mallopt
83// TODO: Better testing
84//
85// 9/28/2003 (new page-level allocator replaces ptmalloc2):
86// * malloc/free of small objects goes from ~300 ns to ~50 ns.
87// * allocation of a reasonably complicated struct
88// goes from about 1100 ns to about 300 ns.
89
90#include "config.h"
Brian Silverman20350ac2021-11-17 18:19:55 -080091// At least for gcc on Linux/i386 and Linux/amd64 not adding throw()
92// to tc_xxx functions actually ends up generating better code.
93#define PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -070094#include <gperftools/tcmalloc.h>
95
96#include <errno.h> // for ENOMEM, EINVAL, errno
Austin Schuh745610d2015-09-06 18:19:50 -070097#if defined HAVE_STDINT_H
98#include <stdint.h>
99#elif defined HAVE_INTTYPES_H
100#include <inttypes.h>
101#else
102#include <sys/types.h>
103#endif
104#include <stddef.h> // for size_t, NULL
105#include <stdlib.h> // for getenv
106#include <string.h> // for strcmp, memset, strlen, etc
107#ifdef HAVE_UNISTD_H
108#include <unistd.h> // for getpagesize, write, etc
109#endif
110#include <algorithm> // for max, min
111#include <limits> // for numeric_limits
112#include <new> // for nothrow_t (ptr only), etc
113#include <vector> // for vector
114
115#include <gperftools/malloc_extension.h>
116#include <gperftools/malloc_hook.h> // for MallocHook
Brian Silverman20350ac2021-11-17 18:19:55 -0800117#include <gperftools/nallocx.h>
Austin Schuh745610d2015-09-06 18:19:50 -0700118#include "base/basictypes.h" // for int64
119#include "base/commandlineflags.h" // for RegisterFlagValidator, etc
120#include "base/dynamic_annotations.h" // for RunningOnValgrind
121#include "base/spinlock.h" // for SpinLockHolder
122#include "central_freelist.h" // for CentralFreeListPadded
123#include "common.h" // for StackTrace, kPageShift, etc
124#include "internal_logging.h" // for ASSERT, TCMalloc_Printer, etc
125#include "linked_list.h" // for SLL_SetNext
126#include "malloc_hook-inl.h" // for MallocHook::InvokeNewHook, etc
127#include "page_heap.h" // for PageHeap, PageHeap::Stats
128#include "page_heap_allocator.h" // for PageHeapAllocator
129#include "span.h" // for Span, DLL_Prepend, etc
130#include "stack_trace_table.h" // for StackTraceTable
131#include "static_vars.h" // for Static
132#include "system-alloc.h" // for DumpSystemAllocatorStats, etc
133#include "tcmalloc_guard.h" // for TCMallocGuard
134#include "thread_cache.h" // for ThreadCache
135
Brian Silverman20350ac2021-11-17 18:19:55 -0800136#include "maybe_emergency_malloc.h"
Austin Schuh745610d2015-09-06 18:19:50 -0700137
138#if (defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)) && !defined(WIN32_OVERRIDE_ALLOCATORS)
139# define WIN32_DO_PATCHING 1
140#endif
141
142// Some windows file somewhere (at least on cygwin) #define's small (!)
143#undef small
144
Brian Silverman20350ac2021-11-17 18:19:55 -0800145using std::max;
146using std::min;
147using std::numeric_limits;
148using std::vector;
Austin Schuh745610d2015-09-06 18:19:50 -0700149
150#include "libc_override.h"
151
Austin Schuh745610d2015-09-06 18:19:50 -0700152using tcmalloc::AlignmentForSize;
153using tcmalloc::kLog;
154using tcmalloc::kCrash;
155using tcmalloc::kCrashWithStats;
156using tcmalloc::Log;
157using tcmalloc::PageHeap;
158using tcmalloc::PageHeapAllocator;
159using tcmalloc::SizeMap;
160using tcmalloc::Span;
161using tcmalloc::StackTrace;
162using tcmalloc::Static;
163using tcmalloc::ThreadCache;
164
Austin Schuh745610d2015-09-06 18:19:50 -0700165DECLARE_double(tcmalloc_release_rate);
Brian Silverman20350ac2021-11-17 18:19:55 -0800166DECLARE_int64(tcmalloc_heap_limit_mb);
167
168// Those common architectures are known to be safe w.r.t. aliasing function
169// with "extra" unused args to function with fewer arguments (e.g.
170// tc_delete_nothrow being aliased to tc_delete).
171//
172// Benefit of aliasing is relatively moderate. It reduces instruction
173// cache pressure a bit (not relevant for largely unused
174// tc_delete_nothrow, but is potentially relevant for
175// tc_delete_aligned (or sized)). It also used to be the case that gcc
176// 5+ optimization for merging identical functions kicked in and
177// "screwed" one of the otherwise identical functions with extra
178// jump. I am not able to reproduce that anymore.
179#if !defined(__i386__) && !defined(__x86_64__) && \
180 !defined(__ppc__) && !defined(__PPC__) && \
181 !defined(__aarch64__) && !defined(__mips__) && !defined(__arm__)
182#undef TCMALLOC_NO_ALIASES
183#define TCMALLOC_NO_ALIASES
184#endif
185
186#if defined(__GNUC__) && defined(__ELF__) && !defined(TCMALLOC_NO_ALIASES)
187#define TC_ALIAS(name) __attribute__((alias(#name)))
188#endif
Austin Schuh745610d2015-09-06 18:19:50 -0700189
190// For windows, the printf we use to report large allocs is
191// potentially dangerous: it could cause a malloc that would cause an
192// infinite loop. So by default we set the threshold to a huge number
193// on windows, so this bad situation will never trigger. You can
194// always set TCMALLOC_LARGE_ALLOC_REPORT_THRESHOLD manually if you
195// want this functionality.
196#ifdef _WIN32
197const int64 kDefaultLargeAllocReportThreshold = static_cast<int64>(1) << 62;
198#else
199const int64 kDefaultLargeAllocReportThreshold = static_cast<int64>(1) << 30;
200#endif
201DEFINE_int64(tcmalloc_large_alloc_report_threshold,
202 EnvToInt64("TCMALLOC_LARGE_ALLOC_REPORT_THRESHOLD",
203 kDefaultLargeAllocReportThreshold),
204 "Allocations larger than this value cause a stack "
205 "trace to be dumped to stderr. The threshold for "
206 "dumping stack traces is increased by a factor of 1.125 "
207 "every time we print a message so that the threshold "
208 "automatically goes up by a factor of ~1000 every 60 "
209 "messages. This bounds the amount of extra logging "
210 "generated by this flag. Default value of this flag "
211 "is very large and therefore you should see no extra "
212 "logging unless the flag is overridden. Set to 0 to "
213 "disable reporting entirely.");
214
215
216// We already declared these functions in tcmalloc.h, but we have to
217// declare them again to give them an ATTRIBUTE_SECTION: we want to
218// put all callers of MallocHook::Invoke* in this module into
219// ATTRIBUTE_SECTION(google_malloc) section, so that
220// MallocHook::GetCallerStackTrace can function accurately.
221#ifndef _WIN32 // windows doesn't have attribute_section, so don't bother
222extern "C" {
Brian Silverman20350ac2021-11-17 18:19:55 -0800223 void* tc_malloc(size_t size) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700224 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800225 void tc_free(void* ptr) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700226 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800227 void tc_free_sized(void* ptr, size_t size) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700228 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800229 void* tc_realloc(void* ptr, size_t size) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700230 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800231 void* tc_calloc(size_t nmemb, size_t size) PERFTOOLS_NOTHROW
232 ATTRIBUTE_SECTION(google_malloc);
233 void tc_cfree(void* ptr) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700234 ATTRIBUTE_SECTION(google_malloc);
235
Brian Silverman20350ac2021-11-17 18:19:55 -0800236 void* tc_memalign(size_t __alignment, size_t __size) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700237 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800238 int tc_posix_memalign(void** ptr, size_t align, size_t size) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700239 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800240 void* tc_valloc(size_t __size) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700241 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800242 void* tc_pvalloc(size_t __size) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700243 ATTRIBUTE_SECTION(google_malloc);
244
Brian Silverman20350ac2021-11-17 18:19:55 -0800245 void tc_malloc_stats(void) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700246 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800247 int tc_mallopt(int cmd, int value) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700248 ATTRIBUTE_SECTION(google_malloc);
249#ifdef HAVE_STRUCT_MALLINFO
Brian Silverman20350ac2021-11-17 18:19:55 -0800250 struct mallinfo tc_mallinfo(void) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700251 ATTRIBUTE_SECTION(google_malloc);
252#endif
253
254 void* tc_new(size_t size)
255 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800256 void tc_delete(void* p) PERFTOOLS_NOTHROW
257 ATTRIBUTE_SECTION(google_malloc);
258 void tc_delete_sized(void* p, size_t size) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700259 ATTRIBUTE_SECTION(google_malloc);
260 void* tc_newarray(size_t size)
261 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800262 void tc_deletearray(void* p) PERFTOOLS_NOTHROW
263 ATTRIBUTE_SECTION(google_malloc);
264 void tc_deletearray_sized(void* p, size_t size) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700265 ATTRIBUTE_SECTION(google_malloc);
266
267 // And the nothrow variants of these:
Brian Silverman20350ac2021-11-17 18:19:55 -0800268 void* tc_new_nothrow(size_t size, const std::nothrow_t&) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700269 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800270 void* tc_newarray_nothrow(size_t size, const std::nothrow_t&) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700271 ATTRIBUTE_SECTION(google_malloc);
272 // Surprisingly, standard C++ library implementations use a
273 // nothrow-delete internally. See, eg:
274 // http://www.dinkumware.com/manuals/?manual=compleat&page=new.html
Brian Silverman20350ac2021-11-17 18:19:55 -0800275 void tc_delete_nothrow(void* ptr, const std::nothrow_t&) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700276 ATTRIBUTE_SECTION(google_malloc);
Brian Silverman20350ac2021-11-17 18:19:55 -0800277 void tc_deletearray_nothrow(void* ptr, const std::nothrow_t&) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700278 ATTRIBUTE_SECTION(google_malloc);
279
Brian Silverman20350ac2021-11-17 18:19:55 -0800280#if defined(ENABLE_ALIGNED_NEW_DELETE)
281
282 void* tc_new_aligned(size_t size, std::align_val_t al)
283 ATTRIBUTE_SECTION(google_malloc);
284 void tc_delete_aligned(void* p, std::align_val_t al) PERFTOOLS_NOTHROW
285 ATTRIBUTE_SECTION(google_malloc);
286 void tc_delete_sized_aligned(void* p, size_t size, std::align_val_t al) PERFTOOLS_NOTHROW
287 ATTRIBUTE_SECTION(google_malloc);
288 void* tc_newarray_aligned(size_t size, std::align_val_t al)
289 ATTRIBUTE_SECTION(google_malloc);
290 void tc_deletearray_aligned(void* p, std::align_val_t al) PERFTOOLS_NOTHROW
291 ATTRIBUTE_SECTION(google_malloc);
292 void tc_deletearray_sized_aligned(void* p, size_t size, std::align_val_t al) PERFTOOLS_NOTHROW
293 ATTRIBUTE_SECTION(google_malloc);
294
295 // And the nothrow variants of these:
296 void* tc_new_aligned_nothrow(size_t size, std::align_val_t al, const std::nothrow_t&) PERFTOOLS_NOTHROW
297 ATTRIBUTE_SECTION(google_malloc);
298 void* tc_newarray_aligned_nothrow(size_t size, std::align_val_t al, const std::nothrow_t&) PERFTOOLS_NOTHROW
299 ATTRIBUTE_SECTION(google_malloc);
300 void tc_delete_aligned_nothrow(void* ptr, std::align_val_t al, const std::nothrow_t&) PERFTOOLS_NOTHROW
301 ATTRIBUTE_SECTION(google_malloc);
302 void tc_deletearray_aligned_nothrow(void* ptr, std::align_val_t al, const std::nothrow_t&) PERFTOOLS_NOTHROW
303 ATTRIBUTE_SECTION(google_malloc);
304
305#endif // defined(ENABLE_ALIGNED_NEW_DELETE)
306
Austin Schuh745610d2015-09-06 18:19:50 -0700307 // Some non-standard extensions that we support.
308
309 // This is equivalent to
310 // OS X: malloc_size()
311 // glibc: malloc_usable_size()
312 // Windows: _msize()
Brian Silverman20350ac2021-11-17 18:19:55 -0800313 size_t tc_malloc_size(void* p) PERFTOOLS_NOTHROW
Austin Schuh745610d2015-09-06 18:19:50 -0700314 ATTRIBUTE_SECTION(google_malloc);
315} // extern "C"
316#endif // #ifndef _WIN32
317
318// ----------------------- IMPLEMENTATION -------------------------------
319
320static int tc_new_mode = 0; // See tc_set_new_mode().
321
322// Routines such as free() and realloc() catch some erroneous pointers
323// passed to them, and invoke the below when they do. (An erroneous pointer
324// won't be caught if it's within a valid span or a stale span for which
325// the pagemap cache has a non-zero sizeclass.) This is a cheap (source-editing
326// required) kind of exception handling for these routines.
327namespace {
Brian Silverman20350ac2021-11-17 18:19:55 -0800328ATTRIBUTE_NOINLINE void InvalidFree(void* ptr) {
329 if (tcmalloc::IsEmergencyPtr(ptr)) {
330 tcmalloc::EmergencyFree(ptr);
331 return;
332 }
Austin Schuh745610d2015-09-06 18:19:50 -0700333 Log(kCrash, __FILE__, __LINE__, "Attempt to free invalid pointer", ptr);
334}
335
336size_t InvalidGetSizeForRealloc(const void* old_ptr) {
337 Log(kCrash, __FILE__, __LINE__,
338 "Attempt to realloc invalid pointer", old_ptr);
339 return 0;
340}
341
342size_t InvalidGetAllocatedSize(const void* ptr) {
343 Log(kCrash, __FILE__, __LINE__,
344 "Attempt to get the size of an invalid pointer", ptr);
345 return 0;
346}
347} // unnamed namespace
348
349// Extract interesting stats
350struct TCMallocStats {
351 uint64_t thread_bytes; // Bytes in thread caches
352 uint64_t central_bytes; // Bytes in central cache
353 uint64_t transfer_bytes; // Bytes in central transfer cache
354 uint64_t metadata_bytes; // Bytes alloced for metadata
355 PageHeap::Stats pageheap; // Stats from page heap
356};
357
358// Get stats into "r". Also, if class_count != NULL, class_count[k]
359// will be set to the total number of objects of size class k in the
360// central cache, transfer cache, and per-thread caches. If small_spans
361// is non-NULL, it is filled. Same for large_spans.
362static void ExtractStats(TCMallocStats* r, uint64_t* class_count,
363 PageHeap::SmallSpanStats* small_spans,
364 PageHeap::LargeSpanStats* large_spans) {
365 r->central_bytes = 0;
366 r->transfer_bytes = 0;
Brian Silverman20350ac2021-11-17 18:19:55 -0800367 for (int cl = 0; cl < Static::num_size_classes(); ++cl) {
Austin Schuh745610d2015-09-06 18:19:50 -0700368 const int length = Static::central_cache()[cl].length();
369 const int tc_length = Static::central_cache()[cl].tc_length();
370 const size_t cache_overhead = Static::central_cache()[cl].OverheadBytes();
371 const size_t size = static_cast<uint64_t>(
372 Static::sizemap()->ByteSizeForClass(cl));
373 r->central_bytes += (size * length) + cache_overhead;
374 r->transfer_bytes += (size * tc_length);
375 if (class_count) {
376 // Sum the lengths of all per-class freelists, except the per-thread
377 // freelists, which get counted when we call GetThreadStats(), below.
378 class_count[cl] = length + tc_length;
379 }
380
381 }
382
383 // Add stats from per-thread heaps
384 r->thread_bytes = 0;
385 { // scope
386 SpinLockHolder h(Static::pageheap_lock());
387 ThreadCache::GetThreadStats(&r->thread_bytes, class_count);
388 r->metadata_bytes = tcmalloc::metadata_system_bytes();
389 r->pageheap = Static::pageheap()->stats();
390 if (small_spans != NULL) {
391 Static::pageheap()->GetSmallSpanStats(small_spans);
392 }
393 if (large_spans != NULL) {
394 Static::pageheap()->GetLargeSpanStats(large_spans);
395 }
396 }
397}
398
399static double PagesToMiB(uint64_t pages) {
400 return (pages << kPageShift) / 1048576.0;
401}
402
403// WRITE stats to "out"
404static void DumpStats(TCMalloc_Printer* out, int level) {
405 TCMallocStats stats;
Brian Silverman20350ac2021-11-17 18:19:55 -0800406 uint64_t class_count[kClassSizesMax];
Austin Schuh745610d2015-09-06 18:19:50 -0700407 PageHeap::SmallSpanStats small;
408 PageHeap::LargeSpanStats large;
409 if (level >= 2) {
410 ExtractStats(&stats, class_count, &small, &large);
411 } else {
412 ExtractStats(&stats, NULL, NULL, NULL);
413 }
414
415 static const double MiB = 1048576.0;
416
417 const uint64_t virtual_memory_used = (stats.pageheap.system_bytes
418 + stats.metadata_bytes);
419 const uint64_t physical_memory_used = (virtual_memory_used
420 - stats.pageheap.unmapped_bytes);
421 const uint64_t bytes_in_use_by_app = (physical_memory_used
422 - stats.metadata_bytes
423 - stats.pageheap.free_bytes
424 - stats.central_bytes
425 - stats.transfer_bytes
426 - stats.thread_bytes);
427
428#ifdef TCMALLOC_SMALL_BUT_SLOW
429 out->printf(
430 "NOTE: SMALL MEMORY MODEL IS IN USE, PERFORMANCE MAY SUFFER.\n");
431#endif
432 out->printf(
433 "------------------------------------------------\n"
434 "MALLOC: %12" PRIu64 " (%7.1f MiB) Bytes in use by application\n"
435 "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes in page heap freelist\n"
436 "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes in central cache freelist\n"
437 "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes in transfer cache freelist\n"
438 "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes in thread cache freelists\n"
439 "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes in malloc metadata\n"
440 "MALLOC: ------------\n"
441 "MALLOC: = %12" PRIu64 " (%7.1f MiB) Actual memory used (physical + swap)\n"
442 "MALLOC: + %12" PRIu64 " (%7.1f MiB) Bytes released to OS (aka unmapped)\n"
443 "MALLOC: ------------\n"
444 "MALLOC: = %12" PRIu64 " (%7.1f MiB) Virtual address space used\n"
445 "MALLOC:\n"
446 "MALLOC: %12" PRIu64 " Spans in use\n"
447 "MALLOC: %12" PRIu64 " Thread heaps in use\n"
448 "MALLOC: %12" PRIu64 " Tcmalloc page size\n"
449 "------------------------------------------------\n"
450 "Call ReleaseFreeMemory() to release freelist memory to the OS"
451 " (via madvise()).\n"
452 "Bytes released to the OS take up virtual address space"
453 " but no physical memory.\n",
454 bytes_in_use_by_app, bytes_in_use_by_app / MiB,
455 stats.pageheap.free_bytes, stats.pageheap.free_bytes / MiB,
456 stats.central_bytes, stats.central_bytes / MiB,
457 stats.transfer_bytes, stats.transfer_bytes / MiB,
458 stats.thread_bytes, stats.thread_bytes / MiB,
459 stats.metadata_bytes, stats.metadata_bytes / MiB,
460 physical_memory_used, physical_memory_used / MiB,
461 stats.pageheap.unmapped_bytes, stats.pageheap.unmapped_bytes / MiB,
462 virtual_memory_used, virtual_memory_used / MiB,
463 uint64_t(Static::span_allocator()->inuse()),
464 uint64_t(ThreadCache::HeapsInUse()),
465 uint64_t(kPageSize));
466
467 if (level >= 2) {
468 out->printf("------------------------------------------------\n");
469 out->printf("Total size of freelists for per-thread caches,\n");
470 out->printf("transfer cache, and central cache, by size class\n");
471 out->printf("------------------------------------------------\n");
Brian Silverman20350ac2021-11-17 18:19:55 -0800472 uint64_t cumulative_bytes = 0;
473 uint64_t cumulative_overhead = 0;
474 for (uint32 cl = 0; cl < Static::num_size_classes(); ++cl) {
Austin Schuh745610d2015-09-06 18:19:50 -0700475 if (class_count[cl] > 0) {
Brian Silverman20350ac2021-11-17 18:19:55 -0800476 size_t cl_size = Static::sizemap()->ByteSizeForClass(cl);
477 const uint64_t class_bytes = class_count[cl] * cl_size;
478 cumulative_bytes += class_bytes;
479 const uint64_t class_overhead =
480 Static::central_cache()[cl].OverheadBytes();
481 cumulative_overhead += class_overhead;
482 out->printf("class %3d [ %8zu bytes ] : "
483 "%8" PRIu64 " objs; %5.1f MiB; %5.1f cum MiB; "
484 "%8.3f overhead MiB; %8.3f cum overhead MiB\n",
485 cl, cl_size,
Austin Schuh745610d2015-09-06 18:19:50 -0700486 class_count[cl],
487 class_bytes / MiB,
Brian Silverman20350ac2021-11-17 18:19:55 -0800488 cumulative_bytes / MiB,
489 class_overhead / MiB,
490 cumulative_overhead / MiB);
Austin Schuh745610d2015-09-06 18:19:50 -0700491 }
492 }
493
494 // append page heap info
495 int nonempty_sizes = 0;
496 for (int s = 0; s < kMaxPages; s++) {
497 if (small.normal_length[s] + small.returned_length[s] > 0) {
498 nonempty_sizes++;
499 }
500 }
501 out->printf("------------------------------------------------\n");
502 out->printf("PageHeap: %d sizes; %6.1f MiB free; %6.1f MiB unmapped\n",
503 nonempty_sizes, stats.pageheap.free_bytes / MiB,
504 stats.pageheap.unmapped_bytes / MiB);
505 out->printf("------------------------------------------------\n");
506 uint64_t total_normal = 0;
507 uint64_t total_returned = 0;
Brian Silverman20350ac2021-11-17 18:19:55 -0800508 for (int s = 1; s <= kMaxPages; s++) {
509 const int n_length = small.normal_length[s - 1];
510 const int r_length = small.returned_length[s - 1];
Austin Schuh745610d2015-09-06 18:19:50 -0700511 if (n_length + r_length > 0) {
512 uint64_t n_pages = s * n_length;
513 uint64_t r_pages = s * r_length;
514 total_normal += n_pages;
515 total_returned += r_pages;
516 out->printf("%6u pages * %6u spans ~ %6.1f MiB; %6.1f MiB cum"
517 "; unmapped: %6.1f MiB; %6.1f MiB cum\n",
518 s,
519 (n_length + r_length),
520 PagesToMiB(n_pages + r_pages),
521 PagesToMiB(total_normal + total_returned),
522 PagesToMiB(r_pages),
523 PagesToMiB(total_returned));
524 }
525 }
526
527 total_normal += large.normal_pages;
528 total_returned += large.returned_pages;
Brian Silverman20350ac2021-11-17 18:19:55 -0800529 out->printf(">%-5u large * %6u spans ~ %6.1f MiB; %6.1f MiB cum"
Austin Schuh745610d2015-09-06 18:19:50 -0700530 "; unmapped: %6.1f MiB; %6.1f MiB cum\n",
Brian Silverman20350ac2021-11-17 18:19:55 -0800531 static_cast<unsigned int>(kMaxPages),
Austin Schuh745610d2015-09-06 18:19:50 -0700532 static_cast<unsigned int>(large.spans),
533 PagesToMiB(large.normal_pages + large.returned_pages),
534 PagesToMiB(total_normal + total_returned),
535 PagesToMiB(large.returned_pages),
536 PagesToMiB(total_returned));
537 }
538}
539
540static void PrintStats(int level) {
541 const int kBufferSize = 16 << 10;
542 char* buffer = new char[kBufferSize];
543 TCMalloc_Printer printer(buffer, kBufferSize);
544 DumpStats(&printer, level);
545 write(STDERR_FILENO, buffer, strlen(buffer));
546 delete[] buffer;
547}
548
549static void** DumpHeapGrowthStackTraces() {
550 // Count how much space we need
551 int needed_slots = 0;
552 {
553 SpinLockHolder h(Static::pageheap_lock());
554 for (StackTrace* t = Static::growth_stacks();
555 t != NULL;
556 t = reinterpret_cast<StackTrace*>(
557 t->stack[tcmalloc::kMaxStackDepth-1])) {
558 needed_slots += 3 + t->depth;
559 }
560 needed_slots += 100; // Slop in case list grows
561 needed_slots += needed_slots/8; // An extra 12.5% slop
562 }
563
564 void** result = new void*[needed_slots];
565 if (result == NULL) {
566 Log(kLog, __FILE__, __LINE__,
567 "tcmalloc: allocation failed for stack trace slots",
568 needed_slots * sizeof(*result));
569 return NULL;
570 }
571
572 SpinLockHolder h(Static::pageheap_lock());
573 int used_slots = 0;
574 for (StackTrace* t = Static::growth_stacks();
575 t != NULL;
576 t = reinterpret_cast<StackTrace*>(
577 t->stack[tcmalloc::kMaxStackDepth-1])) {
578 ASSERT(used_slots < needed_slots); // Need to leave room for terminator
579 if (used_slots + 3 + t->depth >= needed_slots) {
580 // No more room
581 break;
582 }
583
584 result[used_slots+0] = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
585 result[used_slots+1] = reinterpret_cast<void*>(t->size);
586 result[used_slots+2] = reinterpret_cast<void*>(t->depth);
587 for (int d = 0; d < t->depth; d++) {
588 result[used_slots+3+d] = t->stack[d];
589 }
590 used_slots += 3 + t->depth;
591 }
592 result[used_slots] = reinterpret_cast<void*>(static_cast<uintptr_t>(0));
593 return result;
594}
595
596static void IterateOverRanges(void* arg, MallocExtension::RangeFunction func) {
597 PageID page = 1; // Some code may assume that page==0 is never used
598 bool done = false;
599 while (!done) {
600 // Accumulate a small number of ranges in a local buffer
601 static const int kNumRanges = 16;
602 static base::MallocRange ranges[kNumRanges];
603 int n = 0;
604 {
605 SpinLockHolder h(Static::pageheap_lock());
606 while (n < kNumRanges) {
607 if (!Static::pageheap()->GetNextRange(page, &ranges[n])) {
608 done = true;
609 break;
610 } else {
611 uintptr_t limit = ranges[n].address + ranges[n].length;
612 page = (limit + kPageSize - 1) >> kPageShift;
613 n++;
614 }
615 }
616 }
617
618 for (int i = 0; i < n; i++) {
619 (*func)(arg, &ranges[i]);
620 }
621 }
622}
623
624// TCMalloc's support for extra malloc interfaces
625class TCMallocImplementation : public MallocExtension {
626 private:
627 // ReleaseToSystem() might release more than the requested bytes because
628 // the page heap releases at the span granularity, and spans are of wildly
629 // different sizes. This member keeps track of the extra bytes bytes
630 // released so that the app can periodically call ReleaseToSystem() to
631 // release memory at a constant rate.
632 // NOTE: Protected by Static::pageheap_lock().
633 size_t extra_bytes_released_;
634
635 public:
636 TCMallocImplementation()
637 : extra_bytes_released_(0) {
638 }
639
640 virtual void GetStats(char* buffer, int buffer_length) {
641 ASSERT(buffer_length > 0);
642 TCMalloc_Printer printer(buffer, buffer_length);
643
644 // Print level one stats unless lots of space is available
645 if (buffer_length < 10000) {
646 DumpStats(&printer, 1);
647 } else {
648 DumpStats(&printer, 2);
649 }
650 }
651
652 // We may print an extra, tcmalloc-specific warning message here.
653 virtual void GetHeapSample(MallocExtensionWriter* writer) {
654 if (FLAGS_tcmalloc_sample_parameter == 0) {
655 const char* const kWarningMsg =
656 "%warn\n"
657 "%warn This heap profile does not have any data in it, because\n"
658 "%warn the application was run with heap sampling turned off.\n"
659 "%warn To get useful data from GetHeapSample(), you must\n"
660 "%warn set the environment variable TCMALLOC_SAMPLE_PARAMETER to\n"
661 "%warn a positive sampling period, such as 524288.\n"
662 "%warn\n";
663 writer->append(kWarningMsg, strlen(kWarningMsg));
664 }
665 MallocExtension::GetHeapSample(writer);
666 }
667
668 virtual void** ReadStackTraces(int* sample_period) {
669 tcmalloc::StackTraceTable table;
670 {
671 SpinLockHolder h(Static::pageheap_lock());
672 Span* sampled = Static::sampled_objects();
673 for (Span* s = sampled->next; s != sampled; s = s->next) {
674 table.AddTrace(*reinterpret_cast<StackTrace*>(s->objects));
675 }
676 }
677 *sample_period = ThreadCache::GetCache()->GetSamplePeriod();
678 return table.ReadStackTracesAndClear(); // grabs and releases pageheap_lock
679 }
680
681 virtual void** ReadHeapGrowthStackTraces() {
682 return DumpHeapGrowthStackTraces();
683 }
684
Brian Silverman20350ac2021-11-17 18:19:55 -0800685 virtual size_t GetThreadCacheSize() {
686 ThreadCache* tc = ThreadCache::GetCacheIfPresent();
687 if (!tc)
688 return 0;
689 return tc->Size();
690 }
691
692 virtual void MarkThreadTemporarilyIdle() {
693 ThreadCache::BecomeTemporarilyIdle();
694 }
695
Austin Schuh745610d2015-09-06 18:19:50 -0700696 virtual void Ranges(void* arg, RangeFunction func) {
697 IterateOverRanges(arg, func);
698 }
699
700 virtual bool GetNumericProperty(const char* name, size_t* value) {
701 ASSERT(name != NULL);
702
703 if (strcmp(name, "generic.current_allocated_bytes") == 0) {
704 TCMallocStats stats;
705 ExtractStats(&stats, NULL, NULL, NULL);
706 *value = stats.pageheap.system_bytes
707 - stats.thread_bytes
708 - stats.central_bytes
709 - stats.transfer_bytes
710 - stats.pageheap.free_bytes
711 - stats.pageheap.unmapped_bytes;
712 return true;
713 }
714
715 if (strcmp(name, "generic.heap_size") == 0) {
716 TCMallocStats stats;
717 ExtractStats(&stats, NULL, NULL, NULL);
718 *value = stats.pageheap.system_bytes;
719 return true;
720 }
721
Brian Silverman20350ac2021-11-17 18:19:55 -0800722 if (strcmp(name, "generic.total_physical_bytes") == 0) {
723 TCMallocStats stats;
724 ExtractStats(&stats, NULL, NULL, NULL);
725 *value = stats.pageheap.system_bytes + stats.metadata_bytes -
726 stats.pageheap.unmapped_bytes;
727 return true;
728 }
729
Austin Schuh745610d2015-09-06 18:19:50 -0700730 if (strcmp(name, "tcmalloc.slack_bytes") == 0) {
731 // Kept for backwards compatibility. Now defined externally as:
732 // pageheap_free_bytes + pageheap_unmapped_bytes.
733 SpinLockHolder l(Static::pageheap_lock());
734 PageHeap::Stats stats = Static::pageheap()->stats();
735 *value = stats.free_bytes + stats.unmapped_bytes;
736 return true;
737 }
738
739 if (strcmp(name, "tcmalloc.central_cache_free_bytes") == 0) {
740 TCMallocStats stats;
741 ExtractStats(&stats, NULL, NULL, NULL);
742 *value = stats.central_bytes;
743 return true;
744 }
745
746 if (strcmp(name, "tcmalloc.transfer_cache_free_bytes") == 0) {
747 TCMallocStats stats;
748 ExtractStats(&stats, NULL, NULL, NULL);
749 *value = stats.transfer_bytes;
750 return true;
751 }
752
753 if (strcmp(name, "tcmalloc.thread_cache_free_bytes") == 0) {
754 TCMallocStats stats;
755 ExtractStats(&stats, NULL, NULL, NULL);
756 *value = stats.thread_bytes;
757 return true;
758 }
759
760 if (strcmp(name, "tcmalloc.pageheap_free_bytes") == 0) {
761 SpinLockHolder l(Static::pageheap_lock());
762 *value = Static::pageheap()->stats().free_bytes;
763 return true;
764 }
765
766 if (strcmp(name, "tcmalloc.pageheap_unmapped_bytes") == 0) {
767 SpinLockHolder l(Static::pageheap_lock());
768 *value = Static::pageheap()->stats().unmapped_bytes;
769 return true;
770 }
771
Brian Silverman20350ac2021-11-17 18:19:55 -0800772 if (strcmp(name, "tcmalloc.pageheap_committed_bytes") == 0) {
773 SpinLockHolder l(Static::pageheap_lock());
774 *value = Static::pageheap()->stats().committed_bytes;
775 return true;
776 }
777
778 if (strcmp(name, "tcmalloc.pageheap_scavenge_count") == 0) {
779 SpinLockHolder l(Static::pageheap_lock());
780 *value = Static::pageheap()->stats().scavenge_count;
781 return true;
782 }
783
784 if (strcmp(name, "tcmalloc.pageheap_commit_count") == 0) {
785 SpinLockHolder l(Static::pageheap_lock());
786 *value = Static::pageheap()->stats().commit_count;
787 return true;
788 }
789
790 if (strcmp(name, "tcmalloc.pageheap_total_commit_bytes") == 0) {
791 SpinLockHolder l(Static::pageheap_lock());
792 *value = Static::pageheap()->stats().total_commit_bytes;
793 return true;
794 }
795
796 if (strcmp(name, "tcmalloc.pageheap_decommit_count") == 0) {
797 SpinLockHolder l(Static::pageheap_lock());
798 *value = Static::pageheap()->stats().decommit_count;
799 return true;
800 }
801
802 if (strcmp(name, "tcmalloc.pageheap_total_decommit_bytes") == 0) {
803 SpinLockHolder l(Static::pageheap_lock());
804 *value = Static::pageheap()->stats().total_decommit_bytes;
805 return true;
806 }
807
808 if (strcmp(name, "tcmalloc.pageheap_reserve_count") == 0) {
809 SpinLockHolder l(Static::pageheap_lock());
810 *value = Static::pageheap()->stats().reserve_count;
811 return true;
812 }
813
814 if (strcmp(name, "tcmalloc.pageheap_total_reserve_bytes") == 0) {
815 SpinLockHolder l(Static::pageheap_lock());
816 *value = Static::pageheap()->stats().total_reserve_bytes;
817 return true;
818 }
819
Austin Schuh745610d2015-09-06 18:19:50 -0700820 if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
821 SpinLockHolder l(Static::pageheap_lock());
822 *value = ThreadCache::overall_thread_cache_size();
823 return true;
824 }
825
826 if (strcmp(name, "tcmalloc.current_total_thread_cache_bytes") == 0) {
827 TCMallocStats stats;
828 ExtractStats(&stats, NULL, NULL, NULL);
829 *value = stats.thread_bytes;
830 return true;
831 }
832
833 if (strcmp(name, "tcmalloc.aggressive_memory_decommit") == 0) {
Brian Silverman20350ac2021-11-17 18:19:55 -0800834 SpinLockHolder l(Static::pageheap_lock());
Austin Schuh745610d2015-09-06 18:19:50 -0700835 *value = size_t(Static::pageheap()->GetAggressiveDecommit());
836 return true;
837 }
838
Brian Silverman20350ac2021-11-17 18:19:55 -0800839 if (strcmp(name, "tcmalloc.heap_limit_mb") == 0) {
840 SpinLockHolder l(Static::pageheap_lock());
841 *value = FLAGS_tcmalloc_heap_limit_mb;
842 return true;
843 }
844
Austin Schuh745610d2015-09-06 18:19:50 -0700845 return false;
846 }
847
848 virtual bool SetNumericProperty(const char* name, size_t value) {
849 ASSERT(name != NULL);
850
851 if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
852 SpinLockHolder l(Static::pageheap_lock());
853 ThreadCache::set_overall_thread_cache_size(value);
854 return true;
855 }
856
857 if (strcmp(name, "tcmalloc.aggressive_memory_decommit") == 0) {
Brian Silverman20350ac2021-11-17 18:19:55 -0800858 SpinLockHolder l(Static::pageheap_lock());
Austin Schuh745610d2015-09-06 18:19:50 -0700859 Static::pageheap()->SetAggressiveDecommit(value != 0);
860 return true;
861 }
862
Brian Silverman20350ac2021-11-17 18:19:55 -0800863 if (strcmp(name, "tcmalloc.heap_limit_mb") == 0) {
864 SpinLockHolder l(Static::pageheap_lock());
865 FLAGS_tcmalloc_heap_limit_mb = value;
866 return true;
867 }
868
Austin Schuh745610d2015-09-06 18:19:50 -0700869 return false;
870 }
871
872 virtual void MarkThreadIdle() {
873 ThreadCache::BecomeIdle();
874 }
875
876 virtual void MarkThreadBusy(); // Implemented below
877
878 virtual SysAllocator* GetSystemAllocator() {
879 SpinLockHolder h(Static::pageheap_lock());
Brian Silverman20350ac2021-11-17 18:19:55 -0800880 return tcmalloc_sys_alloc;
Austin Schuh745610d2015-09-06 18:19:50 -0700881 }
882
883 virtual void SetSystemAllocator(SysAllocator* alloc) {
884 SpinLockHolder h(Static::pageheap_lock());
Brian Silverman20350ac2021-11-17 18:19:55 -0800885 tcmalloc_sys_alloc = alloc;
Austin Schuh745610d2015-09-06 18:19:50 -0700886 }
887
888 virtual void ReleaseToSystem(size_t num_bytes) {
889 SpinLockHolder h(Static::pageheap_lock());
890 if (num_bytes <= extra_bytes_released_) {
891 // We released too much on a prior call, so don't release any
892 // more this time.
893 extra_bytes_released_ = extra_bytes_released_ - num_bytes;
894 return;
895 }
896 num_bytes = num_bytes - extra_bytes_released_;
897 // num_bytes might be less than one page. If we pass zero to
898 // ReleaseAtLeastNPages, it won't do anything, so we release a whole
899 // page now and let extra_bytes_released_ smooth it out over time.
900 Length num_pages = max<Length>(num_bytes >> kPageShift, 1);
901 size_t bytes_released = Static::pageheap()->ReleaseAtLeastNPages(
902 num_pages) << kPageShift;
903 if (bytes_released > num_bytes) {
904 extra_bytes_released_ = bytes_released - num_bytes;
905 } else {
906 // The PageHeap wasn't able to release num_bytes. Don't try to
907 // compensate with a big release next time. Specifically,
908 // ReleaseFreeMemory() calls ReleaseToSystem(LONG_MAX).
909 extra_bytes_released_ = 0;
910 }
911 }
912
913 virtual void SetMemoryReleaseRate(double rate) {
914 FLAGS_tcmalloc_release_rate = rate;
915 }
916
917 virtual double GetMemoryReleaseRate() {
918 return FLAGS_tcmalloc_release_rate;
919 }
Brian Silverman20350ac2021-11-17 18:19:55 -0800920 virtual size_t GetEstimatedAllocatedSize(size_t size);
Austin Schuh745610d2015-09-06 18:19:50 -0700921
922 // This just calls GetSizeWithCallback, but because that's in an
923 // unnamed namespace, we need to move the definition below it in the
924 // file.
925 virtual size_t GetAllocatedSize(const void* ptr);
926
927 // This duplicates some of the logic in GetSizeWithCallback, but is
928 // faster. This is important on OS X, where this function is called
929 // on every allocation operation.
930 virtual Ownership GetOwnership(const void* ptr) {
931 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
932 // The rest of tcmalloc assumes that all allocated pointers use at
933 // most kAddressBits bits. If ptr doesn't, then it definitely
934 // wasn't alloacted by tcmalloc.
935 if ((p >> (kAddressBits - kPageShift)) > 0) {
936 return kNotOwned;
937 }
Brian Silverman20350ac2021-11-17 18:19:55 -0800938 uint32 cl;
939 if (Static::pageheap()->TryGetSizeClass(p, &cl)) {
Austin Schuh745610d2015-09-06 18:19:50 -0700940 return kOwned;
941 }
942 const Span *span = Static::pageheap()->GetDescriptor(p);
943 return span ? kOwned : kNotOwned;
944 }
945
946 virtual void GetFreeListSizes(vector<MallocExtension::FreeListInfo>* v) {
Brian Silverman20350ac2021-11-17 18:19:55 -0800947 static const char kCentralCacheType[] = "tcmalloc.central";
948 static const char kTransferCacheType[] = "tcmalloc.transfer";
949 static const char kThreadCacheType[] = "tcmalloc.thread";
950 static const char kPageHeapType[] = "tcmalloc.page";
951 static const char kPageHeapUnmappedType[] = "tcmalloc.page_unmapped";
952 static const char kLargeSpanType[] = "tcmalloc.large";
953 static const char kLargeUnmappedSpanType[] = "tcmalloc.large_unmapped";
Austin Schuh745610d2015-09-06 18:19:50 -0700954
955 v->clear();
956
957 // central class information
958 int64 prev_class_size = 0;
Brian Silverman20350ac2021-11-17 18:19:55 -0800959 for (int cl = 1; cl < Static::num_size_classes(); ++cl) {
Austin Schuh745610d2015-09-06 18:19:50 -0700960 size_t class_size = Static::sizemap()->ByteSizeForClass(cl);
961 MallocExtension::FreeListInfo i;
962 i.min_object_size = prev_class_size + 1;
963 i.max_object_size = class_size;
964 i.total_bytes_free =
965 Static::central_cache()[cl].length() * class_size;
966 i.type = kCentralCacheType;
967 v->push_back(i);
968
969 // transfer cache
970 i.total_bytes_free =
971 Static::central_cache()[cl].tc_length() * class_size;
972 i.type = kTransferCacheType;
973 v->push_back(i);
974
975 prev_class_size = Static::sizemap()->ByteSizeForClass(cl);
976 }
977
978 // Add stats from per-thread heaps
Brian Silverman20350ac2021-11-17 18:19:55 -0800979 uint64_t class_count[kClassSizesMax];
Austin Schuh745610d2015-09-06 18:19:50 -0700980 memset(class_count, 0, sizeof(class_count));
981 {
982 SpinLockHolder h(Static::pageheap_lock());
983 uint64_t thread_bytes = 0;
984 ThreadCache::GetThreadStats(&thread_bytes, class_count);
985 }
986
987 prev_class_size = 0;
Brian Silverman20350ac2021-11-17 18:19:55 -0800988 for (int cl = 1; cl < Static::num_size_classes(); ++cl) {
Austin Schuh745610d2015-09-06 18:19:50 -0700989 MallocExtension::FreeListInfo i;
990 i.min_object_size = prev_class_size + 1;
991 i.max_object_size = Static::sizemap()->ByteSizeForClass(cl);
992 i.total_bytes_free =
993 class_count[cl] * Static::sizemap()->ByteSizeForClass(cl);
994 i.type = kThreadCacheType;
995 v->push_back(i);
Brian Silverman20350ac2021-11-17 18:19:55 -0800996
997 prev_class_size = Static::sizemap()->ByteSizeForClass(cl);
Austin Schuh745610d2015-09-06 18:19:50 -0700998 }
999
1000 // append page heap info
1001 PageHeap::SmallSpanStats small;
1002 PageHeap::LargeSpanStats large;
1003 {
1004 SpinLockHolder h(Static::pageheap_lock());
1005 Static::pageheap()->GetSmallSpanStats(&small);
1006 Static::pageheap()->GetLargeSpanStats(&large);
1007 }
1008
1009 // large spans: mapped
1010 MallocExtension::FreeListInfo span_info;
1011 span_info.type = kLargeSpanType;
1012 span_info.max_object_size = (numeric_limits<size_t>::max)();
1013 span_info.min_object_size = kMaxPages << kPageShift;
1014 span_info.total_bytes_free = large.normal_pages << kPageShift;
1015 v->push_back(span_info);
1016
1017 // large spans: unmapped
1018 span_info.type = kLargeUnmappedSpanType;
1019 span_info.total_bytes_free = large.returned_pages << kPageShift;
1020 v->push_back(span_info);
1021
1022 // small spans
Brian Silverman20350ac2021-11-17 18:19:55 -08001023 for (int s = 1; s <= kMaxPages; s++) {
Austin Schuh745610d2015-09-06 18:19:50 -07001024 MallocExtension::FreeListInfo i;
1025 i.max_object_size = (s << kPageShift);
1026 i.min_object_size = ((s - 1) << kPageShift);
1027
1028 i.type = kPageHeapType;
Brian Silverman20350ac2021-11-17 18:19:55 -08001029 i.total_bytes_free = (s << kPageShift) * small.normal_length[s - 1];
Austin Schuh745610d2015-09-06 18:19:50 -07001030 v->push_back(i);
1031
1032 i.type = kPageHeapUnmappedType;
Brian Silverman20350ac2021-11-17 18:19:55 -08001033 i.total_bytes_free = (s << kPageShift) * small.returned_length[s - 1];
Austin Schuh745610d2015-09-06 18:19:50 -07001034 v->push_back(i);
1035 }
1036 }
1037};
1038
Brian Silverman20350ac2021-11-17 18:19:55 -08001039static inline ATTRIBUTE_ALWAYS_INLINE
1040size_t align_size_up(size_t size, size_t align) {
1041 ASSERT(align <= kPageSize);
1042 size_t new_size = (size + align - 1) & ~(align - 1);
1043 if (PREDICT_FALSE(new_size == 0)) {
1044 // Note, new_size == 0 catches both integer overflow and size
1045 // being 0.
1046 if (size == 0) {
1047 new_size = align;
1048 } else {
1049 new_size = size;
1050 }
1051 }
1052 return new_size;
1053}
1054
1055// Puts in *cl size class that is suitable for allocation of size bytes with
1056// align alignment. Returns true if such size class exists and false otherwise.
1057static bool size_class_with_alignment(size_t size, size_t align, uint32_t* cl) {
1058 if (PREDICT_FALSE(align > kPageSize)) {
1059 return false;
1060 }
1061 size = align_size_up(size, align);
1062 if (PREDICT_FALSE(!Static::sizemap()->GetSizeClass(size, cl))) {
1063 return false;
1064 }
1065 ASSERT((Static::sizemap()->class_to_size(*cl) & (align - 1)) == 0);
1066 return true;
1067}
1068
1069// nallocx slow path. Moved to a separate function because
1070// ThreadCache::InitModule is not inlined which would cause nallocx to
1071// become non-leaf function with stack frame and stack spills.
1072static ATTRIBUTE_NOINLINE size_t nallocx_slow(size_t size, int flags) {
1073 if (PREDICT_FALSE(!Static::IsInited())) ThreadCache::InitModule();
1074
1075 size_t align = static_cast<size_t>(1ull << (flags & 0x3f));
1076 uint32 cl;
1077 bool ok = size_class_with_alignment(size, align, &cl);
1078 if (ok) {
1079 return Static::sizemap()->ByteSizeForClass(cl);
1080 } else {
1081 return tcmalloc::pages(size) << kPageShift;
1082 }
1083}
1084
1085// The nallocx function allocates no memory, but it performs the same size
1086// computation as the malloc function, and returns the real size of the
1087// allocation that would result from the equivalent malloc function call.
1088// nallocx is a malloc extension originally implemented by jemalloc:
1089// http://www.unix.com/man-page/freebsd/3/nallocx/
1090extern "C" PERFTOOLS_DLL_DECL
1091size_t tc_nallocx(size_t size, int flags) {
1092 if (PREDICT_FALSE(flags != 0)) {
1093 return nallocx_slow(size, flags);
1094 }
1095 uint32 cl;
1096 // size class 0 is only possible if malloc is not yet initialized
1097 if (Static::sizemap()->GetSizeClass(size, &cl) && cl != 0) {
1098 return Static::sizemap()->ByteSizeForClass(cl);
1099 } else {
1100 return nallocx_slow(size, 0);
1101 }
1102}
1103
1104extern "C" PERFTOOLS_DLL_DECL
1105size_t nallocx(size_t size, int flags)
1106#ifdef TC_ALIAS
1107 TC_ALIAS(tc_nallocx);
1108#else
1109{
1110 return nallocx_slow(size, flags);
1111}
1112#endif
1113
1114
1115size_t TCMallocImplementation::GetEstimatedAllocatedSize(size_t size) {
1116 return tc_nallocx(size, 0);
1117}
1118
Austin Schuh745610d2015-09-06 18:19:50 -07001119// The constructor allocates an object to ensure that initialization
1120// runs before main(), and therefore we do not have a chance to become
1121// multi-threaded before initialization. We also create the TSD key
1122// here. Presumably by the time this constructor runs, glibc is in
1123// good enough shape to handle pthread_key_create().
1124//
1125// The constructor also takes the opportunity to tell STL to use
1126// tcmalloc. We want to do this early, before construct time, so
1127// all user STL allocations go through tcmalloc (which works really
1128// well for STL).
1129//
1130// The destructor prints stats when the program exits.
1131static int tcmallocguard_refcount = 0; // no lock needed: runs before main()
1132TCMallocGuard::TCMallocGuard() {
1133 if (tcmallocguard_refcount++ == 0) {
1134 ReplaceSystemAlloc(); // defined in libc_override_*.h
1135 tc_free(tc_malloc(1));
1136 ThreadCache::InitTSD();
1137 tc_free(tc_malloc(1));
1138 // Either we, or debugallocation.cc, or valgrind will control memory
1139 // management. We register our extension if we're the winner.
1140#ifdef TCMALLOC_USING_DEBUGALLOCATION
1141 // Let debugallocation register its extension.
1142#else
1143 if (RunningOnValgrind()) {
1144 // Let Valgrind uses its own malloc (so don't register our extension).
1145 } else {
1146 MallocExtension::Register(new TCMallocImplementation);
1147 }
1148#endif
1149 }
1150}
1151
1152TCMallocGuard::~TCMallocGuard() {
1153 if (--tcmallocguard_refcount == 0) {
1154 const char* env = NULL;
1155 if (!RunningOnValgrind()) {
1156 // Valgrind uses it's own malloc so we cannot do MALLOCSTATS
1157 env = getenv("MALLOCSTATS");
1158 }
1159 if (env != NULL) {
1160 int level = atoi(env);
1161 if (level < 1) level = 1;
1162 PrintStats(level);
1163 }
1164 }
1165}
1166#ifndef WIN32_OVERRIDE_ALLOCATORS
1167static TCMallocGuard module_enter_exit_hook;
1168#endif
1169
1170//-------------------------------------------------------------------
1171// Helpers for the exported routines below
1172//-------------------------------------------------------------------
1173
1174static inline bool CheckCachedSizeClass(void *ptr) {
1175 PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
Brian Silverman20350ac2021-11-17 18:19:55 -08001176 uint32 cached_value;
1177 if (!Static::pageheap()->TryGetSizeClass(p, &cached_value)) {
1178 return true;
1179 }
1180 return cached_value == Static::pageheap()->GetDescriptor(p)->sizeclass;
Austin Schuh745610d2015-09-06 18:19:50 -07001181}
1182
Brian Silverman20350ac2021-11-17 18:19:55 -08001183static inline ATTRIBUTE_ALWAYS_INLINE void* CheckedMallocResult(void *result) {
Austin Schuh745610d2015-09-06 18:19:50 -07001184 ASSERT(result == NULL || CheckCachedSizeClass(result));
1185 return result;
1186}
1187
Brian Silverman20350ac2021-11-17 18:19:55 -08001188static inline ATTRIBUTE_ALWAYS_INLINE void* SpanToMallocResult(Span *span) {
1189 Static::pageheap()->InvalidateCachedSizeClass(span->start);
Austin Schuh745610d2015-09-06 18:19:50 -07001190 return
1191 CheckedMallocResult(reinterpret_cast<void*>(span->start << kPageShift));
1192}
1193
1194static void* DoSampledAllocation(size_t size) {
Brian Silverman20350ac2021-11-17 18:19:55 -08001195#ifndef NO_TCMALLOC_SAMPLES
Austin Schuh745610d2015-09-06 18:19:50 -07001196 // Grab the stack trace outside the heap lock
1197 StackTrace tmp;
1198 tmp.depth = GetStackTrace(tmp.stack, tcmalloc::kMaxStackDepth, 1);
1199 tmp.size = size;
1200
1201 SpinLockHolder h(Static::pageheap_lock());
1202 // Allocate span
1203 Span *span = Static::pageheap()->New(tcmalloc::pages(size == 0 ? 1 : size));
Brian Silverman20350ac2021-11-17 18:19:55 -08001204 if (PREDICT_FALSE(span == NULL)) {
Austin Schuh745610d2015-09-06 18:19:50 -07001205 return NULL;
1206 }
1207
1208 // Allocate stack trace
1209 StackTrace *stack = Static::stacktrace_allocator()->New();
Brian Silverman20350ac2021-11-17 18:19:55 -08001210 if (PREDICT_FALSE(stack == NULL)) {
Austin Schuh745610d2015-09-06 18:19:50 -07001211 // Sampling failed because of lack of memory
1212 return span;
1213 }
1214 *stack = tmp;
1215 span->sample = 1;
1216 span->objects = stack;
1217 tcmalloc::DLL_Prepend(Static::sampled_objects(), span);
1218
1219 return SpanToMallocResult(span);
Brian Silverman20350ac2021-11-17 18:19:55 -08001220#else
1221 abort();
1222#endif
Austin Schuh745610d2015-09-06 18:19:50 -07001223}
1224
1225namespace {
1226
1227typedef void* (*malloc_fn)(void *arg);
1228
1229SpinLock set_new_handler_lock(SpinLock::LINKER_INITIALIZED);
1230
1231void* handle_oom(malloc_fn retry_fn,
1232 void* retry_arg,
1233 bool from_operator,
1234 bool nothrow) {
Brian Silverman20350ac2021-11-17 18:19:55 -08001235 // we hit out of memory condition, usually if it happens we've
1236 // called sbrk or mmap and failed, and thus errno is set. But there
1237 // is support for setting up custom system allocator or setting up
1238 // page heap size limit, in which cases errno may remain
1239 // untouched.
1240 //
1241 // So we set errno here. C++ operator new doesn't require ENOMEM to
1242 // be set, but doesn't forbid it too (and often C++ oom does happen
1243 // with ENOMEM set).
1244 errno = ENOMEM;
Austin Schuh745610d2015-09-06 18:19:50 -07001245 if (!from_operator && !tc_new_mode) {
1246 // we're out of memory in C library function (malloc etc) and no
1247 // "new mode" forced on us. Just return NULL
1248 return NULL;
1249 }
1250 // we're OOM in operator new or "new mode" is set. We might have to
1251 // call new_handle and maybe retry allocation.
1252
1253 for (;;) {
1254 // Get the current new handler. NB: this function is not
1255 // thread-safe. We make a feeble stab at making it so here, but
1256 // this lock only protects against tcmalloc interfering with
1257 // itself, not with other libraries calling set_new_handler.
1258 std::new_handler nh;
1259 {
1260 SpinLockHolder h(&set_new_handler_lock);
1261 nh = std::set_new_handler(0);
1262 (void) std::set_new_handler(nh);
1263 }
1264#if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)
1265 if (!nh) {
1266 return NULL;
1267 }
1268 // Since exceptions are disabled, we don't really know if new_handler
1269 // failed. Assume it will abort if it fails.
1270 (*nh)();
1271#else
1272 // If no new_handler is established, the allocation failed.
1273 if (!nh) {
1274 if (nothrow) {
1275 return NULL;
1276 }
1277 throw std::bad_alloc();
1278 }
1279 // Otherwise, try the new_handler. If it returns, retry the
1280 // allocation. If it throws std::bad_alloc, fail the allocation.
1281 // if it throws something else, don't interfere.
1282 try {
1283 (*nh)();
1284 } catch (const std::bad_alloc&) {
1285 if (!nothrow) throw;
1286 return NULL;
1287 }
1288#endif // (defined(__GNUC__) && !defined(__EXCEPTIONS)) || (defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS)
1289
1290 // we get here if new_handler returns successfully. So we retry
1291 // allocation.
1292 void* rv = retry_fn(retry_arg);
1293 if (rv != NULL) {
1294 return rv;
1295 }
1296
1297 // if allocation failed again we go to next loop iteration
1298 }
1299}
1300
1301// Copy of FLAGS_tcmalloc_large_alloc_report_threshold with
1302// automatic increases factored in.
Brian Silverman20350ac2021-11-17 18:19:55 -08001303#ifdef ENABLE_LARGE_ALLOC_REPORT
Austin Schuh745610d2015-09-06 18:19:50 -07001304static int64_t large_alloc_threshold =
1305 (kPageSize > FLAGS_tcmalloc_large_alloc_report_threshold
1306 ? kPageSize : FLAGS_tcmalloc_large_alloc_report_threshold);
Brian Silverman20350ac2021-11-17 18:19:55 -08001307#endif
Austin Schuh745610d2015-09-06 18:19:50 -07001308
1309static void ReportLargeAlloc(Length num_pages, void* result) {
1310 StackTrace stack;
1311 stack.depth = GetStackTrace(stack.stack, tcmalloc::kMaxStackDepth, 1);
1312
1313 static const int N = 1000;
1314 char buffer[N];
1315 TCMalloc_Printer printer(buffer, N);
1316 printer.printf("tcmalloc: large alloc %" PRIu64 " bytes == %p @ ",
1317 static_cast<uint64>(num_pages) << kPageShift,
1318 result);
1319 for (int i = 0; i < stack.depth; i++) {
1320 printer.printf(" %p", stack.stack[i]);
1321 }
1322 printer.printf("\n");
1323 write(STDERR_FILENO, buffer, strlen(buffer));
1324}
1325
Austin Schuh745610d2015-09-06 18:19:50 -07001326// Must be called with the page lock held.
1327inline bool should_report_large(Length num_pages) {
Brian Silverman20350ac2021-11-17 18:19:55 -08001328#ifdef ENABLE_LARGE_ALLOC_REPORT
Austin Schuh745610d2015-09-06 18:19:50 -07001329 const int64 threshold = large_alloc_threshold;
1330 if (threshold > 0 && num_pages >= (threshold >> kPageShift)) {
1331 // Increase the threshold by 1/8 every time we generate a report.
1332 // We cap the threshold at 8GiB to avoid overflow problems.
1333 large_alloc_threshold = (threshold + threshold/8 < 8ll<<30
1334 ? threshold + threshold/8 : 8ll<<30);
1335 return true;
1336 }
Brian Silverman20350ac2021-11-17 18:19:55 -08001337#endif
Austin Schuh745610d2015-09-06 18:19:50 -07001338 return false;
1339}
1340
1341// Helper for do_malloc().
Brian Silverman20350ac2021-11-17 18:19:55 -08001342static void* do_malloc_pages(ThreadCache* heap, size_t size) {
Austin Schuh745610d2015-09-06 18:19:50 -07001343 void* result;
1344 bool report_large;
1345
1346 Length num_pages = tcmalloc::pages(size);
Austin Schuh745610d2015-09-06 18:19:50 -07001347
Brian Silverman20350ac2021-11-17 18:19:55 -08001348 // NOTE: we're passing original size here as opposed to rounded-up
1349 // size as we do in do_malloc_small. The difference is small here
1350 // (at most 4k out of at least 256k). And not rounding up saves us
1351 // from possibility of overflow, which rounding up could produce.
1352 //
1353 // See https://github.com/gperftools/gperftools/issues/723
1354 if (heap->SampleAllocation(size)) {
Austin Schuh745610d2015-09-06 18:19:50 -07001355 result = DoSampledAllocation(size);
1356
1357 SpinLockHolder h(Static::pageheap_lock());
1358 report_large = should_report_large(num_pages);
1359 } else {
1360 SpinLockHolder h(Static::pageheap_lock());
1361 Span* span = Static::pageheap()->New(num_pages);
Brian Silverman20350ac2021-11-17 18:19:55 -08001362 result = (PREDICT_FALSE(span == NULL) ? NULL : SpanToMallocResult(span));
Austin Schuh745610d2015-09-06 18:19:50 -07001363 report_large = should_report_large(num_pages);
1364 }
1365
1366 if (report_large) {
1367 ReportLargeAlloc(num_pages, result);
1368 }
1369 return result;
1370}
1371
Brian Silverman20350ac2021-11-17 18:19:55 -08001372static void *nop_oom_handler(size_t size) {
1373 return NULL;
Austin Schuh745610d2015-09-06 18:19:50 -07001374}
1375
Brian Silverman20350ac2021-11-17 18:19:55 -08001376ATTRIBUTE_ALWAYS_INLINE inline void* do_malloc(size_t size) {
1377 if (PREDICT_FALSE(ThreadCache::IsUseEmergencyMalloc())) {
1378 return tcmalloc::EmergencyMalloc(size);
Austin Schuh745610d2015-09-06 18:19:50 -07001379 }
Brian Silverman20350ac2021-11-17 18:19:55 -08001380
1381 // note: it will force initialization of malloc if necessary
1382 ThreadCache* cache = ThreadCache::GetCache();
1383 uint32 cl;
1384
1385 ASSERT(Static::IsInited());
1386 ASSERT(cache != NULL);
1387
1388 if (PREDICT_FALSE(!Static::sizemap()->GetSizeClass(size, &cl))) {
1389 return do_malloc_pages(cache, size);
1390 }
1391
1392 size_t allocated_size = Static::sizemap()->class_to_size(cl);
1393 if (PREDICT_FALSE(cache->SampleAllocation(allocated_size))) {
1394 return DoSampledAllocation(size);
1395 }
1396
1397 // The common case, and also the simplest. This just pops the
1398 // size-appropriate freelist, after replenishing it if it's empty.
1399 return CheckedMallocResult(cache->Allocate(allocated_size, cl, nop_oom_handler));
Austin Schuh745610d2015-09-06 18:19:50 -07001400}
1401
1402static void *retry_malloc(void* size) {
1403 return do_malloc(reinterpret_cast<size_t>(size));
1404}
1405
Brian Silverman20350ac2021-11-17 18:19:55 -08001406ATTRIBUTE_ALWAYS_INLINE inline void* do_malloc_or_cpp_alloc(size_t size) {
Austin Schuh745610d2015-09-06 18:19:50 -07001407 void *rv = do_malloc(size);
Brian Silverman20350ac2021-11-17 18:19:55 -08001408 if (PREDICT_TRUE(rv != NULL)) {
Austin Schuh745610d2015-09-06 18:19:50 -07001409 return rv;
1410 }
1411 return handle_oom(retry_malloc, reinterpret_cast<void *>(size),
1412 false, true);
1413}
1414
Brian Silverman20350ac2021-11-17 18:19:55 -08001415ATTRIBUTE_ALWAYS_INLINE inline void* do_calloc(size_t n, size_t elem_size) {
Austin Schuh745610d2015-09-06 18:19:50 -07001416 // Overflow check
1417 const size_t size = n * elem_size;
1418 if (elem_size != 0 && size / elem_size != n) return NULL;
1419
1420 void* result = do_malloc_or_cpp_alloc(size);
1421 if (result != NULL) {
Brian Silverman20350ac2021-11-17 18:19:55 -08001422 memset(result, 0, tc_nallocx(size, 0));
Austin Schuh745610d2015-09-06 18:19:50 -07001423 }
1424 return result;
1425}
1426
1427// If ptr is NULL, do nothing. Otherwise invoke the given function.
1428inline void free_null_or_invalid(void* ptr, void (*invalid_free_fn)(void*)) {
1429 if (ptr != NULL) {
1430 (*invalid_free_fn)(ptr);
1431 }
1432}
1433
Brian Silverman20350ac2021-11-17 18:19:55 -08001434static ATTRIBUTE_NOINLINE void do_free_pages(Span* span, void* ptr) {
1435 SpinLockHolder h(Static::pageheap_lock());
1436 if (span->sample) {
1437 StackTrace* st = reinterpret_cast<StackTrace*>(span->objects);
1438 tcmalloc::DLL_Remove(span);
1439 Static::stacktrace_allocator()->Delete(st);
1440 span->objects = NULL;
Austin Schuh745610d2015-09-06 18:19:50 -07001441 }
Brian Silverman20350ac2021-11-17 18:19:55 -08001442 Static::pageheap()->Delete(span);
Austin Schuh745610d2015-09-06 18:19:50 -07001443}
1444
Brian Silverman20350ac2021-11-17 18:19:55 -08001445#ifndef NDEBUG
1446// note, with sized deletions we have no means to support win32
1447// behavior where we detect "not ours" points and delegate them native
1448// memory management. This is because nature of sized deletes
1449// bypassing addr -> size class checks. So in this validation code we
1450// also assume that sized delete is always used with "our" pointers.
1451bool ValidateSizeHint(void* ptr, size_t size_hint) {
1452 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
1453 Span* span = Static::pageheap()->GetDescriptor(p);
1454 uint32 cl = 0;
1455 Static::sizemap()->GetSizeClass(size_hint, &cl);
1456 return (span->sizeclass == cl);
1457}
1458#endif
1459
Austin Schuh745610d2015-09-06 18:19:50 -07001460// Helper for the object deletion (free, delete, etc.). Inputs:
1461// ptr is object to be freed
1462// invalid_free_fn is a function that gets invoked on certain "bad frees"
1463//
1464// We can usually detect the case where ptr is not pointing to a page that
1465// tcmalloc is using, and in those cases we invoke invalid_free_fn.
Brian Silverman20350ac2021-11-17 18:19:55 -08001466ATTRIBUTE_ALWAYS_INLINE inline
1467void do_free_with_callback(void* ptr,
1468 void (*invalid_free_fn)(void*),
1469 bool use_hint, size_t size_hint) {
1470 ThreadCache* heap = ThreadCache::GetCacheIfPresent();
1471
1472 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
1473 uint32 cl;
1474
1475 ASSERT(!use_hint || ValidateSizeHint(ptr, size_hint));
1476
1477 if (!use_hint || PREDICT_FALSE(!Static::sizemap()->GetSizeClass(size_hint, &cl))) {
1478 // if we're in sized delete, but size is too large, no need to
1479 // probe size cache
1480 bool cache_hit = !use_hint && Static::pageheap()->TryGetSizeClass(p, &cl);
1481 if (PREDICT_FALSE(!cache_hit)) {
1482 Span* span = Static::pageheap()->GetDescriptor(p);
1483 if (PREDICT_FALSE(!span)) {
1484 // span can be NULL because the pointer passed in is NULL or invalid
1485 // (not something returned by malloc or friends), or because the
1486 // pointer was allocated with some other allocator besides
1487 // tcmalloc. The latter can happen if tcmalloc is linked in via
1488 // a dynamic library, but is not listed last on the link line.
1489 // In that case, libraries after it on the link line will
1490 // allocate with libc malloc, but free with tcmalloc's free.
1491 free_null_or_invalid(ptr, invalid_free_fn);
1492 return;
1493 }
1494 cl = span->sizeclass;
1495 if (PREDICT_FALSE(cl == 0)) {
1496 ASSERT(reinterpret_cast<uintptr_t>(ptr) % kPageSize == 0);
1497 ASSERT(span != NULL && span->start == p);
1498 do_free_pages(span, ptr);
1499 return;
1500 }
1501 if (!use_hint) {
1502 Static::pageheap()->SetCachedSizeClass(p, cl);
1503 }
1504 }
Austin Schuh745610d2015-09-06 18:19:50 -07001505 }
Brian Silverman20350ac2021-11-17 18:19:55 -08001506
1507 if (PREDICT_TRUE(heap != NULL)) {
1508 ASSERT(Static::IsInited());
1509 // If we've hit initialized thread cache, so we're done.
1510 heap->Deallocate(ptr, cl);
1511 return;
1512 }
1513
1514 if (PREDICT_FALSE(!Static::IsInited())) {
1515 // if free was called very early we've could have missed the case
1516 // of invalid or nullptr free. I.e. because probing size classes
1517 // cache could return bogus result (cl = 0 as of this
1518 // writing). But since there is no way we could be dealing with
1519 // ptr we've allocated, since successfull malloc implies IsInited,
1520 // we can just call "invalid free" handling code.
1521 free_null_or_invalid(ptr, invalid_free_fn);
1522 return;
1523 }
1524
1525 // Otherwise, delete directly into central cache
1526 tcmalloc::SLL_SetNext(ptr, NULL);
1527 Static::central_cache()[cl].InsertRange(ptr, ptr, 1);
Austin Schuh745610d2015-09-06 18:19:50 -07001528}
1529
1530// The default "do_free" that uses the default callback.
Brian Silverman20350ac2021-11-17 18:19:55 -08001531ATTRIBUTE_ALWAYS_INLINE inline void do_free(void* ptr) {
1532 return do_free_with_callback(ptr, &InvalidFree, false, 0);
Austin Schuh745610d2015-09-06 18:19:50 -07001533}
1534
1535// NOTE: some logic here is duplicated in GetOwnership (above), for
1536// speed. If you change this function, look at that one too.
1537inline size_t GetSizeWithCallback(const void* ptr,
1538 size_t (*invalid_getsize_fn)(const void*)) {
1539 if (ptr == NULL)
1540 return 0;
1541 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
Brian Silverman20350ac2021-11-17 18:19:55 -08001542 uint32 cl;
1543 if (Static::pageheap()->TryGetSizeClass(p, &cl)) {
Austin Schuh745610d2015-09-06 18:19:50 -07001544 return Static::sizemap()->ByteSizeForClass(cl);
Austin Schuh745610d2015-09-06 18:19:50 -07001545 }
Brian Silverman20350ac2021-11-17 18:19:55 -08001546
1547 const Span *span = Static::pageheap()->GetDescriptor(p);
1548 if (PREDICT_FALSE(span == NULL)) { // means we do not own this memory
1549 return (*invalid_getsize_fn)(ptr);
1550 }
1551
1552 if (span->sizeclass != 0) {
1553 return Static::sizemap()->ByteSizeForClass(span->sizeclass);
1554 }
1555
1556 if (span->sample) {
1557 size_t orig_size = reinterpret_cast<StackTrace*>(span->objects)->size;
1558 return tc_nallocx(orig_size, 0);
1559 }
1560
1561 return span->length << kPageShift;
Austin Schuh745610d2015-09-06 18:19:50 -07001562}
1563
1564// This lets you call back to a given function pointer if ptr is invalid.
1565// It is used primarily by windows code which wants a specialized callback.
Brian Silverman20350ac2021-11-17 18:19:55 -08001566ATTRIBUTE_ALWAYS_INLINE inline void* do_realloc_with_callback(
Austin Schuh745610d2015-09-06 18:19:50 -07001567 void* old_ptr, size_t new_size,
1568 void (*invalid_free_fn)(void*),
1569 size_t (*invalid_get_size_fn)(const void*)) {
1570 // Get the size of the old entry
1571 const size_t old_size = GetSizeWithCallback(old_ptr, invalid_get_size_fn);
1572
1573 // Reallocate if the new size is larger than the old size,
1574 // or if the new size is significantly smaller than the old size.
1575 // We do hysteresis to avoid resizing ping-pongs:
1576 // . If we need to grow, grow to max(new_size, old_size * 1.X)
1577 // . Don't shrink unless new_size < old_size * 0.Y
1578 // X and Y trade-off time for wasted space. For now we do 1.25 and 0.5.
Brian Silverman20350ac2021-11-17 18:19:55 -08001579 const size_t min_growth = min(old_size / 4,
1580 (std::numeric_limits<size_t>::max)() - old_size); // Avoid overflow.
1581 const size_t lower_bound_to_grow = old_size + min_growth;
Austin Schuh745610d2015-09-06 18:19:50 -07001582 const size_t upper_bound_to_shrink = old_size / 2ul;
1583 if ((new_size > old_size) || (new_size < upper_bound_to_shrink)) {
1584 // Need to reallocate.
1585 void* new_ptr = NULL;
1586
1587 if (new_size > old_size && new_size < lower_bound_to_grow) {
1588 new_ptr = do_malloc_or_cpp_alloc(lower_bound_to_grow);
1589 }
1590 if (new_ptr == NULL) {
1591 // Either new_size is not a tiny increment, or last do_malloc failed.
1592 new_ptr = do_malloc_or_cpp_alloc(new_size);
1593 }
Brian Silverman20350ac2021-11-17 18:19:55 -08001594 if (PREDICT_FALSE(new_ptr == NULL)) {
Austin Schuh745610d2015-09-06 18:19:50 -07001595 return NULL;
1596 }
1597 MallocHook::InvokeNewHook(new_ptr, new_size);
1598 memcpy(new_ptr, old_ptr, ((old_size < new_size) ? old_size : new_size));
1599 MallocHook::InvokeDeleteHook(old_ptr);
1600 // We could use a variant of do_free() that leverages the fact
1601 // that we already know the sizeclass of old_ptr. The benefit
1602 // would be small, so don't bother.
Brian Silverman20350ac2021-11-17 18:19:55 -08001603 do_free_with_callback(old_ptr, invalid_free_fn, false, 0);
Austin Schuh745610d2015-09-06 18:19:50 -07001604 return new_ptr;
1605 } else {
1606 // We still need to call hooks to report the updated size:
1607 MallocHook::InvokeDeleteHook(old_ptr);
1608 MallocHook::InvokeNewHook(old_ptr, new_size);
1609 return old_ptr;
1610 }
1611}
1612
Brian Silverman20350ac2021-11-17 18:19:55 -08001613ATTRIBUTE_ALWAYS_INLINE inline void* do_realloc(void* old_ptr, size_t new_size) {
Austin Schuh745610d2015-09-06 18:19:50 -07001614 return do_realloc_with_callback(old_ptr, new_size,
1615 &InvalidFree, &InvalidGetSizeForRealloc);
1616}
1617
Brian Silverman20350ac2021-11-17 18:19:55 -08001618static ATTRIBUTE_ALWAYS_INLINE inline
1619void* do_memalign_pages(size_t align, size_t size) {
Austin Schuh745610d2015-09-06 18:19:50 -07001620 ASSERT((align & (align - 1)) == 0);
Brian Silverman20350ac2021-11-17 18:19:55 -08001621 ASSERT(align > kPageSize);
Austin Schuh745610d2015-09-06 18:19:50 -07001622 if (size + align < size) return NULL; // Overflow
1623
Brian Silverman20350ac2021-11-17 18:19:55 -08001624 if (PREDICT_FALSE(Static::pageheap() == NULL)) ThreadCache::InitModule();
Austin Schuh745610d2015-09-06 18:19:50 -07001625
1626 // Allocate at least one byte to avoid boundary conditions below
1627 if (size == 0) size = 1;
1628
Austin Schuh745610d2015-09-06 18:19:50 -07001629 // We will allocate directly from the page heap
1630 SpinLockHolder h(Static::pageheap_lock());
1631
Austin Schuh745610d2015-09-06 18:19:50 -07001632 // Allocate extra pages and carve off an aligned portion
1633 const Length alloc = tcmalloc::pages(size + align);
1634 Span* span = Static::pageheap()->New(alloc);
Brian Silverman20350ac2021-11-17 18:19:55 -08001635 if (PREDICT_FALSE(span == NULL)) return NULL;
Austin Schuh745610d2015-09-06 18:19:50 -07001636
1637 // Skip starting portion so that we end up aligned
1638 Length skip = 0;
1639 while ((((span->start+skip) << kPageShift) & (align - 1)) != 0) {
1640 skip++;
1641 }
1642 ASSERT(skip < alloc);
1643 if (skip > 0) {
1644 Span* rest = Static::pageheap()->Split(span, skip);
1645 Static::pageheap()->Delete(span);
1646 span = rest;
1647 }
1648
1649 // Skip trailing portion that we do not need to return
1650 const Length needed = tcmalloc::pages(size);
1651 ASSERT(span->length >= needed);
1652 if (span->length > needed) {
1653 Span* trailer = Static::pageheap()->Split(span, needed);
1654 Static::pageheap()->Delete(trailer);
1655 }
1656 return SpanToMallocResult(span);
1657}
1658
1659// Helpers for use by exported routines below:
1660
1661inline void do_malloc_stats() {
1662 PrintStats(1);
1663}
1664
1665inline int do_mallopt(int cmd, int value) {
1666 return 1; // Indicates error
1667}
1668
1669#ifdef HAVE_STRUCT_MALLINFO
1670inline struct mallinfo do_mallinfo() {
1671 TCMallocStats stats;
1672 ExtractStats(&stats, NULL, NULL, NULL);
1673
1674 // Just some of the fields are filled in.
1675 struct mallinfo info;
1676 memset(&info, 0, sizeof(info));
1677
1678 // Unfortunately, the struct contains "int" field, so some of the
1679 // size values will be truncated.
1680 info.arena = static_cast<int>(stats.pageheap.system_bytes);
1681 info.fsmblks = static_cast<int>(stats.thread_bytes
1682 + stats.central_bytes
1683 + stats.transfer_bytes);
1684 info.fordblks = static_cast<int>(stats.pageheap.free_bytes +
1685 stats.pageheap.unmapped_bytes);
1686 info.uordblks = static_cast<int>(stats.pageheap.system_bytes
1687 - stats.thread_bytes
1688 - stats.central_bytes
1689 - stats.transfer_bytes
1690 - stats.pageheap.free_bytes
1691 - stats.pageheap.unmapped_bytes);
1692
1693 return info;
1694}
1695#endif // HAVE_STRUCT_MALLINFO
1696
Austin Schuh745610d2015-09-06 18:19:50 -07001697} // end unnamed namespace
1698
1699// As promised, the definition of this function, declared above.
1700size_t TCMallocImplementation::GetAllocatedSize(const void* ptr) {
1701 if (ptr == NULL)
1702 return 0;
1703 ASSERT(TCMallocImplementation::GetOwnership(ptr)
1704 != TCMallocImplementation::kNotOwned);
1705 return GetSizeWithCallback(ptr, &InvalidGetAllocatedSize);
1706}
1707
1708void TCMallocImplementation::MarkThreadBusy() {
1709 // Allocate to force the creation of a thread cache, but avoid
1710 // invoking any hooks.
1711 do_free(do_malloc(0));
1712}
1713
1714//-------------------------------------------------------------------
1715// Exported routines
1716//-------------------------------------------------------------------
1717
1718extern "C" PERFTOOLS_DLL_DECL const char* tc_version(
Brian Silverman20350ac2021-11-17 18:19:55 -08001719 int* major, int* minor, const char** patch) PERFTOOLS_NOTHROW {
Austin Schuh745610d2015-09-06 18:19:50 -07001720 if (major) *major = TC_VERSION_MAJOR;
1721 if (minor) *minor = TC_VERSION_MINOR;
1722 if (patch) *patch = TC_VERSION_PATCH;
1723 return TC_VERSION_STRING;
1724}
1725
1726// This function behaves similarly to MSVC's _set_new_mode.
1727// If flag is 0 (default), calls to malloc will behave normally.
1728// If flag is 1, calls to malloc will behave like calls to new,
1729// and the std_new_handler will be invoked on failure.
1730// Returns the previous mode.
Brian Silverman20350ac2021-11-17 18:19:55 -08001731extern "C" PERFTOOLS_DLL_DECL int tc_set_new_mode(int flag) PERFTOOLS_NOTHROW {
Austin Schuh745610d2015-09-06 18:19:50 -07001732 int old_mode = tc_new_mode;
1733 tc_new_mode = flag;
1734 return old_mode;
1735}
1736
Brian Silverman20350ac2021-11-17 18:19:55 -08001737extern "C" PERFTOOLS_DLL_DECL int tc_query_new_mode() PERFTOOLS_NOTHROW {
1738 return tc_new_mode;
1739}
1740
Austin Schuh745610d2015-09-06 18:19:50 -07001741#ifndef TCMALLOC_USING_DEBUGALLOCATION // debugallocation.cc defines its own
1742
1743// CAVEAT: The code structure below ensures that MallocHook methods are always
1744// called from the stack frame of the invoked allocation function.
1745// heap-checker.cc depends on this to start a stack trace from
1746// the call to the (de)allocation function.
1747
Brian Silverman20350ac2021-11-17 18:19:55 -08001748namespace tcmalloc {
Austin Schuh745610d2015-09-06 18:19:50 -07001749
Brian Silverman20350ac2021-11-17 18:19:55 -08001750
1751static ATTRIBUTE_SECTION(google_malloc)
1752void invoke_hooks_and_free(void *ptr) {
Austin Schuh745610d2015-09-06 18:19:50 -07001753 MallocHook::InvokeDeleteHook(ptr);
1754 do_free(ptr);
1755}
1756
Brian Silverman20350ac2021-11-17 18:19:55 -08001757ATTRIBUTE_SECTION(google_malloc)
1758void* cpp_throw_oom(size_t size) {
1759 return handle_oom(retry_malloc, reinterpret_cast<void *>(size),
1760 true, false);
1761}
1762
1763ATTRIBUTE_SECTION(google_malloc)
1764void* cpp_nothrow_oom(size_t size) {
1765 return handle_oom(retry_malloc, reinterpret_cast<void *>(size),
1766 true, true);
1767}
1768
1769ATTRIBUTE_SECTION(google_malloc)
1770void* malloc_oom(size_t size) {
1771 return handle_oom(retry_malloc, reinterpret_cast<void *>(size),
1772 false, true);
1773}
1774
1775// tcmalloc::allocate_full_XXX is called by fast-path malloc when some
1776// complex handling is needed (such as fetching object from central
1777// freelist or malloc sampling). It contains all 'operator new' logic,
1778// as opposed to malloc_fast_path which only deals with important
1779// subset of cases.
1780//
1781// Note that this is under tcmalloc namespace so that pprof
1782// can automatically filter it out of growthz/heapz profiles.
1783//
1784// We have slightly fancy setup because we need to call hooks from
1785// function in 'google_malloc' section and we cannot place template
1786// into this section. Thus 3 separate functions 'built' by macros.
1787//
1788// Also note that we're carefully orchestrating for
1789// MallocHook::GetCallerStackTrace to work even if compiler isn't
1790// optimizing tail calls (e.g. -O0 is given). We still require
1791// ATTRIBUTE_ALWAYS_INLINE to work for that case, but it was seen to
1792// work for -O0 -fno-inline across both GCC and clang. I.e. in this
1793// case we'll get stack frame for tc_new, followed by stack frame for
1794// allocate_full_cpp_throw_oom, followed by hooks machinery and user
1795// code's stack frames. So GetCallerStackTrace will find 2
1796// subsequent stack frames in google_malloc section and correctly
1797// 'cut' stack trace just before tc_new.
1798template <void* OOMHandler(size_t)>
1799ATTRIBUTE_ALWAYS_INLINE inline
1800static void* do_allocate_full(size_t size) {
1801 void* p = do_malloc(size);
1802 if (PREDICT_FALSE(p == NULL)) {
1803 p = OOMHandler(size);
1804 }
1805 MallocHook::InvokeNewHook(p, size);
1806 return CheckedMallocResult(p);
1807}
1808
1809#define AF(oom) \
1810 ATTRIBUTE_SECTION(google_malloc) \
1811 void* allocate_full_##oom(size_t size) { \
1812 return do_allocate_full<oom>(size); \
1813 }
1814
1815AF(cpp_throw_oom)
1816AF(cpp_nothrow_oom)
1817AF(malloc_oom)
1818
1819#undef AF
1820
1821template <void* OOMHandler(size_t)>
1822static ATTRIBUTE_ALWAYS_INLINE inline void* dispatch_allocate_full(size_t size) {
1823 if (OOMHandler == cpp_throw_oom) {
1824 return allocate_full_cpp_throw_oom(size);
1825 }
1826 if (OOMHandler == cpp_nothrow_oom) {
1827 return allocate_full_cpp_nothrow_oom(size);
1828 }
1829 ASSERT(OOMHandler == malloc_oom);
1830 return allocate_full_malloc_oom(size);
1831}
1832
1833struct retry_memalign_data {
1834 size_t align;
1835 size_t size;
1836};
1837
1838static void *retry_do_memalign(void *arg) {
1839 retry_memalign_data *data = static_cast<retry_memalign_data *>(arg);
1840 return do_memalign_pages(data->align, data->size);
1841}
1842
1843static ATTRIBUTE_SECTION(google_malloc)
1844void* memalign_pages(size_t align, size_t size,
1845 bool from_operator, bool nothrow) {
1846 void *rv = do_memalign_pages(align, size);
1847 if (PREDICT_FALSE(rv == NULL)) {
1848 retry_memalign_data data;
1849 data.align = align;
1850 data.size = size;
1851 rv = handle_oom(retry_do_memalign, &data,
1852 from_operator, nothrow);
1853 }
1854 MallocHook::InvokeNewHook(rv, size);
1855 return CheckedMallocResult(rv);
1856}
1857
1858} // namespace tcmalloc
1859
1860// This is quick, fast-path-only implementation of malloc/new. It is
1861// designed to only have support for fast-path. It checks if more
1862// complex handling is needed (such as a pageheap allocation or
1863// sampling) and only performs allocation if none of those uncommon
1864// conditions hold. When we have one of those odd cases it simply
1865// tail-calls to one of tcmalloc::allocate_full_XXX defined above.
1866//
1867// Such approach was found to be quite effective. Generated code for
1868// tc_{new,malloc} either succeeds quickly or tail-calls to
1869// allocate_full. Terseness of the source and lack of
1870// non-tail calls enables compiler to produce better code. Also
1871// produced code is short enough to enable effort-less human
1872// comprehension. Which itself led to elimination of various checks
1873// that were not necessary for fast-path.
1874template <void* OOMHandler(size_t)>
1875ATTRIBUTE_ALWAYS_INLINE inline
1876static void * malloc_fast_path(size_t size) {
1877 if (PREDICT_FALSE(!base::internal::new_hooks_.empty())) {
1878 return tcmalloc::dispatch_allocate_full<OOMHandler>(size);
1879 }
1880
1881 ThreadCache *cache = ThreadCache::GetFastPathCache();
1882
1883 if (PREDICT_FALSE(cache == NULL)) {
1884 return tcmalloc::dispatch_allocate_full<OOMHandler>(size);
1885 }
1886
1887 uint32 cl;
1888 if (PREDICT_FALSE(!Static::sizemap()->GetSizeClass(size, &cl))) {
1889 return tcmalloc::dispatch_allocate_full<OOMHandler>(size);
1890 }
1891
1892 size_t allocated_size = Static::sizemap()->ByteSizeForClass(cl);
1893
1894 if (PREDICT_FALSE(!cache->TryRecordAllocationFast(allocated_size))) {
1895 return tcmalloc::dispatch_allocate_full<OOMHandler>(size);
1896 }
1897
1898 return CheckedMallocResult(cache->Allocate(allocated_size, cl, OOMHandler));
1899}
1900
1901template <void* OOMHandler(size_t)>
1902ATTRIBUTE_ALWAYS_INLINE inline
1903static void* memalign_fast_path(size_t align, size_t size) {
1904 if (PREDICT_FALSE(align > kPageSize)) {
1905 if (OOMHandler == tcmalloc::cpp_throw_oom) {
1906 return tcmalloc::memalign_pages(align, size, true, false);
1907 } else if (OOMHandler == tcmalloc::cpp_nothrow_oom) {
1908 return tcmalloc::memalign_pages(align, size, true, true);
1909 } else {
1910 ASSERT(OOMHandler == tcmalloc::malloc_oom);
1911 return tcmalloc::memalign_pages(align, size, false, true);
1912 }
1913 }
1914
1915 // Everything with alignment <= kPageSize we can easily delegate to
1916 // regular malloc
1917
1918 return malloc_fast_path<OOMHandler>(align_size_up(size, align));
1919}
1920
1921extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN
1922void* tc_malloc(size_t size) PERFTOOLS_NOTHROW {
1923 return malloc_fast_path<tcmalloc::malloc_oom>(size);
1924}
1925
1926static ATTRIBUTE_ALWAYS_INLINE inline
1927void free_fast_path(void *ptr) {
1928 if (PREDICT_FALSE(!base::internal::delete_hooks_.empty())) {
1929 tcmalloc::invoke_hooks_and_free(ptr);
1930 return;
1931 }
1932 do_free(ptr);
1933}
1934
1935extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN
1936void tc_free(void* ptr) PERFTOOLS_NOTHROW {
1937 free_fast_path(ptr);
1938}
1939
1940extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN
1941void tc_free_sized(void *ptr, size_t size) PERFTOOLS_NOTHROW {
1942 if (PREDICT_FALSE(!base::internal::delete_hooks_.empty())) {
1943 tcmalloc::invoke_hooks_and_free(ptr);
1944 return;
1945 }
1946#ifndef NO_TCMALLOC_SAMPLES
1947 // if ptr is kPageSize-aligned, then it could be sampled allocation,
1948 // thus we don't trust hint and just do plain free. It also handles
1949 // nullptr for us.
1950 if (PREDICT_FALSE((reinterpret_cast<uintptr_t>(ptr) & (kPageSize-1)) == 0)) {
1951 tc_free(ptr);
1952 return;
1953 }
1954#else
1955 if (!ptr) {
1956 return;
1957 }
1958#endif
1959 do_free_with_callback(ptr, &InvalidFree, true, size);
1960}
1961
1962#ifdef TC_ALIAS
1963
1964extern "C" PERFTOOLS_DLL_DECL void tc_delete_sized(void *p, size_t size) PERFTOOLS_NOTHROW
1965 TC_ALIAS(tc_free_sized);
1966extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_sized(void *p, size_t size) PERFTOOLS_NOTHROW
1967 TC_ALIAS(tc_free_sized);
1968
1969#else
1970
1971extern "C" PERFTOOLS_DLL_DECL void tc_delete_sized(void *p, size_t size) PERFTOOLS_NOTHROW {
1972 tc_free_sized(p, size);
1973}
1974extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_sized(void *p, size_t size) PERFTOOLS_NOTHROW {
1975 tc_free_sized(p, size);
1976}
1977
1978#endif
1979
Austin Schuh745610d2015-09-06 18:19:50 -07001980extern "C" PERFTOOLS_DLL_DECL void* tc_calloc(size_t n,
Brian Silverman20350ac2021-11-17 18:19:55 -08001981 size_t elem_size) PERFTOOLS_NOTHROW {
1982 if (ThreadCache::IsUseEmergencyMalloc()) {
1983 return tcmalloc::EmergencyCalloc(n, elem_size);
1984 }
Austin Schuh745610d2015-09-06 18:19:50 -07001985 void* result = do_calloc(n, elem_size);
1986 MallocHook::InvokeNewHook(result, n * elem_size);
1987 return result;
1988}
1989
Brian Silverman20350ac2021-11-17 18:19:55 -08001990extern "C" PERFTOOLS_DLL_DECL void tc_cfree(void* ptr) PERFTOOLS_NOTHROW
1991#ifdef TC_ALIAS
1992TC_ALIAS(tc_free);
1993#else
1994{
1995 free_fast_path(ptr);
Austin Schuh745610d2015-09-06 18:19:50 -07001996}
Brian Silverman20350ac2021-11-17 18:19:55 -08001997#endif
Austin Schuh745610d2015-09-06 18:19:50 -07001998
1999extern "C" PERFTOOLS_DLL_DECL void* tc_realloc(void* old_ptr,
Brian Silverman20350ac2021-11-17 18:19:55 -08002000 size_t new_size) PERFTOOLS_NOTHROW {
Austin Schuh745610d2015-09-06 18:19:50 -07002001 if (old_ptr == NULL) {
2002 void* result = do_malloc_or_cpp_alloc(new_size);
2003 MallocHook::InvokeNewHook(result, new_size);
2004 return result;
2005 }
2006 if (new_size == 0) {
2007 MallocHook::InvokeDeleteHook(old_ptr);
2008 do_free(old_ptr);
2009 return NULL;
2010 }
Brian Silverman20350ac2021-11-17 18:19:55 -08002011 if (PREDICT_FALSE(tcmalloc::IsEmergencyPtr(old_ptr))) {
2012 return tcmalloc::EmergencyRealloc(old_ptr, new_size);
2013 }
Austin Schuh745610d2015-09-06 18:19:50 -07002014 return do_realloc(old_ptr, new_size);
2015}
2016
Brian Silverman20350ac2021-11-17 18:19:55 -08002017extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN
2018void* tc_new(size_t size) {
2019 return malloc_fast_path<tcmalloc::cpp_throw_oom>(size);
Austin Schuh745610d2015-09-06 18:19:50 -07002020}
2021
Brian Silverman20350ac2021-11-17 18:19:55 -08002022extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN
2023void* tc_new_nothrow(size_t size, const std::nothrow_t&) PERFTOOLS_NOTHROW {
2024 return malloc_fast_path<tcmalloc::cpp_nothrow_oom>(size);
Austin Schuh745610d2015-09-06 18:19:50 -07002025}
2026
Brian Silverman20350ac2021-11-17 18:19:55 -08002027extern "C" PERFTOOLS_DLL_DECL void tc_delete(void* p) PERFTOOLS_NOTHROW
2028#ifdef TC_ALIAS
2029TC_ALIAS(tc_free);
2030#else
2031{
2032 free_fast_path(p);
Austin Schuh745610d2015-09-06 18:19:50 -07002033}
Brian Silverman20350ac2021-11-17 18:19:55 -08002034#endif
Austin Schuh745610d2015-09-06 18:19:50 -07002035
2036// Standard C++ library implementations define and use this
2037// (via ::operator delete(ptr, nothrow)).
2038// But it's really the same as normal delete, so we just do the same thing.
Brian Silverman20350ac2021-11-17 18:19:55 -08002039extern "C" PERFTOOLS_DLL_DECL void tc_delete_nothrow(void* p, const std::nothrow_t&) PERFTOOLS_NOTHROW
2040{
2041 if (PREDICT_FALSE(!base::internal::delete_hooks_.empty())) {
2042 tcmalloc::invoke_hooks_and_free(p);
2043 return;
2044 }
Austin Schuh745610d2015-09-06 18:19:50 -07002045 do_free(p);
2046}
2047
Brian Silverman20350ac2021-11-17 18:19:55 -08002048extern "C" PERFTOOLS_DLL_DECL void* tc_newarray(size_t size)
2049#ifdef TC_ALIAS
2050TC_ALIAS(tc_new);
2051#else
2052{
2053 return malloc_fast_path<tcmalloc::cpp_throw_oom>(size);
Austin Schuh745610d2015-09-06 18:19:50 -07002054}
Brian Silverman20350ac2021-11-17 18:19:55 -08002055#endif
Austin Schuh745610d2015-09-06 18:19:50 -07002056
2057extern "C" PERFTOOLS_DLL_DECL void* tc_newarray_nothrow(size_t size, const std::nothrow_t&)
Brian Silverman20350ac2021-11-17 18:19:55 -08002058 PERFTOOLS_NOTHROW
2059#ifdef TC_ALIAS
2060TC_ALIAS(tc_new_nothrow);
2061#else
2062{
2063 return malloc_fast_path<tcmalloc::cpp_nothrow_oom>(size);
Austin Schuh745610d2015-09-06 18:19:50 -07002064}
Brian Silverman20350ac2021-11-17 18:19:55 -08002065#endif
Austin Schuh745610d2015-09-06 18:19:50 -07002066
Brian Silverman20350ac2021-11-17 18:19:55 -08002067extern "C" PERFTOOLS_DLL_DECL void tc_deletearray(void* p) PERFTOOLS_NOTHROW
2068#ifdef TC_ALIAS
2069TC_ALIAS(tc_free);
2070#else
2071{
2072 free_fast_path(p);
Austin Schuh745610d2015-09-06 18:19:50 -07002073}
Brian Silverman20350ac2021-11-17 18:19:55 -08002074#endif
Austin Schuh745610d2015-09-06 18:19:50 -07002075
Brian Silverman20350ac2021-11-17 18:19:55 -08002076extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_nothrow(void* p, const std::nothrow_t&) PERFTOOLS_NOTHROW
2077#ifdef TC_ALIAS
2078TC_ALIAS(tc_delete_nothrow);
2079#else
2080{
2081 free_fast_path(p);
Austin Schuh745610d2015-09-06 18:19:50 -07002082}
Brian Silverman20350ac2021-11-17 18:19:55 -08002083#endif
Austin Schuh745610d2015-09-06 18:19:50 -07002084
Brian Silverman20350ac2021-11-17 18:19:55 -08002085extern "C" PERFTOOLS_DLL_DECL CACHELINE_ALIGNED_FN
2086void* tc_memalign(size_t align, size_t size) PERFTOOLS_NOTHROW {
2087 return memalign_fast_path<tcmalloc::malloc_oom>(align, size);
Austin Schuh745610d2015-09-06 18:19:50 -07002088}
2089
2090extern "C" PERFTOOLS_DLL_DECL int tc_posix_memalign(
Brian Silverman20350ac2021-11-17 18:19:55 -08002091 void** result_ptr, size_t align, size_t size) PERFTOOLS_NOTHROW {
Austin Schuh745610d2015-09-06 18:19:50 -07002092 if (((align % sizeof(void*)) != 0) ||
2093 ((align & (align - 1)) != 0) ||
2094 (align == 0)) {
2095 return EINVAL;
2096 }
2097
Brian Silverman20350ac2021-11-17 18:19:55 -08002098 void* result = tc_memalign(align, size);
2099 if (PREDICT_FALSE(result == NULL)) {
Austin Schuh745610d2015-09-06 18:19:50 -07002100 return ENOMEM;
2101 } else {
2102 *result_ptr = result;
2103 return 0;
2104 }
2105}
2106
Brian Silverman20350ac2021-11-17 18:19:55 -08002107#if defined(ENABLE_ALIGNED_NEW_DELETE)
Austin Schuh745610d2015-09-06 18:19:50 -07002108
Brian Silverman20350ac2021-11-17 18:19:55 -08002109extern "C" PERFTOOLS_DLL_DECL void* tc_new_aligned(size_t size, std::align_val_t align) {
2110 return memalign_fast_path<tcmalloc::cpp_throw_oom>(static_cast<size_t>(align), size);
Austin Schuh745610d2015-09-06 18:19:50 -07002111}
2112
Brian Silverman20350ac2021-11-17 18:19:55 -08002113extern "C" PERFTOOLS_DLL_DECL void* tc_new_aligned_nothrow(size_t size, std::align_val_t align, const std::nothrow_t&) PERFTOOLS_NOTHROW {
2114 return memalign_fast_path<tcmalloc::cpp_nothrow_oom>(static_cast<size_t>(align), size);
2115}
2116
2117extern "C" PERFTOOLS_DLL_DECL void tc_delete_aligned(void* p, std::align_val_t) PERFTOOLS_NOTHROW
2118{
2119 free_fast_path(p);
2120}
2121
2122// There is no easy way to obtain the actual size used by do_memalign to allocate aligned storage, so for now
2123// just ignore the size. It might get useful in the future.
2124extern "C" PERFTOOLS_DLL_DECL void tc_delete_sized_aligned(void* p, size_t size, std::align_val_t align) PERFTOOLS_NOTHROW
2125{
2126 free_fast_path(p);
2127}
2128
2129extern "C" PERFTOOLS_DLL_DECL void tc_delete_aligned_nothrow(void* p, std::align_val_t, const std::nothrow_t&) PERFTOOLS_NOTHROW
2130{
2131 free_fast_path(p);
2132}
2133
2134extern "C" PERFTOOLS_DLL_DECL void* tc_newarray_aligned(size_t size, std::align_val_t align)
2135#ifdef TC_ALIAS
2136TC_ALIAS(tc_new_aligned);
2137#else
2138{
2139 return memalign_fast_path<tcmalloc::cpp_throw_oom>(static_cast<size_t>(align), size);
2140}
2141#endif
2142
2143extern "C" PERFTOOLS_DLL_DECL void* tc_newarray_aligned_nothrow(size_t size, std::align_val_t align, const std::nothrow_t& nt) PERFTOOLS_NOTHROW
2144#ifdef TC_ALIAS
2145TC_ALIAS(tc_new_aligned_nothrow);
2146#else
2147{
2148 return memalign_fast_path<tcmalloc::cpp_nothrow_oom>(static_cast<size_t>(align), size);
2149}
2150#endif
2151
2152extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_aligned(void* p, std::align_val_t) PERFTOOLS_NOTHROW
2153#ifdef TC_ALIAS
2154TC_ALIAS(tc_delete_aligned);
2155#else
2156{
2157 free_fast_path(p);
2158}
2159#endif
2160
2161// There is no easy way to obtain the actual size used by do_memalign to allocate aligned storage, so for now
2162// just ignore the size. It might get useful in the future.
2163extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_sized_aligned(void* p, size_t size, std::align_val_t align) PERFTOOLS_NOTHROW
2164#ifdef TC_ALIAS
2165TC_ALIAS(tc_delete_sized_aligned);
2166#else
2167{
2168 free_fast_path(p);
2169}
2170#endif
2171
2172extern "C" PERFTOOLS_DLL_DECL void tc_deletearray_aligned_nothrow(void* p, std::align_val_t, const std::nothrow_t&) PERFTOOLS_NOTHROW
2173#ifdef TC_ALIAS
2174TC_ALIAS(tc_delete_aligned_nothrow);
2175#else
2176{
2177 free_fast_path(p);
2178}
2179#endif
2180
2181#endif // defined(ENABLE_ALIGNED_NEW_DELETE)
2182
2183static size_t pagesize = 0;
2184
2185extern "C" PERFTOOLS_DLL_DECL void* tc_valloc(size_t size) PERFTOOLS_NOTHROW {
2186 // Allocate page-aligned object of length >= size bytes
2187 if (pagesize == 0) pagesize = getpagesize();
2188 return tc_memalign(pagesize, size);
2189}
2190
2191extern "C" PERFTOOLS_DLL_DECL void* tc_pvalloc(size_t size) PERFTOOLS_NOTHROW {
Austin Schuh745610d2015-09-06 18:19:50 -07002192 // Round up size to a multiple of pagesize
2193 if (pagesize == 0) pagesize = getpagesize();
2194 if (size == 0) { // pvalloc(0) should allocate one page, according to
2195 size = pagesize; // http://man.free4web.biz/man3/libmpatrol.3.html
2196 }
2197 size = (size + pagesize - 1) & ~(pagesize - 1);
Brian Silverman20350ac2021-11-17 18:19:55 -08002198 return tc_memalign(pagesize, size);
Austin Schuh745610d2015-09-06 18:19:50 -07002199}
2200
Brian Silverman20350ac2021-11-17 18:19:55 -08002201extern "C" PERFTOOLS_DLL_DECL void tc_malloc_stats(void) PERFTOOLS_NOTHROW {
Austin Schuh745610d2015-09-06 18:19:50 -07002202 do_malloc_stats();
2203}
2204
Brian Silverman20350ac2021-11-17 18:19:55 -08002205extern "C" PERFTOOLS_DLL_DECL int tc_mallopt(int cmd, int value) PERFTOOLS_NOTHROW {
Austin Schuh745610d2015-09-06 18:19:50 -07002206 return do_mallopt(cmd, value);
2207}
2208
2209#ifdef HAVE_STRUCT_MALLINFO
Brian Silverman20350ac2021-11-17 18:19:55 -08002210extern "C" PERFTOOLS_DLL_DECL struct mallinfo tc_mallinfo(void) PERFTOOLS_NOTHROW {
Austin Schuh745610d2015-09-06 18:19:50 -07002211 return do_mallinfo();
2212}
2213#endif
2214
Brian Silverman20350ac2021-11-17 18:19:55 -08002215extern "C" PERFTOOLS_DLL_DECL size_t tc_malloc_size(void* ptr) PERFTOOLS_NOTHROW {
Austin Schuh745610d2015-09-06 18:19:50 -07002216 return MallocExtension::instance()->GetAllocatedSize(ptr);
2217}
2218
Brian Silverman20350ac2021-11-17 18:19:55 -08002219extern "C" PERFTOOLS_DLL_DECL void* tc_malloc_skip_new_handler(size_t size) PERFTOOLS_NOTHROW {
Austin Schuh745610d2015-09-06 18:19:50 -07002220 void* result = do_malloc(size);
2221 MallocHook::InvokeNewHook(result, size);
2222 return result;
2223}
2224
2225#endif // TCMALLOC_USING_DEBUGALLOCATION