Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1423)

Side by Side Diff: third_party/tcmalloc/chromium/src/tcmalloc.cc

Issue 9311003: Update the tcmalloc chromium branch to r144 (gperftools 2.0), and merge chromium-specific changes. (Closed) Base URL: http://git.chromium.org/git/chromium.git@trunk
Patch Set: Fixed. Created 8 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2005, Google Inc. 1 // Copyright (c) 2005, Google Inc.
2 // All rights reserved. 2 // All rights reserved.
3 // 3 //
4 // Redistribution and use in source and binary forms, with or without 4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are 5 // modification, are permitted provided that the following conditions are
6 // met: 6 // met:
7 // 7 //
8 // * Redistributions of source code must retain the above copyright 8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer. 9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above 10 // * Redistributions in binary form must reproduce the above
(...skipping 69 matching lines...) Expand 10 before | Expand all | Expand 10 after
80 // TODO: Bias reclamation to larger addresses 80 // TODO: Bias reclamation to larger addresses
81 // TODO: implement mallinfo/mallopt 81 // TODO: implement mallinfo/mallopt
82 // TODO: Better testing 82 // TODO: Better testing
83 // 83 //
84 // 9/28/2003 (new page-level allocator replaces ptmalloc2): 84 // 9/28/2003 (new page-level allocator replaces ptmalloc2):
85 // * malloc/free of small objects goes from ~300 ns to ~50 ns. 85 // * malloc/free of small objects goes from ~300 ns to ~50 ns.
86 // * allocation of a reasonably complicated struct 86 // * allocation of a reasonably complicated struct
87 // goes from about 1100 ns to about 300 ns. 87 // goes from about 1100 ns to about 300 ns.
88 88
89 #include "config.h" 89 #include "config.h"
90 #include <google/tcmalloc.h> 90 #include <gperftools/tcmalloc.h>
91 91
92 #include <errno.h> // for ENOMEM, EINVAL, errno 92 #include <errno.h> // for ENOMEM, EINVAL, errno
93 #ifdef HAVE_SYS_CDEFS_H 93 #ifdef HAVE_SYS_CDEFS_H
94 #include <sys/cdefs.h> // for __THROW 94 #include <sys/cdefs.h> // for __THROW
95 #endif 95 #endif
96 #ifdef HAVE_FEATURES_H
97 #include <features.h> // for __GLIBC__
98 #endif
99 #if defined HAVE_STDINT_H 96 #if defined HAVE_STDINT_H
100 #include <stdint.h> 97 #include <stdint.h>
101 #elif defined HAVE_INTTYPES_H 98 #elif defined HAVE_INTTYPES_H
102 #include <inttypes.h> 99 #include <inttypes.h>
103 #else 100 #else
104 #include <sys/types.h> 101 #include <sys/types.h>
105 #endif 102 #endif
106 #include <stddef.h> // for size_t, NULL 103 #include <stddef.h> // for size_t, NULL
107 #include <stdlib.h> // for getenv 104 #include <stdlib.h> // for getenv
108 #include <string.h> // for strcmp, memset, strlen, etc 105 #include <string.h> // for strcmp, memset, strlen, etc
109 #ifdef HAVE_UNISTD_H 106 #ifdef HAVE_UNISTD_H
110 #include <unistd.h> // for getpagesize, write, etc 107 #include <unistd.h> // for getpagesize, write, etc
111 #endif 108 #endif
112 #include <algorithm> // for max, min 109 #include <algorithm> // for max, min
113 #include <limits> // for numeric_limits 110 #include <limits> // for numeric_limits
114 #include <new> // for nothrow_t (ptr only), etc 111 #include <new> // for nothrow_t (ptr only), etc
115 #include <vector> // for vector 112 #include <vector> // for vector
116 113
117 #include <google/malloc_extension.h> 114 #include <gperftools/malloc_extension.h>
118 #include <google/malloc_hook.h> // for MallocHook 115 #include <gperftools/malloc_hook.h> // for MallocHook
119 #include "base/basictypes.h" // for int64 116 #include "base/basictypes.h" // for int64
120 #include "base/commandlineflags.h" // for RegisterFlagValidator, etc 117 #include "base/commandlineflags.h" // for RegisterFlagValidator, etc
121 #include "base/dynamic_annotations.h" // for RunningOnValgrind 118 #include "base/dynamic_annotations.h" // for RunningOnValgrind
122 #include "base/spinlock.h" // for SpinLockHolder 119 #include "base/spinlock.h" // for SpinLockHolder
123 #include "central_freelist.h" // for CentralFreeListPadded 120 #include "central_freelist.h" // for CentralFreeListPadded
124 #include "common.h" // for StackTrace, kPageShift, etc 121 #include "common.h" // for StackTrace, kPageShift, etc
125 #include "free_list.h" // for FL_Init 122 #include "free_list.h" // for FL_Init
126 #include "internal_logging.h" // for ASSERT, TCMalloc_Printer, etc 123 #include "internal_logging.h" // for ASSERT, TCMalloc_Printer, etc
127 #include "malloc_hook-inl.h" // for MallocHook::InvokeNewHook, etc 124 #include "malloc_hook-inl.h" // for MallocHook::InvokeNewHook, etc
128 #include "page_heap.h" // for PageHeap, PageHeap::Stats 125 #include "page_heap.h" // for PageHeap, PageHeap::Stats
(...skipping 14 matching lines...) Expand all
143 # include <sys/malloc.h> 140 # include <sys/malloc.h>
144 # elif defined(HAVE_MALLOC_MALLOC_H) 141 # elif defined(HAVE_MALLOC_MALLOC_H)
145 # include <malloc/malloc.h> 142 # include <malloc/malloc.h>
146 # endif 143 # endif
147 #endif 144 #endif
148 145
149 #if (defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)) && !defi ned(WIN32_OVERRIDE_ALLOCATORS) 146 #if (defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)) && !defi ned(WIN32_OVERRIDE_ALLOCATORS)
150 # define WIN32_DO_PATCHING 1 147 # define WIN32_DO_PATCHING 1
151 #endif 148 #endif
152 149
153 // GLibc 2.14+ requires the hook functions be declared volatile, based on the 150 // Some windows file somewhere (at least on cygwin) #define's small (!)
154 // value of the define __MALLOC_HOOK_VOLATILE. For compatibility with 151 #undef small
155 // older/non-GLibc implementations, provide an empty definition.
156 #if !defined(__MALLOC_HOOK_VOLATILE)
157 #define __MALLOC_HOOK_VOLATILE
158 #endif
159 152
160 using STL_NAMESPACE::max; 153 using STL_NAMESPACE::max;
161 using STL_NAMESPACE::numeric_limits; 154 using STL_NAMESPACE::numeric_limits;
162 using STL_NAMESPACE::vector; 155 using STL_NAMESPACE::vector;
156
157 #include "libc_override.h"
158
159 // __THROW is defined in glibc (via <sys/cdefs.h>). It means,
160 // counter-intuitively, "This function will never throw an exception."
161 // It's an optional optimization tool, but we may need to use it to
162 // match glibc prototypes.
163 #ifndef __THROW // I guess we're not on a glibc system
164 # define __THROW // __THROW is just an optimization, so ok to make it ""
165 #endif
166
163 using tcmalloc::AlignmentForSize; 167 using tcmalloc::AlignmentForSize;
168 using tcmalloc::kLog;
169 using tcmalloc::kCrash;
170 using tcmalloc::kCrashWithStats;
171 using tcmalloc::Log;
164 using tcmalloc::PageHeap; 172 using tcmalloc::PageHeap;
165 using tcmalloc::PageHeapAllocator; 173 using tcmalloc::PageHeapAllocator;
166 using tcmalloc::SizeMap; 174 using tcmalloc::SizeMap;
167 using tcmalloc::Span; 175 using tcmalloc::Span;
168 using tcmalloc::StackTrace; 176 using tcmalloc::StackTrace;
169 using tcmalloc::Static; 177 using tcmalloc::Static;
170 using tcmalloc::ThreadCache; 178 using tcmalloc::ThreadCache;
171 179
172 // __THROW is defined in glibc systems. It means, counter-intuitively,
173 // "This function will never throw an exception." It's an optional
174 // optimization tool, but we may need to use it to match glibc prototypes.
175 #ifndef __THROW // I guess we're not on a glibc system
176 # define __THROW // __THROW is just an optimization, so ok to make it ""
177 #endif
178
179 // ---- Double free debug declarations 180 // ---- Double free debug declarations
180 static size_t ExcludeSpaceForMark(size_t size); 181 static size_t ExcludeSpaceForMark(size_t size);
181 static void AddRoomForMark(size_t* size); 182 static void AddRoomForMark(size_t* size);
182 static void ExcludeMarkFromSize(size_t* new_size); 183 static void ExcludeMarkFromSize(size_t* new_size);
183 static void MarkAllocatedRegion(void* ptr); 184 static void MarkAllocatedRegion(void* ptr);
184 static void ValidateAllocatedRegion(void* ptr, size_t cl); 185 static void ValidateAllocatedRegion(void* ptr, size_t cl);
185 // ---- End Double free debug declarations 186 // ---- End Double free debug declarations
186 187
187 DECLARE_int64(tcmalloc_sample_parameter); 188 DECLARE_int64(tcmalloc_sample_parameter);
188 DECLARE_double(tcmalloc_release_rate); 189 DECLARE_double(tcmalloc_release_rate);
(...skipping 84 matching lines...) Expand 10 before | Expand all | Expand 10 after
273 // Some non-standard extensions that we support. 274 // Some non-standard extensions that we support.
274 275
275 // This is equivalent to 276 // This is equivalent to
276 // OS X: malloc_size() 277 // OS X: malloc_size()
277 // glibc: malloc_usable_size() 278 // glibc: malloc_usable_size()
278 // Windows: _msize() 279 // Windows: _msize()
279 size_t tc_malloc_size(void* p) __THROW 280 size_t tc_malloc_size(void* p) __THROW
280 ATTRIBUTE_SECTION(google_malloc); 281 ATTRIBUTE_SECTION(google_malloc);
281 } // extern "C" 282 } // extern "C"
282 283
283 // Override the libc functions to prefer our own instead. This comes
284 // first so code in tcmalloc.cc can use the overridden versions. One
285 // exception: in windows, by default, we patch our code into these
286 // functions (via src/windows/patch_function.cc) rather than override
287 // them. In that case, we don't want to do this overriding here.
288 #if !defined(WIN32_DO_PATCHING)
289
290 // TODO(mbelshe): Turn off TCMalloc's symbols for libc. We do that
291 // elsewhere.
292 #ifndef _WIN32
293
294 #if defined(__GNUC__) && !defined(__MACH__)
295 // Potentially faster variants that use the gcc alias extension.
296 // FreeBSD does support aliases, but apparently not correctly. :-(
297 // NOTE: we make many of these symbols weak, but do so in the makefile
298 // (via objcopy -W) and not here. That ends up being more portable.
299 # define ALIAS(x) __attribute__ ((alias (x)))
300 void* operator new(size_t size) throw (std::bad_alloc) ALIAS("tc_new");
301 void operator delete(void* p) __THROW ALIAS("tc_delete");
302 void* operator new[](size_t size) throw (std::bad_alloc) ALIAS("tc_newarray");
303 void operator delete[](void* p) __THROW ALIAS("tc_deletearray");
304 void* operator new(size_t size, const std::nothrow_t&) __THROW
305 ALIAS("tc_new_nothrow");
306 void* operator new[](size_t size, const std::nothrow_t&) __THROW
307 ALIAS("tc_newarray_nothrow");
308 void operator delete(void* size, const std::nothrow_t&) __THROW
309 ALIAS("tc_delete_nothrow");
310 void operator delete[](void* size, const std::nothrow_t&) __THROW
311 ALIAS("tc_deletearray_nothrow");
312 extern "C" {
313 void* malloc(size_t size) __THROW ALIAS("tc_malloc");
314 void free(void* ptr) __THROW ALIAS("tc_free");
315 void* realloc(void* ptr, size_t size) __THROW ALIAS("tc_realloc");
316 void* calloc(size_t n, size_t size) __THROW ALIAS("tc_calloc");
317 void cfree(void* ptr) __THROW ALIAS("tc_cfree");
318 void* memalign(size_t align, size_t s) __THROW ALIAS("tc_memalign");
319 void* valloc(size_t size) __THROW ALIAS("tc_valloc");
320 void* pvalloc(size_t size) __THROW ALIAS("tc_pvalloc");
321 int posix_memalign(void** r, size_t a, size_t s) __THROW
322 ALIAS("tc_posix_memalign");
323 void malloc_stats(void) __THROW ALIAS("tc_malloc_stats");
324 int mallopt(int cmd, int value) __THROW ALIAS("tc_mallopt");
325 #ifdef HAVE_STRUCT_MALLINFO
326 struct mallinfo mallinfo(void) __THROW ALIAS("tc_mallinfo");
327 #endif
328 size_t malloc_size(void* p) __THROW ALIAS("tc_malloc_size");
329 size_t malloc_usable_size(void* p) __THROW ALIAS("tc_malloc_size");
330 } // extern "C"
331 #else // #if defined(__GNUC__) && !defined(__MACH__)
332 // Portable wrappers
333 void* operator new(size_t size) { return tc_new(size); }
334 void operator delete(void* p) __THROW { tc_delete(p); }
335 void* operator new[](size_t size) { return tc_newarray(size); }
336 void operator delete[](void* p) __THROW { tc_deletearray(p); }
337 void* operator new(size_t size, const std::nothrow_t& nt) __THROW {
338 return tc_new_nothrow(size, nt);
339 }
340 void* operator new[](size_t size, const std::nothrow_t& nt) __THROW {
341 return tc_newarray_nothrow(size, nt);
342 }
343 void operator delete(void* ptr, const std::nothrow_t& nt) __THROW {
344 return tc_delete_nothrow(ptr, nt);
345 }
346 void operator delete[](void* ptr, const std::nothrow_t& nt) __THROW {
347 return tc_deletearray_nothrow(ptr, nt);
348 }
349 extern "C" {
350 void* malloc(size_t s) __THROW { return tc_malloc(s); }
351 void free(void* p) __THROW { tc_free(p); }
352 void* realloc(void* p, size_t s) __THROW { return tc_realloc(p, s); }
353 void* calloc(size_t n, size_t s) __THROW { return tc_calloc(n, s); }
354 void cfree(void* p) __THROW { tc_cfree(p); }
355 void* memalign(size_t a, size_t s) __THROW { return tc_memalign(a, s); }
356 void* valloc(size_t s) __THROW { return tc_valloc(s); }
357 void* pvalloc(size_t s) __THROW { return tc_pvalloc(s); }
358 int posix_memalign(void** r, size_t a, size_t s) __THROW {
359 return tc_posix_memalign(r, a, s);
360 }
361 void malloc_stats(void) __THROW { tc_malloc_stats(); }
362 int mallopt(int cmd, int v) __THROW { return tc_mallopt(cmd, v); }
363 #ifdef HAVE_STRUCT_MALLINFO
364 struct mallinfo mallinfo(void) __THROW { return tc_mallinfo(); }
365 #endif
366 size_t malloc_size(void* p) __THROW { return tc_malloc_size(p); }
367 size_t malloc_usable_size(void* p) __THROW { return tc_malloc_size(p); }
368 } // extern "C"
369 #endif // #if defined(__GNUC__)
370
371 // Some library routines on RedHat 9 allocate memory using malloc()
372 // and free it using __libc_free() (or vice-versa). Since we provide
373 // our own implementations of malloc/free, we need to make sure that
374 // the __libc_XXX variants (defined as part of glibc) also point to
375 // the same implementations.
376 #ifdef __GLIBC__ // only glibc defines __libc_*
377 extern "C" {
378 #ifdef ALIAS
379 void* __libc_malloc(size_t size) ALIAS("tc_malloc");
380 void __libc_free(void* ptr) ALIAS("tc_free");
381 void* __libc_realloc(void* ptr, size_t size) ALIAS("tc_realloc");
382 void* __libc_calloc(size_t n, size_t size) ALIAS("tc_calloc");
383 void __libc_cfree(void* ptr) ALIAS("tc_cfree");
384 void* __libc_memalign(size_t align, size_t s) ALIAS("tc_memalign");
385 void* __libc_valloc(size_t size) ALIAS("tc_valloc");
386 void* __libc_pvalloc(size_t size) ALIAS("tc_pvalloc");
387 int __posix_memalign(void** r, size_t a, size_t s) ALIAS("tc_posix_memalign");
388 #else // #ifdef ALIAS
389 void* __libc_malloc(size_t size) { return malloc(size); }
390 void __libc_free(void* ptr) { free(ptr); }
391 void* __libc_realloc(void* ptr, size_t size) { return realloc(ptr, size); }
392 void* __libc_calloc(size_t n, size_t size) { return calloc(n, size); }
393 void __libc_cfree(void* ptr) { cfree(ptr); }
394 void* __libc_memalign(size_t align, size_t s) { return memalign(align, s); }
395 void* __libc_valloc(size_t size) { return valloc(size); }
396 void* __libc_pvalloc(size_t size) { return pvalloc(size); }
397 int __posix_memalign(void** r, size_t a, size_t s) {
398 return posix_memalign(r, a, s);
399 }
400 #endif // #ifdef ALIAS
401 } // extern "C"
402 #endif // ifdef __GLIBC__
403
404 #if defined(__GLIBC__) && defined(HAVE_MALLOC_H)
405 // If we're using glibc, then override glibc malloc hooks to make sure that even
406 // if calls fall through to ptmalloc (due to dlopen() with RTLD_DEEPBIND or what
407 // not), ptmalloc will use TCMalloc.
408
409 static void* tc_ptmalloc_malloc_hook(size_t size, const void* caller) {
410 return tc_malloc(size);
411 }
412
413 void* (*__MALLOC_HOOK_VOLATILE __malloc_hook)(
414 size_t size, const void* caller) = tc_ptmalloc_malloc_hook;
415
416 static void* tc_ptmalloc_realloc_hook(
417 void* ptr, size_t size, const void* caller) {
418 return tc_realloc(ptr, size);
419 }
420
421 void* (*__MALLOC_HOOK_VOLATILE __realloc_hook)(
422 void* ptr, size_t size, const void* caller) = tc_ptmalloc_realloc_hook;
423
424 static void tc_ptmalloc_free_hook(void* ptr, const void* caller) {
425 tc_free(ptr);
426 }
427
428 void (*__MALLOC_HOOK_VOLATILE __free_hook)(void* ptr, const void* caller) = tc_p tmalloc_free_hook;
429
430 #endif
431
432 #endif // #ifndef _WIN32
433 #undef ALIAS
434
435 #endif // #ifndef(WIN32_DO_PATCHING)
436
437 284
438 // ----------------------- IMPLEMENTATION ------------------------------- 285 // ----------------------- IMPLEMENTATION -------------------------------
439 286
440 static int tc_new_mode = 0; // See tc_set_new_mode(). 287 static int tc_new_mode = 0; // See tc_set_new_mode().
441 288
442 // Routines such as free() and realloc() catch some erroneous pointers 289 // Routines such as free() and realloc() catch some erroneous pointers
443 // passed to them, and invoke the below when they do. (An erroneous pointer 290 // passed to them, and invoke the below when they do. (An erroneous pointer
444 // won't be caught if it's within a valid span or a stale span for which 291 // won't be caught if it's within a valid span or a stale span for which
445 // the pagemap cache has a non-zero sizeclass.) This is a cheap (source-editing 292 // the pagemap cache has a non-zero sizeclass.) This is a cheap (source-editing
446 // required) kind of exception handling for these routines. 293 // required) kind of exception handling for these routines.
447 namespace { 294 namespace {
448 void InvalidFree(void* ptr) { 295 void InvalidFree(void* ptr) {
449 CRASH("Attempt to free invalid pointer: %p\n", ptr); 296 Log(kCrash, __FILE__, __LINE__, "Attempt to free invalid pointer", ptr);
450 } 297 }
451 298
452 size_t InvalidGetSizeForRealloc(void* old_ptr) { 299 size_t InvalidGetSizeForRealloc(const void* old_ptr) {
453 CRASH("Attempt to realloc invalid pointer: %p\n", old_ptr); 300 Log(kCrash, __FILE__, __LINE__,
301 "Attempt to realloc invalid pointer", old_ptr);
454 return 0; 302 return 0;
455 } 303 }
456 304
457 size_t InvalidGetAllocatedSize(void* ptr) { 305 size_t InvalidGetAllocatedSize(const void* ptr) {
458 CRASH("Attempt to get the size of an invalid pointer: %p\n", ptr); 306 Log(kCrash, __FILE__, __LINE__,
307 "Attempt to get the size of an invalid pointer", ptr);
459 return 0; 308 return 0;
460 } 309 }
461 } // unnamed namespace 310 } // unnamed namespace
462 311
463 // Extract interesting stats 312 // Extract interesting stats
464 struct TCMallocStats { 313 struct TCMallocStats {
465 uint64_t thread_bytes; // Bytes in thread caches 314 uint64_t thread_bytes; // Bytes in thread caches
466 uint64_t central_bytes; // Bytes in central cache 315 uint64_t central_bytes; // Bytes in central cache
467 uint64_t transfer_bytes; // Bytes in central transfer cache 316 uint64_t transfer_bytes; // Bytes in central transfer cache
468 uint64_t metadata_bytes; // Bytes alloced for metadata 317 uint64_t metadata_bytes; // Bytes alloced for metadata
469 PageHeap::Stats pageheap; // Stats from page heap 318 PageHeap::Stats pageheap; // Stats from page heap
470 }; 319 };
471 320
472 // Get stats into "r". Also get per-size-class counts if class_count != NULL 321 // Get stats into "r". Also get per-size-class counts if class_count != NULL
473 static void ExtractStats(TCMallocStats* r, uint64_t* class_count) { 322 static void ExtractStats(TCMallocStats* r, uint64_t* class_count,
323 PageHeap::SmallSpanStats* small_spans,
324 PageHeap::LargeSpanStats* large_spans) {
474 r->central_bytes = 0; 325 r->central_bytes = 0;
475 r->transfer_bytes = 0; 326 r->transfer_bytes = 0;
476 for (int cl = 0; cl < kNumClasses; ++cl) { 327 for (int cl = 0; cl < kNumClasses; ++cl) {
477 const int length = Static::central_cache()[cl].length(); 328 const int length = Static::central_cache()[cl].length();
478 const int tc_length = Static::central_cache()[cl].tc_length(); 329 const int tc_length = Static::central_cache()[cl].tc_length();
330 const size_t cache_overhead = Static::central_cache()[cl].OverheadBytes();
479 const size_t size = static_cast<uint64_t>( 331 const size_t size = static_cast<uint64_t>(
480 Static::sizemap()->ByteSizeForClass(cl)); 332 Static::sizemap()->ByteSizeForClass(cl));
481 r->central_bytes += (size * length); 333 r->central_bytes += (size * length) + cache_overhead;
482 r->transfer_bytes += (size * tc_length); 334 r->transfer_bytes += (size * tc_length);
483 if (class_count) class_count[cl] = length + tc_length; 335 if (class_count) class_count[cl] = length + tc_length;
484 } 336 }
485 337
486 // Add stats from per-thread heaps 338 // Add stats from per-thread heaps
487 r->thread_bytes = 0; 339 r->thread_bytes = 0;
488 { // scope 340 { // scope
489 SpinLockHolder h(Static::pageheap_lock()); 341 SpinLockHolder h(Static::pageheap_lock());
490 ThreadCache::GetThreadStats(&r->thread_bytes, class_count); 342 ThreadCache::GetThreadStats(&r->thread_bytes, class_count);
491 r->metadata_bytes = tcmalloc::metadata_system_bytes(); 343 r->metadata_bytes = tcmalloc::metadata_system_bytes();
492 r->pageheap = Static::pageheap()->stats(); 344 r->pageheap = Static::pageheap()->stats();
345 if (small_spans != NULL) {
346 Static::pageheap()->GetSmallSpanStats(small_spans);
347 }
348 if (large_spans != NULL) {
349 Static::pageheap()->GetLargeSpanStats(large_spans);
350 }
493 } 351 }
494 } 352 }
495 353
354 static double PagesToMiB(uint64_t pages) {
355 return (pages << kPageShift) / 1048576.0;
356 }
357
496 // WRITE stats to "out" 358 // WRITE stats to "out"
497 static void DumpStats(TCMalloc_Printer* out, int level) { 359 static void DumpStats(TCMalloc_Printer* out, int level) {
498 TCMallocStats stats; 360 TCMallocStats stats;
499 uint64_t class_count[kNumClasses]; 361 uint64_t class_count[kNumClasses];
500 ExtractStats(&stats, (level >= 2 ? class_count : NULL)); 362 PageHeap::SmallSpanStats small;
363 PageHeap::LargeSpanStats large;
364 if (level >= 2) {
365 ExtractStats(&stats, class_count, &small, &large);
366 } else {
367 ExtractStats(&stats, NULL, NULL, NULL);
368 }
501 369
502 static const double MiB = 1048576.0; 370 static const double MiB = 1048576.0;
503 371
504 const uint64_t virtual_memory_used = (stats.pageheap.system_bytes 372 const uint64_t virtual_memory_used = (stats.pageheap.system_bytes
505 + stats.metadata_bytes); 373 + stats.metadata_bytes);
506 const uint64_t physical_memory_used = (virtual_memory_used 374 const uint64_t physical_memory_used = (virtual_memory_used
507 - stats.pageheap.unmapped_bytes); 375 - stats.pageheap.unmapped_bytes);
508 const uint64_t bytes_in_use_by_app = (physical_memory_used 376 const uint64_t bytes_in_use_by_app = (physical_memory_used
509 - stats.metadata_bytes 377 - stats.metadata_bytes
510 - stats.pageheap.free_bytes 378 - stats.pageheap.free_bytes
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
574 cumulative += class_bytes; 442 cumulative += class_bytes;
575 out->printf("class %3d [ %8" PRIuS " bytes ] : " 443 out->printf("class %3d [ %8" PRIuS " bytes ] : "
576 "%8" PRIu64 " objs; %5.1f MiB; %5.1f cum MiB\n", 444 "%8" PRIu64 " objs; %5.1f MiB; %5.1f cum MiB\n",
577 cl, Static::sizemap()->ByteSizeForClass(cl), 445 cl, Static::sizemap()->ByteSizeForClass(cl),
578 class_count[cl], 446 class_count[cl],
579 class_bytes / MiB, 447 class_bytes / MiB,
580 cumulative / MiB); 448 cumulative / MiB);
581 } 449 }
582 } 450 }
583 451
584 SpinLockHolder h(Static::pageheap_lock()); 452 // append page heap info
585 Static::pageheap()->Dump(out); 453 int nonempty_sizes = 0;
454 for (int s = 0; s < kMaxPages; s++) {
455 if (small.normal_length[s] + small.returned_length[s] > 0) {
456 nonempty_sizes++;
457 }
458 }
459 out->printf("------------------------------------------------\n");
460 out->printf("PageHeap: %d sizes; %6.1f MiB free; %6.1f MiB unmapped\n",
461 nonempty_sizes, stats.pageheap.free_bytes / MiB,
462 stats.pageheap.unmapped_bytes / MiB);
463 out->printf("------------------------------------------------\n");
464 uint64_t total_normal = 0;
465 uint64_t total_returned = 0;
466 for (int s = 0; s < kMaxPages; s++) {
467 const int n_length = small.normal_length[s];
468 const int r_length = small.returned_length[s];
469 if (n_length + r_length > 0) {
470 uint64_t n_pages = s * n_length;
471 uint64_t r_pages = s * r_length;
472 total_normal += n_pages;
473 total_returned += r_pages;
474 out->printf("%6u pages * %6u spans ~ %6.1f MiB; %6.1f MiB cum"
475 "; unmapped: %6.1f MiB; %6.1f MiB cum\n",
476 s,
477 (n_length + r_length),
478 PagesToMiB(n_pages + r_pages),
479 PagesToMiB(total_normal + total_returned),
480 PagesToMiB(r_pages),
481 PagesToMiB(total_returned));
482 }
483 }
484
485 total_normal += large.normal_pages;
486 total_returned += large.returned_pages;
487 out->printf(">255 large * %6u spans ~ %6.1f MiB; %6.1f MiB cum"
488 "; unmapped: %6.1f MiB; %6.1f MiB cum\n",
489 static_cast<unsigned int>(large.spans),
490 PagesToMiB(large.normal_pages + large.returned_pages),
491 PagesToMiB(total_normal + total_returned),
492 PagesToMiB(large.returned_pages),
493 PagesToMiB(total_returned));
586 } 494 }
587 } 495 }
588 496
589 static void PrintStats(int level) { 497 static void PrintStats(int level) {
590 const int kBufferSize = 16 << 10; 498 const int kBufferSize = 16 << 10;
591 char* buffer = new char[kBufferSize]; 499 char* buffer = new char[kBufferSize];
592 TCMalloc_Printer printer(buffer, kBufferSize); 500 TCMalloc_Printer printer(buffer, kBufferSize);
593 DumpStats(&printer, level); 501 DumpStats(&printer, level);
594 write(STDERR_FILENO, buffer, strlen(buffer)); 502 write(STDERR_FILENO, buffer, strlen(buffer));
595 delete[] buffer; 503 delete[] buffer;
596 } 504 }
597 505
598 static void** DumpHeapGrowthStackTraces() { 506 static void** DumpHeapGrowthStackTraces() {
599 // Count how much space we need 507 // Count how much space we need
600 int needed_slots = 0; 508 int needed_slots = 0;
601 { 509 {
602 SpinLockHolder h(Static::pageheap_lock()); 510 SpinLockHolder h(Static::pageheap_lock());
603 for (StackTrace* t = Static::growth_stacks(); 511 for (StackTrace* t = Static::growth_stacks();
604 t != NULL; 512 t != NULL;
605 t = reinterpret_cast<StackTrace*>( 513 t = reinterpret_cast<StackTrace*>(
606 t->stack[tcmalloc::kMaxStackDepth-1])) { 514 t->stack[tcmalloc::kMaxStackDepth-1])) {
607 needed_slots += 3 + t->depth; 515 needed_slots += 3 + t->depth;
608 } 516 }
609 needed_slots += 100; // Slop in case list grows 517 needed_slots += 100; // Slop in case list grows
610 needed_slots += needed_slots/8; // An extra 12.5% slop 518 needed_slots += needed_slots/8; // An extra 12.5% slop
611 } 519 }
612 520
613 void** result = new void*[needed_slots]; 521 void** result = new void*[needed_slots];
614 if (result == NULL) { 522 if (result == NULL) {
615 MESSAGE("tcmalloc: allocation failed for stack trace slots", 523 Log(kLog, __FILE__, __LINE__,
616 needed_slots * sizeof(*result)); 524 "tcmalloc: allocation failed for stack trace slots",
525 needed_slots * sizeof(*result));
617 return NULL; 526 return NULL;
618 } 527 }
619 528
620 SpinLockHolder h(Static::pageheap_lock()); 529 SpinLockHolder h(Static::pageheap_lock());
621 int used_slots = 0; 530 int used_slots = 0;
622 for (StackTrace* t = Static::growth_stacks(); 531 for (StackTrace* t = Static::growth_stacks();
623 t != NULL; 532 t != NULL;
624 t = reinterpret_cast<StackTrace*>( 533 t = reinterpret_cast<StackTrace*>(
625 t->stack[tcmalloc::kMaxStackDepth-1])) { 534 t->stack[tcmalloc::kMaxStackDepth-1])) {
626 ASSERT(used_slots < needed_slots); // Need to leave room for terminator 535 ASSERT(used_slots < needed_slots); // Need to leave room for terminator
(...skipping 105 matching lines...) Expand 10 before | Expand all | Expand 10 after
732 641
733 virtual void Ranges(void* arg, RangeFunction func) { 642 virtual void Ranges(void* arg, RangeFunction func) {
734 IterateOverRanges(arg, func); 643 IterateOverRanges(arg, func);
735 } 644 }
736 645
737 virtual bool GetNumericProperty(const char* name, size_t* value) { 646 virtual bool GetNumericProperty(const char* name, size_t* value) {
738 ASSERT(name != NULL); 647 ASSERT(name != NULL);
739 648
740 if (strcmp(name, "generic.current_allocated_bytes") == 0) { 649 if (strcmp(name, "generic.current_allocated_bytes") == 0) {
741 TCMallocStats stats; 650 TCMallocStats stats;
742 ExtractStats(&stats, NULL); 651 ExtractStats(&stats, NULL, NULL, NULL);
743 *value = stats.pageheap.system_bytes 652 *value = stats.pageheap.system_bytes
744 - stats.thread_bytes 653 - stats.thread_bytes
745 - stats.central_bytes 654 - stats.central_bytes
746 - stats.transfer_bytes 655 - stats.transfer_bytes
747 - stats.pageheap.free_bytes 656 - stats.pageheap.free_bytes
748 - stats.pageheap.unmapped_bytes; 657 - stats.pageheap.unmapped_bytes;
749 return true; 658 return true;
750 } 659 }
751 660
752 if (strcmp(name, "generic.heap_size") == 0) { 661 if (strcmp(name, "generic.heap_size") == 0) {
753 TCMallocStats stats; 662 TCMallocStats stats;
754 ExtractStats(&stats, NULL); 663 ExtractStats(&stats, NULL, NULL, NULL);
755 *value = stats.pageheap.system_bytes; 664 *value = stats.pageheap.system_bytes;
756 return true; 665 return true;
757 } 666 }
758 667
759 if (strcmp(name, "tcmalloc.slack_bytes") == 0) { 668 if (strcmp(name, "tcmalloc.slack_bytes") == 0) {
760 // Kept for backwards compatibility. Now defined externally as: 669 // Kept for backwards compatibility. Now defined externally as:
761 // pageheap_free_bytes + pageheap_unmapped_bytes. 670 // pageheap_free_bytes + pageheap_unmapped_bytes.
762 SpinLockHolder l(Static::pageheap_lock()); 671 SpinLockHolder l(Static::pageheap_lock());
763 PageHeap::Stats stats = Static::pageheap()->stats(); 672 PageHeap::Stats stats = Static::pageheap()->stats();
764 *value = stats.free_bytes + stats.unmapped_bytes; 673 *value = stats.free_bytes + stats.unmapped_bytes;
(...skipping 13 matching lines...) Expand all
778 } 687 }
779 688
780 if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) { 689 if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
781 SpinLockHolder l(Static::pageheap_lock()); 690 SpinLockHolder l(Static::pageheap_lock());
782 *value = ThreadCache::overall_thread_cache_size(); 691 *value = ThreadCache::overall_thread_cache_size();
783 return true; 692 return true;
784 } 693 }
785 694
786 if (strcmp(name, "tcmalloc.current_total_thread_cache_bytes") == 0) { 695 if (strcmp(name, "tcmalloc.current_total_thread_cache_bytes") == 0) {
787 TCMallocStats stats; 696 TCMallocStats stats;
788 ExtractStats(&stats, NULL); 697 ExtractStats(&stats, NULL, NULL, NULL);
789 *value = stats.thread_bytes; 698 *value = stats.thread_bytes;
790 return true; 699 return true;
791 } 700 }
792 701
793 return false; 702 return false;
794 } 703 }
795 704
796 virtual bool SetNumericProperty(const char* name, size_t value) { 705 virtual bool SetNumericProperty(const char* name, size_t value) {
797 ASSERT(name != NULL); 706 ASSERT(name != NULL);
798 707
(...skipping 60 matching lines...) Expand 10 before | Expand all | Expand 10 after
859 const size_t alloc_size = Static::sizemap()->ByteSizeForClass(cl); 768 const size_t alloc_size = Static::sizemap()->ByteSizeForClass(cl);
860 return alloc_size; 769 return alloc_size;
861 } else { 770 } else {
862 return tcmalloc::pages(size) << kPageShift; 771 return tcmalloc::pages(size) << kPageShift;
863 } 772 }
864 } 773 }
865 774
866 // This just calls GetSizeWithCallback, but because that's in an 775 // This just calls GetSizeWithCallback, but because that's in an
867 // unnamed namespace, we need to move the definition below it in the 776 // unnamed namespace, we need to move the definition below it in the
868 // file. 777 // file.
869 virtual size_t GetAllocatedSize(void* ptr); 778 virtual size_t GetAllocatedSize(const void* ptr);
779
780 // This duplicates some of the logic in GetSizeWithCallback, but is
781 // faster. This is important on OS X, where this function is called
782 // on every allocation operation.
783 virtual Ownership GetOwnership(const void* ptr) {
784 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
785 // The rest of tcmalloc assumes that all allocated pointers use at
786 // most kAddressBits bits. If ptr doesn't, then it definitely
787 // wasn't alloacted by tcmalloc.
788 if ((p >> (kAddressBits - kPageShift)) > 0) {
789 return kNotOwned;
790 }
791 size_t cl = Static::pageheap()->GetSizeClassIfCached(p);
792 if (cl != 0) {
793 return kOwned;
794 }
795 const Span *span = Static::pageheap()->GetDescriptor(p);
796 return span ? kOwned : kNotOwned;
797 }
870 798
871 virtual void GetFreeListSizes(vector<MallocExtension::FreeListInfo>* v) { 799 virtual void GetFreeListSizes(vector<MallocExtension::FreeListInfo>* v) {
872 static const char* kCentralCacheType = "tcmalloc.central"; 800 static const char* kCentralCacheType = "tcmalloc.central";
873 static const char* kTransferCacheType = "tcmalloc.transfer"; 801 static const char* kTransferCacheType = "tcmalloc.transfer";
874 static const char* kThreadCacheType = "tcmalloc.thread"; 802 static const char* kThreadCacheType = "tcmalloc.thread";
875 static const char* kPageHeapType = "tcmalloc.page"; 803 static const char* kPageHeapType = "tcmalloc.page";
876 static const char* kPageHeapUnmappedType = "tcmalloc.page_unmapped"; 804 static const char* kPageHeapUnmappedType = "tcmalloc.page_unmapped";
877 static const char* kLargeSpanType = "tcmalloc.large"; 805 static const char* kLargeSpanType = "tcmalloc.large";
878 static const char* kLargeUnmappedSpanType = "tcmalloc.large_unmapped"; 806 static const char* kLargeUnmappedSpanType = "tcmalloc.large_unmapped";
879 807
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
914 MallocExtension::FreeListInfo i; 842 MallocExtension::FreeListInfo i;
915 i.min_object_size = prev_class_size + 1; 843 i.min_object_size = prev_class_size + 1;
916 i.max_object_size = Static::sizemap()->ByteSizeForClass(cl); 844 i.max_object_size = Static::sizemap()->ByteSizeForClass(cl);
917 i.total_bytes_free = 845 i.total_bytes_free =
918 class_count[cl] * Static::sizemap()->ByteSizeForClass(cl); 846 class_count[cl] * Static::sizemap()->ByteSizeForClass(cl);
919 i.type = kThreadCacheType; 847 i.type = kThreadCacheType;
920 v->push_back(i); 848 v->push_back(i);
921 } 849 }
922 850
923 // append page heap info 851 // append page heap info
924 int64 page_count_normal[kMaxPages]; 852 PageHeap::SmallSpanStats small;
925 int64 page_count_returned[kMaxPages]; 853 PageHeap::LargeSpanStats large;
926 int64 span_count_normal;
927 int64 span_count_returned;
928 { 854 {
929 SpinLockHolder h(Static::pageheap_lock()); 855 SpinLockHolder h(Static::pageheap_lock());
930 Static::pageheap()->GetClassSizes(page_count_normal, 856 Static::pageheap()->GetSmallSpanStats(&small);
931 page_count_returned, 857 Static::pageheap()->GetLargeSpanStats(&large);
932 &span_count_normal,
933 &span_count_returned);
934 } 858 }
935 859
936 // spans: mapped 860 // large spans: mapped
937 MallocExtension::FreeListInfo span_info; 861 MallocExtension::FreeListInfo span_info;
938 span_info.type = kLargeSpanType; 862 span_info.type = kLargeSpanType;
939 span_info.max_object_size = (numeric_limits<size_t>::max)(); 863 span_info.max_object_size = (numeric_limits<size_t>::max)();
940 span_info.min_object_size = kMaxPages << kPageShift; 864 span_info.min_object_size = kMaxPages << kPageShift;
941 span_info.total_bytes_free = span_count_normal << kPageShift; 865 span_info.total_bytes_free = large.normal_pages << kPageShift;
942 v->push_back(span_info); 866 v->push_back(span_info);
943 867
944 // spans: unmapped 868 // large spans: unmapped
945 span_info.type = kLargeUnmappedSpanType; 869 span_info.type = kLargeUnmappedSpanType;
946 span_info.total_bytes_free = span_count_returned << kPageShift; 870 span_info.total_bytes_free = large.returned_pages << kPageShift;
947 v->push_back(span_info); 871 v->push_back(span_info);
948 872
873 // small spans
949 for (int s = 1; s < kMaxPages; s++) { 874 for (int s = 1; s < kMaxPages; s++) {
950 MallocExtension::FreeListInfo i; 875 MallocExtension::FreeListInfo i;
951 i.max_object_size = (s << kPageShift); 876 i.max_object_size = (s << kPageShift);
952 i.min_object_size = ((s - 1) << kPageShift); 877 i.min_object_size = ((s - 1) << kPageShift);
953 878
954 i.type = kPageHeapType; 879 i.type = kPageHeapType;
955 i.total_bytes_free = (s << kPageShift) * page_count_normal[s]; 880 i.total_bytes_free = (s << kPageShift) * small.normal_length[s];
956 v->push_back(i); 881 v->push_back(i);
957 882
958 i.type = kPageHeapUnmappedType; 883 i.type = kPageHeapUnmappedType;
959 i.total_bytes_free = (s << kPageShift) * page_count_returned[s]; 884 i.total_bytes_free = (s << kPageShift) * small.returned_length[s];
960 v->push_back(i); 885 v->push_back(i);
961 } 886 }
962 } 887 }
963 }; 888 };
964 889
965 // The constructor allocates an object to ensure that initialization 890 // The constructor allocates an object to ensure that initialization
966 // runs before main(), and therefore we do not have a chance to become 891 // runs before main(), and therefore we do not have a chance to become
967 // multi-threaded before initialization. We also create the TSD key 892 // multi-threaded before initialization. We also create the TSD key
968 // here. Presumably by the time this constructor runs, glibc is in 893 // here. Presumably by the time this constructor runs, glibc is in
969 // good enough shape to handle pthread_key_create(). 894 // good enough shape to handle pthread_key_create().
970 // 895 //
971 // The constructor also takes the opportunity to tell STL to use 896 // The constructor also takes the opportunity to tell STL to use
972 // tcmalloc. We want to do this early, before construct time, so 897 // tcmalloc. We want to do this early, before construct time, so
973 // all user STL allocations go through tcmalloc (which works really 898 // all user STL allocations go through tcmalloc (which works really
974 // well for STL). 899 // well for STL).
975 // 900 //
976 // The destructor prints stats when the program exits. 901 // The destructor prints stats when the program exits.
977 static int tcmallocguard_refcount = 0; // no lock needed: runs before main() 902 static int tcmallocguard_refcount = 0; // no lock needed: runs before main()
978 TCMallocGuard::TCMallocGuard() { 903 TCMallocGuard::TCMallocGuard() {
979 if (tcmallocguard_refcount++ == 0) { 904 if (tcmallocguard_refcount++ == 0) {
980 #ifdef HAVE_TLS // this is true if the cc/ld/libc combo support TLS 905 #ifdef HAVE_TLS // this is true if the cc/ld/libc combo support TLS
981 // Check whether the kernel also supports TLS (needs to happen at runtime) 906 // Check whether the kernel also supports TLS (needs to happen at runtime)
982 tcmalloc::CheckIfKernelSupportsTLS(); 907 tcmalloc::CheckIfKernelSupportsTLS();
983 #endif 908 #endif
984 #ifdef WIN32_DO_PATCHING 909 ReplaceSystemAlloc(); // defined in libc_override_*.h
985 // patch the windows VirtualAlloc, etc.
986 PatchWindowsFunctions(); // defined in windows/patch_functions.cc
987 #endif
988 tc_free(tc_malloc(1)); 910 tc_free(tc_malloc(1));
989 ThreadCache::InitTSD(); 911 ThreadCache::InitTSD();
990 tc_free(tc_malloc(1)); 912 tc_free(tc_malloc(1));
991 // Either we, or debugallocation.cc, or valgrind will control memory 913 // Either we, or debugallocation.cc, or valgrind will control memory
992 // management. We register our extension if we're the winner. 914 // management. We register our extension if we're the winner.
993 #ifdef TCMALLOC_USING_DEBUGALLOCATION 915 #ifdef TCMALLOC_USING_DEBUGALLOCATION
994 // Let debugallocation register its extension. 916 // Let debugallocation register its extension.
995 #else 917 #else
996 if (RunningOnValgrind()) { 918 if (RunningOnValgrind()) {
997 // Let Valgrind uses its own malloc (so don't register our extension). 919 // Let Valgrind uses its own malloc (so don't register our extension).
(...skipping 76 matching lines...) Expand 10 before | Expand all | Expand 10 after
1074 (kPageSize > FLAGS_tcmalloc_large_alloc_report_threshold 996 (kPageSize > FLAGS_tcmalloc_large_alloc_report_threshold
1075 ? kPageSize : FLAGS_tcmalloc_large_alloc_report_threshold); 997 ? kPageSize : FLAGS_tcmalloc_large_alloc_report_threshold);
1076 998
1077 static void ReportLargeAlloc(Length num_pages, void* result) { 999 static void ReportLargeAlloc(Length num_pages, void* result) {
1078 StackTrace stack; 1000 StackTrace stack;
1079 stack.depth = GetStackTrace(stack.stack, tcmalloc::kMaxStackDepth, 1); 1001 stack.depth = GetStackTrace(stack.stack, tcmalloc::kMaxStackDepth, 1);
1080 1002
1081 static const int N = 1000; 1003 static const int N = 1000;
1082 char buffer[N]; 1004 char buffer[N];
1083 TCMalloc_Printer printer(buffer, N); 1005 TCMalloc_Printer printer(buffer, N);
1084 printer.printf("tcmalloc: large alloc %llu bytes == %p @ ", 1006 printer.printf("tcmalloc: large alloc %"PRIu64" bytes == %p @ ",
1085 static_cast<unsigned long long>(num_pages) << kPageShift, 1007 static_cast<uint64>(num_pages) << kPageShift,
1086 result); 1008 result);
1087 for (int i = 0; i < stack.depth; i++) { 1009 for (int i = 0; i < stack.depth; i++) {
1088 printer.printf(" %p", stack.stack[i]); 1010 printer.printf(" %p", stack.stack[i]);
1089 } 1011 }
1090 printer.printf("\n"); 1012 printer.printf("\n");
1091 write(STDERR_FILENO, buffer, strlen(buffer)); 1013 write(STDERR_FILENO, buffer, strlen(buffer));
1092 } 1014 }
1093 1015
1094 inline void* cpp_alloc(size_t size, bool nothrow); 1016 inline void* cpp_alloc(size_t size, bool nothrow);
1095 inline void* do_malloc(size_t size); 1017 inline void* do_malloc(size_t size);
(...skipping 93 matching lines...) Expand 10 before | Expand all | Expand 10 after
1189 1111
1190 static inline ThreadCache* GetCacheIfPresent() { 1112 static inline ThreadCache* GetCacheIfPresent() {
1191 void* const p = ThreadCache::GetCacheIfPresent(); 1113 void* const p = ThreadCache::GetCacheIfPresent();
1192 return reinterpret_cast<ThreadCache*>(p); 1114 return reinterpret_cast<ThreadCache*>(p);
1193 } 1115 }
1194 1116
1195 // This lets you call back to a given function pointer if ptr is invalid. 1117 // This lets you call back to a given function pointer if ptr is invalid.
1196 // It is used primarily by windows code which wants a specialized callback. 1118 // It is used primarily by windows code which wants a specialized callback.
1197 inline void do_free_with_callback(void* ptr, void (*invalid_free_fn)(void*)) { 1119 inline void do_free_with_callback(void* ptr, void (*invalid_free_fn)(void*)) {
1198 if (ptr == NULL) return; 1120 if (ptr == NULL) return;
1199 ASSERT(Static::pageheap() != NULL); // Should not call free() before malloc() 1121 if (Static::pageheap() == NULL) {
1122 // We called free() before malloc(). This can occur if the
1123 // (system) malloc() is called before tcmalloc is loaded, and then
1124 // free() is called after tcmalloc is loaded (and tc_free has
1125 // replaced free), but before the global constructor has run that
1126 // sets up the tcmalloc data structures.
1127 (*invalid_free_fn)(ptr); // Decide how to handle the bad free request
1128 return;
1129 }
1200 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift; 1130 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
1201 Span* span = NULL; 1131 Span* span = NULL;
1202 size_t cl = Static::pageheap()->GetSizeClassIfCached(p); 1132 size_t cl = Static::pageheap()->GetSizeClassIfCached(p);
1203 1133
1204 if (cl == 0) { 1134 if (cl == 0) {
1205 span = Static::pageheap()->GetDescriptor(p); 1135 span = Static::pageheap()->GetDescriptor(p);
1206 if (!span) { 1136 if (!span) {
1207 // span can be NULL because the pointer passed in is invalid 1137 // span can be NULL because the pointer passed in is invalid
1208 // (not something returned by malloc or friends), or because the 1138 // (not something returned by malloc or friends), or because the
1209 // pointer was allocated with some other allocator besides 1139 // pointer was allocated with some other allocator besides
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
1242 } 1172 }
1243 Static::pageheap()->Delete(span); 1173 Static::pageheap()->Delete(span);
1244 } 1174 }
1245 } 1175 }
1246 1176
1247 // The default "do_free" that uses the default callback. 1177 // The default "do_free" that uses the default callback.
1248 inline void do_free(void* ptr) { 1178 inline void do_free(void* ptr) {
1249 return do_free_with_callback(ptr, &InvalidFree); 1179 return do_free_with_callback(ptr, &InvalidFree);
1250 } 1180 }
1251 1181
1252 inline size_t GetSizeWithCallback(void* ptr, 1182 // NOTE: some logic here is duplicated in GetOwnership (above), for
1253 size_t (*invalid_getsize_fn)(void*)) { 1183 // speed. If you change this function, look at that one too.
1184 inline size_t GetSizeWithCallback(const void* ptr,
1185 size_t (*invalid_getsize_fn)(const void*)) {
1254 if (ptr == NULL) 1186 if (ptr == NULL)
1255 return 0; 1187 return 0;
1256 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift; 1188 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
1257 size_t cl = Static::pageheap()->GetSizeClassIfCached(p); 1189 size_t cl = Static::pageheap()->GetSizeClassIfCached(p);
1258 if (cl != 0) { 1190 if (cl != 0) {
1259 return Static::sizemap()->ByteSizeForClass(cl); 1191 return Static::sizemap()->ByteSizeForClass(cl);
1260 } else { 1192 } else {
1261 Span *span = Static::pageheap()->GetDescriptor(p); 1193 const Span *span = Static::pageheap()->GetDescriptor(p);
1262 if (span == NULL) { // means we do not own this memory 1194 if (span == NULL) { // means we do not own this memory
1263 return (*invalid_getsize_fn)(ptr); 1195 return (*invalid_getsize_fn)(ptr);
1264 } else if (span->sizeclass != 0) { 1196 } else if (span->sizeclass != 0) {
1265 Static::pageheap()->CacheSizeClass(p, span->sizeclass); 1197 Static::pageheap()->CacheSizeClass(p, span->sizeclass);
1266 return Static::sizemap()->ByteSizeForClass(span->sizeclass); 1198 return Static::sizemap()->ByteSizeForClass(span->sizeclass);
1267 } else { 1199 } else {
1268 return span->length << kPageShift; 1200 return span->length << kPageShift;
1269 } 1201 }
1270 } 1202 }
1271 } 1203 }
1272 1204
1273 // This lets you call back to a given function pointer if ptr is invalid. 1205 // This lets you call back to a given function pointer if ptr is invalid.
1274 // It is used primarily by windows code which wants a specialized callback. 1206 // It is used primarily by windows code which wants a specialized callback.
1275 inline void* do_realloc_with_callback( 1207 inline void* do_realloc_with_callback(
1276 void* old_ptr, size_t new_size, 1208 void* old_ptr, size_t new_size,
1277 void (*invalid_free_fn)(void*), 1209 void (*invalid_free_fn)(void*),
1278 size_t (*invalid_get_size_fn)(void*)) { 1210 size_t (*invalid_get_size_fn)(const void*)) {
1279 AddRoomForMark(&new_size); 1211 AddRoomForMark(&new_size);
1280 // Get the size of the old entry 1212 // Get the size of the old entry
1281 const size_t old_size = GetSizeWithCallback(old_ptr, invalid_get_size_fn); 1213 const size_t old_size = GetSizeWithCallback(old_ptr, invalid_get_size_fn);
1282 1214
1283 // Reallocate if the new size is larger than the old size, 1215 // Reallocate if the new size is larger than the old size,
1284 // or if the new size is significantly smaller than the old size. 1216 // or if the new size is significantly smaller than the old size.
1285 // We do hysteresis to avoid resizing ping-pongs: 1217 // We do hysteresis to avoid resizing ping-pongs:
1286 // . If we need to grow, grow to max(new_size, old_size * 1.X) 1218 // . If we need to grow, grow to max(new_size, old_size * 1.X)
1287 // . Don't shrink unless new_size < old_size * 0.Y 1219 // . Don't shrink unless new_size < old_size * 0.Y
1288 // X and Y trade-off time for wasted space. For now we do 1.25 and 0.5. 1220 // X and Y trade-off time for wasted space. For now we do 1.25 and 0.5.
(...skipping 125 matching lines...) Expand 10 before | Expand all | Expand 10 after
1414 PrintStats(1); 1346 PrintStats(1);
1415 } 1347 }
1416 1348
1417 inline int do_mallopt(int cmd, int value) { 1349 inline int do_mallopt(int cmd, int value) {
1418 return 1; // Indicates error 1350 return 1; // Indicates error
1419 } 1351 }
1420 1352
1421 #ifdef HAVE_STRUCT_MALLINFO 1353 #ifdef HAVE_STRUCT_MALLINFO
1422 inline struct mallinfo do_mallinfo() { 1354 inline struct mallinfo do_mallinfo() {
1423 TCMallocStats stats; 1355 TCMallocStats stats;
1424 ExtractStats(&stats, NULL); 1356 ExtractStats(&stats, NULL, NULL, NULL);
1425 1357
1426 // Just some of the fields are filled in. 1358 // Just some of the fields are filled in.
1427 struct mallinfo info; 1359 struct mallinfo info;
1428 memset(&info, 0, sizeof(info)); 1360 memset(&info, 0, sizeof(info));
1429 1361
1430 // Unfortunately, the struct contains "int" field, so some of the 1362 // Unfortunately, the struct contains "int" field, so some of the
1431 // size values will be truncated. 1363 // size values will be truncated.
1432 info.arena = static_cast<int>(stats.pageheap.system_bytes); 1364 info.arena = static_cast<int>(stats.pageheap.system_bytes);
1433 info.fsmblks = static_cast<int>(stats.thread_bytes 1365 info.fsmblks = static_cast<int>(stats.thread_bytes
1434 + stats.central_bytes 1366 + stats.central_bytes
(...skipping 103 matching lines...) Expand 10 before | Expand all | Expand 10 after
1538 } else { // allocation success 1470 } else { // allocation success
1539 return p; 1471 return p;
1540 } 1472 }
1541 #endif // PREANSINEW 1473 #endif // PREANSINEW
1542 } 1474 }
1543 } 1475 }
1544 1476
1545 } // end unnamed namespace 1477 } // end unnamed namespace
1546 1478
1547 // As promised, the definition of this function, declared above. 1479 // As promised, the definition of this function, declared above.
1548 size_t TCMallocImplementation::GetAllocatedSize(void* ptr) { 1480 size_t TCMallocImplementation::GetAllocatedSize(const void* ptr) {
1481 ASSERT(TCMallocImplementation::GetOwnership(ptr)
1482 != TCMallocImplementation::kNotOwned);
1549 return ExcludeSpaceForMark( 1483 return ExcludeSpaceForMark(
1550 GetSizeWithCallback(ptr, &InvalidGetAllocatedSize)); 1484 GetSizeWithCallback(ptr, &InvalidGetAllocatedSize));
1551 } 1485 }
1552 1486
1553 void TCMallocImplementation::MarkThreadBusy() { 1487 void TCMallocImplementation::MarkThreadBusy() {
1554 // Allocate to force the creation of a thread cache, but avoid 1488 // Allocate to force the creation of a thread cache, but avoid
1555 // invoking any hooks. 1489 // invoking any hooks.
1556 do_free(do_malloc(0)); 1490 do_free(do_malloc(0));
1557 } 1491 }
1558 1492
(...skipping 178 matching lines...) Expand 10 before | Expand all | Expand 10 after
1737 return do_mallopt(cmd, value); 1671 return do_mallopt(cmd, value);
1738 } 1672 }
1739 1673
1740 #ifdef HAVE_STRUCT_MALLINFO 1674 #ifdef HAVE_STRUCT_MALLINFO
1741 extern "C" PERFTOOLS_DLL_DECL struct mallinfo tc_mallinfo(void) __THROW { 1675 extern "C" PERFTOOLS_DLL_DECL struct mallinfo tc_mallinfo(void) __THROW {
1742 return do_mallinfo(); 1676 return do_mallinfo();
1743 } 1677 }
1744 #endif 1678 #endif
1745 1679
1746 extern "C" PERFTOOLS_DLL_DECL size_t tc_malloc_size(void* ptr) __THROW { 1680 extern "C" PERFTOOLS_DLL_DECL size_t tc_malloc_size(void* ptr) __THROW {
1747 return GetSizeWithCallback(ptr, &InvalidGetAllocatedSize); 1681 return MallocExtension::instance()->GetAllocatedSize(ptr);
1748 } 1682 }
1749 1683
1750
1751 // Override __libc_memalign in libc on linux boxes specially.
1752 // They have a bug in libc that causes them to (very rarely) allocate
1753 // with __libc_memalign() yet deallocate with free() and the
1754 // definitions above don't catch it.
1755 // This function is an exception to the rule of calling MallocHook method
1756 // from the stack frame of the allocation function;
1757 // heap-checker handles this special case explicitly.
1758 static void *MemalignOverride(size_t align, size_t size, const void *caller)
1759 __THROW ATTRIBUTE_SECTION(google_malloc);
1760
1761 static void *MemalignOverride(size_t align, size_t size, const void *caller)
1762 __THROW {
1763 void* result = do_memalign_or_cpp_memalign(align, size);
1764 MallocHook::InvokeNewHook(result, size);
1765 return result;
1766 }
1767 void *(*__MALLOC_HOOK_VOLATILE __memalign_hook)(size_t, size_t, const void *) = MemalignOverride;
1768 #endif // TCMALLOC_USING_DEBUGALLOCATION 1684 #endif // TCMALLOC_USING_DEBUGALLOCATION
1769 1685
1770 // ---Double free() debugging implementation ----------------------------------- 1686 // ---Double free() debugging implementation -----------------------------------
1771 // We will put a mark at the extreme end of each allocation block. We make 1687 // We will put a mark at the extreme end of each allocation block. We make
1772 // sure that we always allocate enough "extra memory" that we can fit in the 1688 // sure that we always allocate enough "extra memory" that we can fit in the
1773 // mark, and still provide the requested usable region. If ever that mark is 1689 // mark, and still provide the requested usable region. If ever that mark is
1774 // not as expected, then we know that the user is corrupting memory beyond their 1690 // not as expected, then we know that the user is corrupting memory beyond their
1775 // request size, or that they have called free a second time without having 1691 // request size, or that they have called free a second time without having
1776 // the memory allocated (again). This allows us to spot most double free()s, 1692 // the memory allocated (again). This allows us to spot most double free()s,
1777 // but some can "slip by" or confuse our logic if the caller reallocates memory 1693 // but some can "slip by" or confuse our logic if the caller reallocates memory
(...skipping 30 matching lines...) Expand all
1808 static void ValidateAllocatedRegion(void* ptr, size_t cl) {} 1724 static void ValidateAllocatedRegion(void* ptr, size_t cl) {}
1809 1725
1810 #else // TCMALLOC_VALIDATION 1726 #else // TCMALLOC_VALIDATION
1811 1727
1812 static void DieFromDoubleFree() { 1728 static void DieFromDoubleFree() {
1813 char* p = NULL; 1729 char* p = NULL;
1814 p++; 1730 p++;
1815 *p += 1; // Segv. 1731 *p += 1; // Segv.
1816 } 1732 }
1817 1733
1818 static size_t DieFromBadFreePointer(void* unused) { 1734 static size_t DieFromBadFreePointer(const void* unused) {
1819 char* p = NULL; 1735 char* p = NULL;
1820 p += 2; 1736 p += 2;
1821 *p += 2; // Segv. 1737 *p += 2; // Segv.
1822 return 0; 1738 return 0;
1823 } 1739 }
1824 1740
1825 static void DieFromMemoryCorruption() { 1741 static void DieFromMemoryCorruption() {
1826 char* p = NULL; 1742 char* p = NULL;
1827 p += 3; 1743 p += 3;
1828 *p += 3; // Segv. 1744 *p += 3; // Segv.
(...skipping 99 matching lines...) Expand 10 before | Expand all | Expand 10 after
1928 *mark = ~allocated_mark; // Distinctively not allocated. 1844 *mark = ~allocated_mark; // Distinctively not allocated.
1929 } 1845 }
1930 1846
1931 static void MarkAllocatedRegion(void* ptr) { 1847 static void MarkAllocatedRegion(void* ptr) {
1932 if (ptr == NULL) return; 1848 if (ptr == NULL) return;
1933 MarkType* mark = GetMarkLocation(ptr); 1849 MarkType* mark = GetMarkLocation(ptr);
1934 *mark = GetMarkValue(ptr, mark); 1850 *mark = GetMarkValue(ptr, mark);
1935 } 1851 }
1936 1852
1937 #endif // TCMALLOC_VALIDATION 1853 #endif // TCMALLOC_VALIDATION
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698