1 // Copyright (c) 2005, 2007, Google Inc.
2 // All rights reserved.
3 // Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
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
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.
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.
32 // Author: Sanjay Ghemawat <opensource@google.com>
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.)
37 // See doc/tcmalloc.html for a high-level
38 // description of how this malloc works.
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.
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_.
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.
68 // TODO: Bias reclamation to larger addresses
69 // TODO: implement mallinfo/mallopt
70 // TODO: Better testing
72 // 9/28/2003 (new page-level allocator replaces ptmalloc2):
73 // * malloc/free of small objects goes from ~300 ns to ~50 ns.
74 // * allocation of a reasonably complicated struct
75 // goes from about 1100 ns to about 300 ns.
78 #include "FastMalloc.h"
80 #include "Assertions.h"
82 #if ENABLE(JSC_MULTIPLE_THREADS)
85 #if USE(PTHREAD_GETSPECIFIC_DIRECT)
86 #include <System/pthread_machdep.h>
89 #ifndef NO_TCMALLOC_SAMPLES
91 #define NO_TCMALLOC_SAMPLES
95 #if !(defined(USE_SYSTEM_MALLOC) && USE_SYSTEM_MALLOC) && defined(NDEBUG)
96 #define FORCE_SYSTEM_MALLOC 0
98 #define FORCE_SYSTEM_MALLOC 1
101 // Use a background thread to periodically scavenge memory to release back to the system
102 // https://bugs.webkit.org/show_bug.cgi?id=27900: don't turn this on for Tiger until we have figured out why it caused a crash.
103 #define USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY 0
108 #if ENABLE(JSC_MULTIPLE_THREADS)
109 static pthread_key_t isForbiddenKey
;
110 static pthread_once_t isForbiddenKeyOnce
= PTHREAD_ONCE_INIT
;
111 static void initializeIsForbiddenKey()
113 pthread_key_create(&isForbiddenKey
, 0);
117 static bool isForbidden()
119 pthread_once(&isForbiddenKeyOnce
, initializeIsForbiddenKey
);
120 return !!pthread_getspecific(isForbiddenKey
);
124 void fastMallocForbid()
126 pthread_once(&isForbiddenKeyOnce
, initializeIsForbiddenKey
);
127 pthread_setspecific(isForbiddenKey
, &isForbiddenKey
);
130 void fastMallocAllow()
132 pthread_once(&isForbiddenKeyOnce
, initializeIsForbiddenKey
);
133 pthread_setspecific(isForbiddenKey
, 0);
138 static bool staticIsForbidden
;
139 static bool isForbidden()
141 return staticIsForbidden
;
144 void fastMallocForbid()
146 staticIsForbidden
= true;
149 void fastMallocAllow()
151 staticIsForbidden
= false;
153 #endif // ENABLE(JSC_MULTIPLE_THREADS)
162 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
166 void fastMallocMatchFailed(void*)
171 } // namespace Internal
175 void* fastZeroedMalloc(size_t n
)
177 void* result
= fastMalloc(n
);
178 memset(result
, 0, n
);
182 char* fastStrDup(const char* src
)
184 int len
= strlen(src
) + 1;
185 char* dup
= static_cast<char*>(fastMalloc(len
));
188 memcpy(dup
, src
, len
);
193 TryMallocReturnValue
tryFastZeroedMalloc(size_t n
)
196 if (!tryFastMalloc(n
).getValue(result
))
198 memset(result
, 0, n
);
204 #if FORCE_SYSTEM_MALLOC
207 #include "brew/SystemMallocBrew.h"
211 #include <malloc/malloc.h>
218 TryMallocReturnValue
tryFastMalloc(size_t n
)
220 ASSERT(!isForbidden());
222 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
223 if (std::numeric_limits
<size_t>::max() - sizeof(AllocAlignmentInteger
) <= n
) // If overflow would occur...
226 void* result
= malloc(n
+ sizeof(AllocAlignmentInteger
));
230 *static_cast<AllocAlignmentInteger
*>(result
) = Internal::AllocTypeMalloc
;
231 result
= static_cast<AllocAlignmentInteger
*>(result
) + 1;
239 void* fastMalloc(size_t n
)
241 ASSERT(!isForbidden());
243 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
244 TryMallocReturnValue returnValue
= tryFastMalloc(n
);
246 returnValue
.getValue(result
);
248 void* result
= malloc(n
);
253 // The behavior of malloc(0) is implementation defined.
254 // To make sure that fastMalloc never returns 0, retry with fastMalloc(1).
256 return fastMalloc(1);
264 TryMallocReturnValue
tryFastCalloc(size_t n_elements
, size_t element_size
)
266 ASSERT(!isForbidden());
268 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
269 size_t totalBytes
= n_elements
* element_size
;
270 if (n_elements
> 1 && element_size
&& (totalBytes
/ element_size
) != n_elements
|| (std::numeric_limits
<size_t>::max() - sizeof(AllocAlignmentInteger
) <= totalBytes
))
273 totalBytes
+= sizeof(AllocAlignmentInteger
);
274 void* result
= malloc(totalBytes
);
278 memset(result
, 0, totalBytes
);
279 *static_cast<AllocAlignmentInteger
*>(result
) = Internal::AllocTypeMalloc
;
280 result
= static_cast<AllocAlignmentInteger
*>(result
) + 1;
283 return calloc(n_elements
, element_size
);
287 void* fastCalloc(size_t n_elements
, size_t element_size
)
289 ASSERT(!isForbidden());
291 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
292 TryMallocReturnValue returnValue
= tryFastCalloc(n_elements
, element_size
);
294 returnValue
.getValue(result
);
296 void* result
= calloc(n_elements
, element_size
);
301 // If either n_elements or element_size is 0, the behavior of calloc is implementation defined.
302 // To make sure that fastCalloc never returns 0, retry with fastCalloc(1, 1).
303 if (!n_elements
|| !element_size
)
304 return fastCalloc(1, 1);
312 void fastFree(void* p
)
314 ASSERT(!isForbidden());
316 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
320 AllocAlignmentInteger
* header
= Internal::fastMallocMatchValidationValue(p
);
321 if (*header
!= Internal::AllocTypeMalloc
)
322 Internal::fastMallocMatchFailed(p
);
329 TryMallocReturnValue
tryFastRealloc(void* p
, size_t n
)
331 ASSERT(!isForbidden());
333 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
335 if (std::numeric_limits
<size_t>::max() - sizeof(AllocAlignmentInteger
) <= n
) // If overflow would occur...
337 AllocAlignmentInteger
* header
= Internal::fastMallocMatchValidationValue(p
);
338 if (*header
!= Internal::AllocTypeMalloc
)
339 Internal::fastMallocMatchFailed(p
);
340 void* result
= realloc(header
, n
+ sizeof(AllocAlignmentInteger
));
344 // This should not be needed because the value is already there:
345 // *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
346 result
= static_cast<AllocAlignmentInteger
*>(result
) + 1;
349 return fastMalloc(n
);
352 return realloc(p
, n
);
356 void* fastRealloc(void* p
, size_t n
)
358 ASSERT(!isForbidden());
360 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
361 TryMallocReturnValue returnValue
= tryFastRealloc(p
, n
);
363 returnValue
.getValue(result
);
365 void* result
= realloc(p
, n
);
373 void releaseFastMallocFreeMemory() { }
375 FastMallocStatistics
fastMallocStatistics()
377 FastMallocStatistics statistics
= { 0, 0, 0 };
381 size_t fastMallocSize(const void* p
)
384 return malloc_size(p
);
386 return _msize(const_cast<void*>(p
));
395 // This symbol is present in the JavaScriptCore exports file even when FastMalloc is disabled.
396 // It will never be used in this case, so it's type and value are less interesting than its presence.
397 extern "C" const int jscore_fastmalloc_introspection
= 0;
400 #else // FORCE_SYSTEM_MALLOC
404 #elif HAVE(INTTYPES_H)
405 #include <inttypes.h>
407 #include <sys/types.h>
410 #include "AlwaysInline.h"
411 #include "Assertions.h"
412 #include "TCPackedCache.h"
413 #include "TCPageMap.h"
414 #include "TCSpinLock.h"
415 #include "TCSystemAlloc.h"
427 #ifndef WIN32_LEAN_AND_MEAN
428 #define WIN32_LEAN_AND_MEAN
436 #include "MallocZoneSupport.h"
437 #include <wtf/HashSet.h>
438 #include <wtf/Vector.h>
441 #include <dispatch/dispatch.h>
449 // Calling pthread_getspecific through a global function pointer is faster than a normal
450 // call to the function on Mac OS X, and it's used in performance-critical code. So we
451 // use a function pointer. But that's not necessarily faster on other platforms, and we had
452 // problems with this technique on Windows, so we'll do this only on Mac OS X.
453 #if USE(PTHREAD_GETSPECIFIC_DIRECT)
454 #define pthread_getspecific(key) _pthread_getspecific_direct(key)
455 #define pthread_setspecific(key, val) _pthread_setspecific_direct(key, (val))
458 static void* (*pthread_getspecific_function_pointer
)(pthread_key_t
) = pthread_getspecific
;
459 #define pthread_getspecific(key) pthread_getspecific_function_pointer(key)
463 #define DEFINE_VARIABLE(type, name, value, meaning) \
464 namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead { \
465 type FLAGS_##name(value); \
466 char FLAGS_no##name; \
468 using FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead::FLAGS_##name
470 #define DEFINE_int64(name, value, meaning) \
471 DEFINE_VARIABLE(int64_t, name, value, meaning)
473 #define DEFINE_double(name, value, meaning) \
474 DEFINE_VARIABLE(double, name, value, meaning)
478 #define malloc fastMalloc
479 #define calloc fastCalloc
480 #define free fastFree
481 #define realloc fastRealloc
483 #define MESSAGE LOG_ERROR
484 #define CHECK_CONDITION ASSERT
488 class TCMalloc_Central_FreeListPadded
;
489 class TCMalloc_PageHeap
;
490 class TCMalloc_ThreadCache
;
491 template <typename T
> class PageHeapAllocator
;
493 class FastMallocZone
{
497 static kern_return_t
enumerate(task_t
, void*, unsigned typeMmask
, vm_address_t zoneAddress
, memory_reader_t
, vm_range_recorder_t
);
498 static size_t goodSize(malloc_zone_t
*, size_t size
) { return size
; }
499 static boolean_t
check(malloc_zone_t
*) { return true; }
500 static void print(malloc_zone_t
*, boolean_t
) { }
501 static void log(malloc_zone_t
*, void*) { }
502 static void forceLock(malloc_zone_t
*) { }
503 static void forceUnlock(malloc_zone_t
*) { }
504 static void statistics(malloc_zone_t
*, malloc_statistics_t
* stats
) { memset(stats
, 0, sizeof(malloc_statistics_t
)); }
507 FastMallocZone(TCMalloc_PageHeap
*, TCMalloc_ThreadCache
**, TCMalloc_Central_FreeListPadded
*, PageHeapAllocator
<Span
>*, PageHeapAllocator
<TCMalloc_ThreadCache
>*);
508 static size_t size(malloc_zone_t
*, const void*);
509 static void* zoneMalloc(malloc_zone_t
*, size_t);
510 static void* zoneCalloc(malloc_zone_t
*, size_t numItems
, size_t size
);
511 static void zoneFree(malloc_zone_t
*, void*);
512 static void* zoneRealloc(malloc_zone_t
*, void*, size_t);
513 static void* zoneValloc(malloc_zone_t
*, size_t) { LOG_ERROR("valloc is not supported"); return 0; }
514 static void zoneDestroy(malloc_zone_t
*) { }
516 malloc_zone_t m_zone
;
517 TCMalloc_PageHeap
* m_pageHeap
;
518 TCMalloc_ThreadCache
** m_threadHeaps
;
519 TCMalloc_Central_FreeListPadded
* m_centralCaches
;
520 PageHeapAllocator
<Span
>* m_spanAllocator
;
521 PageHeapAllocator
<TCMalloc_ThreadCache
>* m_pageHeapAllocator
;
529 // This #ifdef should almost never be set. Set NO_TCMALLOC_SAMPLES if
530 // you're porting to a system where you really can't get a stacktrace.
531 #ifdef NO_TCMALLOC_SAMPLES
532 // We use #define so code compiles even if you #include stacktrace.h somehow.
533 # define GetStackTrace(stack, depth, skip) (0)
535 # include <google/stacktrace.h>
539 // Even if we have support for thread-local storage in the compiler
540 // and linker, the OS may not support it. We need to check that at
541 // runtime. Right now, we have to keep a manual set of "bad" OSes.
542 #if defined(HAVE_TLS)
543 static bool kernel_supports_tls
= false; // be conservative
544 static inline bool KernelSupportsTLS() {
545 return kernel_supports_tls
;
547 # if !HAVE_DECL_UNAME // if too old for uname, probably too old for TLS
548 static void CheckIfKernelSupportsTLS() {
549 kernel_supports_tls
= false;
552 # include <sys/utsname.h> // DECL_UNAME checked for <sys/utsname.h> too
553 static void CheckIfKernelSupportsTLS() {
555 if (uname(&buf
) != 0) { // should be impossible
556 MESSAGE("uname failed assuming no TLS support (errno=%d)\n", errno
);
557 kernel_supports_tls
= false;
558 } else if (strcasecmp(buf
.sysname
, "linux") == 0) {
559 // The linux case: the first kernel to support TLS was 2.6.0
560 if (buf
.release
[0] < '2' && buf
.release
[1] == '.') // 0.x or 1.x
561 kernel_supports_tls
= false;
562 else if (buf
.release
[0] == '2' && buf
.release
[1] == '.' &&
563 buf
.release
[2] >= '0' && buf
.release
[2] < '6' &&
564 buf
.release
[3] == '.') // 2.0 - 2.5
565 kernel_supports_tls
= false;
567 kernel_supports_tls
= true;
568 } else { // some other kernel, we'll be optimisitic
569 kernel_supports_tls
= true;
571 // TODO(csilvers): VLOG(1) the tls status once we support RAW_VLOG
573 # endif // HAVE_DECL_UNAME
576 // __THROW is defined in glibc systems. It means, counter-intuitively,
577 // "This function will never throw an exception." It's an optional
578 // optimization tool, but we may need to use it to match glibc prototypes.
579 #ifndef __THROW // I guess we're not on a glibc system
580 # define __THROW // __THROW is just an optimization, so ok to make it ""
583 //-------------------------------------------------------------------
585 //-------------------------------------------------------------------
587 // Not all possible combinations of the following parameters make
588 // sense. In particular, if kMaxSize increases, you may have to
589 // increase kNumClasses as well.
590 static const size_t kPageShift
= 12;
591 static const size_t kPageSize
= 1 << kPageShift
;
592 static const size_t kMaxSize
= 8u * kPageSize
;
593 static const size_t kAlignShift
= 3;
594 static const size_t kAlignment
= 1 << kAlignShift
;
595 static const size_t kNumClasses
= 68;
597 // Allocates a big block of memory for the pagemap once we reach more than
599 static const size_t kPageMapBigAllocationThreshold
= 128 << 20;
601 // Minimum number of pages to fetch from system at a time. Must be
602 // significantly bigger than kPageSize to amortize system-call
603 // overhead, and also to reduce external fragementation. Also, we
604 // should keep this value big because various incarnations of Linux
605 // have small limits on the number of mmap() regions per
607 static const size_t kMinSystemAlloc
= 1 << (20 - kPageShift
);
609 // Number of objects to move between a per-thread list and a central
610 // list in one shot. We want this to be not too small so we can
611 // amortize the lock overhead for accessing the central list. Making
612 // it too big may temporarily cause unnecessary memory wastage in the
613 // per-thread free list until the scavenger cleans up the list.
614 static int num_objects_to_move
[kNumClasses
];
616 // Maximum length we allow a per-thread free-list to have before we
617 // move objects from it into the corresponding central free-list. We
618 // want this big to avoid locking the central free-list too often. It
619 // should not hurt to make this list somewhat big because the
620 // scavenging code will shrink it down when its contents are not in use.
621 static const int kMaxFreeListLength
= 256;
623 // Lower and upper bounds on the per-thread cache sizes
624 static const size_t kMinThreadCacheSize
= kMaxSize
* 2;
625 static const size_t kMaxThreadCacheSize
= 512 * 1024;
627 // Default bound on the total amount of thread caches
628 static const size_t kDefaultOverallThreadCacheSize
= 16 << 20;
630 // For all span-lengths < kMaxPages we keep an exact-size list.
631 // REQUIRED: kMaxPages >= kMinSystemAlloc;
632 static const size_t kMaxPages
= kMinSystemAlloc
;
634 /* The smallest prime > 2^n */
635 static int primes_list
[] = {
636 // Small values might cause high rates of sampling
637 // and hence commented out.
638 // 2, 5, 11, 17, 37, 67, 131, 257,
639 // 521, 1031, 2053, 4099, 8209, 16411,
640 32771, 65537, 131101, 262147, 524309, 1048583,
641 2097169, 4194319, 8388617, 16777259, 33554467 };
643 // Twice the approximate gap between sampling actions.
644 // I.e., we take one sample approximately once every
645 // tcmalloc_sample_parameter/2
646 // bytes of allocation, i.e., ~ once every 128KB.
647 // Must be a prime number.
648 #ifdef NO_TCMALLOC_SAMPLES
649 DEFINE_int64(tcmalloc_sample_parameter
, 0,
650 "Unused: code is compiled with NO_TCMALLOC_SAMPLES");
651 static size_t sample_period
= 0;
653 DEFINE_int64(tcmalloc_sample_parameter
, 262147,
654 "Twice the approximate gap between sampling actions."
655 " Must be a prime number. Otherwise will be rounded up to a "
656 " larger prime number");
657 static size_t sample_period
= 262147;
660 // Protects sample_period above
661 static SpinLock sample_period_lock
= SPINLOCK_INITIALIZER
;
663 // Parameters for controlling how fast memory is returned to the OS.
665 DEFINE_double(tcmalloc_release_rate
, 1,
666 "Rate at which we release unused memory to the system. "
667 "Zero means we never release memory back to the system. "
668 "Increase this flag to return memory faster; decrease it "
669 "to return memory slower. Reasonable rates are in the "
672 //-------------------------------------------------------------------
673 // Mapping from size to size_class and vice versa
674 //-------------------------------------------------------------------
676 // Sizes <= 1024 have an alignment >= 8. So for such sizes we have an
677 // array indexed by ceil(size/8). Sizes > 1024 have an alignment >= 128.
678 // So for these larger sizes we have an array indexed by ceil(size/128).
680 // We flatten both logical arrays into one physical array and use
681 // arithmetic to compute an appropriate index. The constants used by
682 // ClassIndex() were selected to make the flattening work.
685 // Size Expression Index
686 // -------------------------------------------------------
690 // 1024 (1024 + 7) / 8 128
691 // 1025 (1025 + 127 + (120<<7)) / 128 129
693 // 32768 (32768 + 127 + (120<<7)) / 128 376
694 static const size_t kMaxSmallSize
= 1024;
695 static const int shift_amount
[2] = { 3, 7 }; // For divides by 8 or 128
696 static const int add_amount
[2] = { 7, 127 + (120 << 7) };
697 static unsigned char class_array
[377];
699 // Compute index of the class_array[] entry for a given size
700 static inline int ClassIndex(size_t s
) {
701 const int i
= (s
> kMaxSmallSize
);
702 return static_cast<int>((s
+ add_amount
[i
]) >> shift_amount
[i
]);
705 // Mapping from size class to max size storable in that class
706 static size_t class_to_size
[kNumClasses
];
708 // Mapping from size class to number of pages to allocate at a time
709 static size_t class_to_pages
[kNumClasses
];
711 // TransferCache is used to cache transfers of num_objects_to_move[size_class]
712 // back and forth between thread caches and the central cache for a given size
715 void *head
; // Head of chain of objects.
716 void *tail
; // Tail of chain of objects.
718 // A central cache freelist can have anywhere from 0 to kNumTransferEntries
719 // slots to put link list chains into. To keep memory usage bounded the total
720 // number of TCEntries across size classes is fixed. Currently each size
721 // class is initially given one TCEntry which also means that the maximum any
722 // one class can have is kNumClasses.
723 static const int kNumTransferEntries
= kNumClasses
;
725 // Note: the following only works for "n"s that fit in 32-bits, but
726 // that is fine since we only use it for small sizes.
727 static inline int LgFloor(size_t n
) {
729 for (int i
= 4; i
>= 0; --i
) {
730 int shift
= (1 << i
);
731 size_t x
= n
>> shift
;
741 // Some very basic linked list functions for dealing with using void * as
744 static inline void *SLL_Next(void *t
) {
745 return *(reinterpret_cast<void**>(t
));
748 static inline void SLL_SetNext(void *t
, void *n
) {
749 *(reinterpret_cast<void**>(t
)) = n
;
752 static inline void SLL_Push(void **list
, void *element
) {
753 SLL_SetNext(element
, *list
);
757 static inline void *SLL_Pop(void **list
) {
758 void *result
= *list
;
759 *list
= SLL_Next(*list
);
764 // Remove N elements from a linked list to which head points. head will be
765 // modified to point to the new head. start and end will point to the first
766 // and last nodes of the range. Note that end will point to NULL after this
767 // function is called.
768 static inline void SLL_PopRange(void **head
, int N
, void **start
, void **end
) {
776 for (int i
= 1; i
< N
; ++i
) {
782 *head
= SLL_Next(tmp
);
783 // Unlink range from list.
784 SLL_SetNext(tmp
, NULL
);
787 static inline void SLL_PushRange(void **head
, void *start
, void *end
) {
789 SLL_SetNext(end
, *head
);
793 static inline size_t SLL_Size(void *head
) {
797 head
= SLL_Next(head
);
802 // Setup helper functions.
804 static ALWAYS_INLINE
size_t SizeClass(size_t size
) {
805 return class_array
[ClassIndex(size
)];
808 // Get the byte-size for a specified class
809 static ALWAYS_INLINE
size_t ByteSizeForClass(size_t cl
) {
810 return class_to_size
[cl
];
812 static int NumMoveSize(size_t size
) {
813 if (size
== 0) return 0;
814 // Use approx 64k transfers between thread and central caches.
815 int num
= static_cast<int>(64.0 * 1024.0 / size
);
816 if (num
< 2) num
= 2;
817 // Clamp well below kMaxFreeListLength to avoid ping pong between central
818 // and thread caches.
819 if (num
> static_cast<int>(0.8 * kMaxFreeListLength
))
820 num
= static_cast<int>(0.8 * kMaxFreeListLength
);
822 // Also, avoid bringing in too many objects into small object free
823 // lists. There are lots of such lists, and if we allow each one to
824 // fetch too many at a time, we end up having to scavenge too often
825 // (especially when there are lots of threads and each thread gets a
826 // small allowance for its thread cache).
828 // TODO: Make thread cache free list sizes dynamic so that we do not
829 // have to equally divide a fixed resource amongst lots of threads.
830 if (num
> 32) num
= 32;
835 // Initialize the mapping arrays
836 static void InitSizeClasses() {
837 // Do some sanity checking on add_amount[]/shift_amount[]/class_array[]
838 if (ClassIndex(0) < 0) {
839 MESSAGE("Invalid class index %d for size 0\n", ClassIndex(0));
842 if (static_cast<size_t>(ClassIndex(kMaxSize
)) >= sizeof(class_array
)) {
843 MESSAGE("Invalid class index %d for kMaxSize\n", ClassIndex(kMaxSize
));
847 // Compute the size classes we want to use
848 size_t sc
= 1; // Next size class to assign
849 unsigned char alignshift
= kAlignShift
;
851 for (size_t size
= kAlignment
; size
<= kMaxSize
; size
+= (1 << alignshift
)) {
852 int lg
= LgFloor(size
);
854 // Increase alignment every so often.
856 // Since we double the alignment every time size doubles and
857 // size >= 128, this means that space wasted due to alignment is
858 // at most 16/128 i.e., 12.5%. Plus we cap the alignment at 256
859 // bytes, so the space wasted as a percentage starts falling for
861 if ((lg
>= 7) && (alignshift
< 8)) {
867 // Allocate enough pages so leftover is less than 1/8 of total.
868 // This bounds wasted space to at most 12.5%.
869 size_t psize
= kPageSize
;
870 while ((psize
% size
) > (psize
>> 3)) {
873 const size_t my_pages
= psize
>> kPageShift
;
875 if (sc
> 1 && my_pages
== class_to_pages
[sc
-1]) {
876 // See if we can merge this into the previous class without
877 // increasing the fragmentation of the previous class.
878 const size_t my_objects
= (my_pages
<< kPageShift
) / size
;
879 const size_t prev_objects
= (class_to_pages
[sc
-1] << kPageShift
)
880 / class_to_size
[sc
-1];
881 if (my_objects
== prev_objects
) {
882 // Adjust last class to include this size
883 class_to_size
[sc
-1] = size
;
889 class_to_pages
[sc
] = my_pages
;
890 class_to_size
[sc
] = size
;
893 if (sc
!= kNumClasses
) {
894 MESSAGE("wrong number of size classes: found %" PRIuS
" instead of %d\n",
895 sc
, int(kNumClasses
));
899 // Initialize the mapping arrays
901 for (unsigned char c
= 1; c
< kNumClasses
; c
++) {
902 const size_t max_size_in_class
= class_to_size
[c
];
903 for (size_t s
= next_size
; s
<= max_size_in_class
; s
+= kAlignment
) {
904 class_array
[ClassIndex(s
)] = c
;
906 next_size
= static_cast<int>(max_size_in_class
+ kAlignment
);
909 // Double-check sizes just to be safe
910 for (size_t size
= 0; size
<= kMaxSize
; size
++) {
911 const size_t sc
= SizeClass(size
);
913 MESSAGE("Bad size class %" PRIuS
" for %" PRIuS
"\n", sc
, size
);
916 if (sc
> 1 && size
<= class_to_size
[sc
-1]) {
917 MESSAGE("Allocating unnecessarily large class %" PRIuS
" for %" PRIuS
921 if (sc
>= kNumClasses
) {
922 MESSAGE("Bad size class %" PRIuS
" for %" PRIuS
"\n", sc
, size
);
925 const size_t s
= class_to_size
[sc
];
927 MESSAGE("Bad size %" PRIuS
" for %" PRIuS
" (sc = %" PRIuS
")\n", s
, size
, sc
);
931 MESSAGE("Bad size %" PRIuS
" for %" PRIuS
" (sc = %" PRIuS
")\n", s
, size
, sc
);
936 // Initialize the num_objects_to_move array.
937 for (size_t cl
= 1; cl
< kNumClasses
; ++cl
) {
938 num_objects_to_move
[cl
] = NumMoveSize(ByteSizeForClass(cl
));
943 // Dump class sizes and maximum external wastage per size class
944 for (size_t cl
= 1; cl
< kNumClasses
; ++cl
) {
945 const int alloc_size
= class_to_pages
[cl
] << kPageShift
;
946 const int alloc_objs
= alloc_size
/ class_to_size
[cl
];
947 const int min_used
= (class_to_size
[cl
-1] + 1) * alloc_objs
;
948 const int max_waste
= alloc_size
- min_used
;
949 MESSAGE("SC %3d [ %8d .. %8d ] from %8d ; %2.0f%% maxwaste\n",
951 int(class_to_size
[cl
-1] + 1),
952 int(class_to_size
[cl
]),
953 int(class_to_pages
[cl
] << kPageShift
),
954 max_waste
* 100.0 / alloc_size
961 // -------------------------------------------------------------------------
962 // Simple allocator for objects of a specified type. External locking
963 // is required before accessing one of these objects.
964 // -------------------------------------------------------------------------
966 // Metadata allocator -- keeps stats about how many bytes allocated
967 static uint64_t metadata_system_bytes
= 0;
968 static void* MetaDataAlloc(size_t bytes
) {
969 void* result
= TCMalloc_SystemAlloc(bytes
, 0);
970 if (result
!= NULL
) {
971 metadata_system_bytes
+= bytes
;
977 class PageHeapAllocator
{
979 // How much to allocate from system at a time
980 static const size_t kAllocIncrement
= 32 << 10;
983 static const size_t kAlignedSize
984 = (((sizeof(T
) + kAlignment
- 1) / kAlignment
) * kAlignment
);
986 // Free area from which to carve new objects
990 // Linked list of all regions allocated by this allocator
991 void* allocated_regions_
;
993 // Free list of already carved objects
996 // Number of allocated but unfreed objects
1001 ASSERT(kAlignedSize
<= kAllocIncrement
);
1003 allocated_regions_
= 0;
1010 // Consult free list
1012 if (free_list_
!= NULL
) {
1013 result
= free_list_
;
1014 free_list_
= *(reinterpret_cast<void**>(result
));
1016 if (free_avail_
< kAlignedSize
) {
1018 char* new_allocation
= reinterpret_cast<char*>(MetaDataAlloc(kAllocIncrement
));
1019 if (!new_allocation
)
1022 *(void**)new_allocation
= allocated_regions_
;
1023 allocated_regions_
= new_allocation
;
1024 free_area_
= new_allocation
+ kAlignedSize
;
1025 free_avail_
= kAllocIncrement
- kAlignedSize
;
1027 result
= free_area_
;
1028 free_area_
+= kAlignedSize
;
1029 free_avail_
-= kAlignedSize
;
1032 return reinterpret_cast<T
*>(result
);
1036 *(reinterpret_cast<void**>(p
)) = free_list_
;
1041 int inuse() const { return inuse_
; }
1043 #if defined(WTF_CHANGES) && OS(DARWIN)
1044 template <class Recorder
>
1045 void recordAdministrativeRegions(Recorder
& recorder
, const RemoteMemoryReader
& reader
)
1047 vm_address_t adminAllocation
= reinterpret_cast<vm_address_t
>(allocated_regions_
);
1048 while (adminAllocation
) {
1049 recorder
.recordRegion(adminAllocation
, kAllocIncrement
);
1050 adminAllocation
= *reader(reinterpret_cast<vm_address_t
*>(adminAllocation
));
1056 // -------------------------------------------------------------------------
1057 // Span - a contiguous run of pages
1058 // -------------------------------------------------------------------------
1060 // Type that can hold a page number
1061 typedef uintptr_t PageID
;
1063 // Type that can hold the length of a run of pages
1064 typedef uintptr_t Length
;
1066 static const Length kMaxValidPages
= (~static_cast<Length
>(0)) >> kPageShift
;
1068 // Convert byte size into pages. This won't overflow, but may return
1069 // an unreasonably large value if bytes is huge enough.
1070 static inline Length
pages(size_t bytes
) {
1071 return (bytes
>> kPageShift
) +
1072 ((bytes
& (kPageSize
- 1)) > 0 ? 1 : 0);
1075 // Convert a user size into the number of bytes that will actually be
1077 static size_t AllocationSize(size_t bytes
) {
1078 if (bytes
> kMaxSize
) {
1079 // Large object: we allocate an integral number of pages
1080 ASSERT(bytes
<= (kMaxValidPages
<< kPageShift
));
1081 return pages(bytes
) << kPageShift
;
1083 // Small object: find the size class to which it belongs
1084 return ByteSizeForClass(SizeClass(bytes
));
1088 // Information kept for a span (a contiguous run of pages).
1090 PageID start
; // Starting page number
1091 Length length
; // Number of pages in span
1092 Span
* next
; // Used when in link list
1093 Span
* prev
; // Used when in link list
1094 void* objects
; // Linked list of free objects
1095 unsigned int free
: 1; // Is the span free
1096 #ifndef NO_TCMALLOC_SAMPLES
1097 unsigned int sample
: 1; // Sampled object?
1099 unsigned int sizeclass
: 8; // Size-class for small objects (or 0)
1100 unsigned int refcount
: 11; // Number of non-free objects
1101 bool decommitted
: 1;
1105 // For debugging, we can keep a log events per span
1112 #define ASSERT_SPAN_COMMITTED(span) ASSERT(!span->decommitted)
1115 void Event(Span
* span
, char op
, int v
= 0) {
1116 span
->history
[span
->nexthistory
] = op
;
1117 span
->value
[span
->nexthistory
] = v
;
1118 span
->nexthistory
++;
1119 if (span
->nexthistory
== sizeof(span
->history
)) span
->nexthistory
= 0;
1122 #define Event(s,o,v) ((void) 0)
1125 // Allocator/deallocator for spans
1126 static PageHeapAllocator
<Span
> span_allocator
;
1127 static Span
* NewSpan(PageID p
, Length len
) {
1128 Span
* result
= span_allocator
.New();
1129 memset(result
, 0, sizeof(*result
));
1131 result
->length
= len
;
1133 result
->nexthistory
= 0;
1138 static inline void DeleteSpan(Span
* span
) {
1140 // In debug mode, trash the contents of deleted Spans
1141 memset(span
, 0x3f, sizeof(*span
));
1143 span_allocator
.Delete(span
);
1146 // -------------------------------------------------------------------------
1147 // Doubly linked list of spans.
1148 // -------------------------------------------------------------------------
1150 static inline void DLL_Init(Span
* list
) {
1155 static inline void DLL_Remove(Span
* span
) {
1156 span
->prev
->next
= span
->next
;
1157 span
->next
->prev
= span
->prev
;
1162 static ALWAYS_INLINE
bool DLL_IsEmpty(const Span
* list
) {
1163 return list
->next
== list
;
1166 static int DLL_Length(const Span
* list
) {
1168 for (Span
* s
= list
->next
; s
!= list
; s
= s
->next
) {
1174 #if 0 /* Not needed at the moment -- causes compiler warnings if not used */
1175 static void DLL_Print(const char* label
, const Span
* list
) {
1176 MESSAGE("%-10s %p:", label
, list
);
1177 for (const Span
* s
= list
->next
; s
!= list
; s
= s
->next
) {
1178 MESSAGE(" <%p,%u,%u>", s
, s
->start
, s
->length
);
1184 static inline void DLL_Prepend(Span
* list
, Span
* span
) {
1185 ASSERT(span
->next
== NULL
);
1186 ASSERT(span
->prev
== NULL
);
1187 span
->next
= list
->next
;
1189 list
->next
->prev
= span
;
1193 // -------------------------------------------------------------------------
1194 // Stack traces kept for sampled allocations
1195 // The following state is protected by pageheap_lock_.
1196 // -------------------------------------------------------------------------
1198 // size/depth are made the same size as a pointer so that some generic
1199 // code below can conveniently cast them back and forth to void*.
1200 static const int kMaxStackDepth
= 31;
1202 uintptr_t size
; // Size of object
1203 uintptr_t depth
; // Number of PC values stored in array below
1204 void* stack
[kMaxStackDepth
];
1206 static PageHeapAllocator
<StackTrace
> stacktrace_allocator
;
1207 static Span sampled_objects
;
1209 // -------------------------------------------------------------------------
1210 // Map from page-id to per-page data
1211 // -------------------------------------------------------------------------
1213 // We use PageMap2<> for 32-bit and PageMap3<> for 64-bit machines.
1214 // We also use a simple one-level cache for hot PageID-to-sizeclass mappings,
1215 // because sometimes the sizeclass is all the information we need.
1217 // Selector class -- general selector uses 3-level map
1218 template <int BITS
> class MapSelector
{
1220 typedef TCMalloc_PageMap3
<BITS
-kPageShift
> Type
;
1221 typedef PackedCache
<BITS
, uint64_t> CacheType
;
1224 #if defined(WTF_CHANGES)
1226 // On all known X86-64 platforms, the upper 16 bits are always unused and therefore
1227 // can be excluded from the PageMap key.
1228 // See http://en.wikipedia.org/wiki/X86-64#Virtual_address_space_details
1230 static const size_t kBitsUnusedOn64Bit
= 16;
1232 static const size_t kBitsUnusedOn64Bit
= 0;
1235 // A three-level map for 64-bit machines
1236 template <> class MapSelector
<64> {
1238 typedef TCMalloc_PageMap3
<64 - kPageShift
- kBitsUnusedOn64Bit
> Type
;
1239 typedef PackedCache
<64, uint64_t> CacheType
;
1243 // A two-level map for 32-bit machines
1244 template <> class MapSelector
<32> {
1246 typedef TCMalloc_PageMap2
<32 - kPageShift
> Type
;
1247 typedef PackedCache
<32 - kPageShift
, uint16_t> CacheType
;
1250 // -------------------------------------------------------------------------
1251 // Page-level allocator
1252 // * Eager coalescing
1254 // Heap for page-level allocation. We allow allocating and freeing a
1255 // contiguous runs of pages (called a "span").
1256 // -------------------------------------------------------------------------
1258 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1259 // The page heap maintains a free list for spans that are no longer in use by
1260 // the central cache or any thread caches. We use a background thread to
1261 // periodically scan the free list and release a percentage of it back to the OS.
1263 // If free_committed_pages_ exceeds kMinimumFreeCommittedPageCount, the
1264 // background thread:
1266 // - pauses for kScavengeDelayInSeconds
1267 // - returns to the OS a percentage of the memory that remained unused during
1268 // that pause (kScavengePercentage * min_free_committed_pages_since_last_scavenge_)
1269 // The goal of this strategy is to reduce memory pressure in a timely fashion
1270 // while avoiding thrashing the OS allocator.
1272 // Time delay before the page heap scavenger will consider returning pages to
1274 static const int kScavengeDelayInSeconds
= 2;
1276 // Approximate percentage of free committed pages to return to the OS in one
1278 static const float kScavengePercentage
= .5f
;
1280 // number of span lists to keep spans in when memory is returned.
1281 static const int kMinSpanListsWithSpans
= 32;
1283 // Number of free committed pages that we want to keep around. The minimum number of pages used when there
1284 // is 1 span in each of the first kMinSpanListsWithSpans spanlists. Currently 528 pages.
1285 static const size_t kMinimumFreeCommittedPageCount
= kMinSpanListsWithSpans
* ((1.0f
+kMinSpanListsWithSpans
) / 2.0f
);
1289 class TCMalloc_PageHeap
{
1293 // Allocate a run of "n" pages. Returns zero if out of memory.
1294 Span
* New(Length n
);
1296 // Delete the span "[p, p+n-1]".
1297 // REQUIRES: span was returned by earlier call to New() and
1298 // has not yet been deleted.
1299 void Delete(Span
* span
);
1301 // Mark an allocated span as being used for small objects of the
1302 // specified size-class.
1303 // REQUIRES: span was returned by an earlier call to New()
1304 // and has not yet been deleted.
1305 void RegisterSizeClass(Span
* span
, size_t sc
);
1307 // Split an allocated span into two spans: one of length "n" pages
1308 // followed by another span of length "span->length - n" pages.
1309 // Modifies "*span" to point to the first span of length "n" pages.
1310 // Returns a pointer to the second span.
1312 // REQUIRES: "0 < n < span->length"
1313 // REQUIRES: !span->free
1314 // REQUIRES: span->sizeclass == 0
1315 Span
* Split(Span
* span
, Length n
);
1317 // Return the descriptor for the specified page.
1318 inline Span
* GetDescriptor(PageID p
) const {
1319 return reinterpret_cast<Span
*>(pagemap_
.get(p
));
1323 inline Span
* GetDescriptorEnsureSafe(PageID p
)
1325 pagemap_
.Ensure(p
, 1);
1326 return GetDescriptor(p
);
1329 size_t ReturnedBytes() const;
1332 // Dump state to stderr
1334 void Dump(TCMalloc_Printer
* out
);
1337 // Return number of bytes allocated from system
1338 inline uint64_t SystemBytes() const { return system_bytes_
; }
1340 // Return number of free bytes in heap
1341 uint64_t FreeBytes() const {
1342 return (static_cast<uint64_t>(free_pages_
) << kPageShift
);
1346 bool CheckList(Span
* list
, Length min_pages
, Length max_pages
);
1348 // Release all pages on the free list for reuse by the OS:
1349 void ReleaseFreePages();
1351 // Return 0 if we have no information, or else the correct sizeclass for p.
1352 // Reads and writes to pagemap_cache_ do not require locking.
1353 // The entries are 64 bits on 64-bit hardware and 16 bits on
1354 // 32-bit hardware, and we don't mind raciness as long as each read of
1355 // an entry yields a valid entry, not a partially updated entry.
1356 size_t GetSizeClassIfCached(PageID p
) const {
1357 return pagemap_cache_
.GetOrDefault(p
, 0);
1359 void CacheSizeClass(PageID p
, size_t cl
) const { pagemap_cache_
.Put(p
, cl
); }
1362 // Pick the appropriate map and cache types based on pointer size
1363 typedef MapSelector
<8*sizeof(uintptr_t)>::Type PageMap
;
1364 typedef MapSelector
<8*sizeof(uintptr_t)>::CacheType PageMapCache
;
1366 mutable PageMapCache pagemap_cache_
;
1368 // We segregate spans of a given size into two circular linked
1369 // lists: one for normal spans, and one for spans whose memory
1370 // has been returned to the system.
1376 // List of free spans of length >= kMaxPages
1379 // Array mapping from span length to a doubly linked list of free spans
1380 SpanList free_
[kMaxPages
];
1382 // Number of pages kept in free lists
1383 uintptr_t free_pages_
;
1385 // Bytes allocated from system
1386 uint64_t system_bytes_
;
1388 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1389 // Number of pages kept in free lists that are still committed.
1390 Length free_committed_pages_
;
1392 // Minimum number of free committed pages since last scavenge. (Can be 0 if
1393 // we've committed new pages since the last scavenge.)
1394 Length min_free_committed_pages_since_last_scavenge_
;
1397 bool GrowHeap(Length n
);
1399 // REQUIRES span->length >= n
1400 // Remove span from its free list, and move any leftover part of
1401 // span into appropriate free lists. Also update "span" to have
1402 // length exactly "n" and mark it as non-free so it can be returned
1405 // "released" is true iff "span" was found on a "returned" list.
1406 void Carve(Span
* span
, Length n
, bool released
);
1408 void RecordSpan(Span
* span
) {
1409 pagemap_
.set(span
->start
, span
);
1410 if (span
->length
> 1) {
1411 pagemap_
.set(span
->start
+ span
->length
- 1, span
);
1415 // Allocate a large span of length == n. If successful, returns a
1416 // span of exactly the specified length. Else, returns NULL.
1417 Span
* AllocLarge(Length n
);
1419 #if !USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1420 // Incrementally release some memory to the system.
1421 // IncrementalScavenge(n) is called whenever n pages are freed.
1422 void IncrementalScavenge(Length n
);
1425 // Number of pages to deallocate before doing more scavenging
1426 int64_t scavenge_counter_
;
1428 // Index of last free list we scavenged
1429 size_t scavenge_index_
;
1431 #if defined(WTF_CHANGES) && OS(DARWIN)
1432 friend class FastMallocZone
;
1435 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1436 void initializeScavenger();
1437 ALWAYS_INLINE
void signalScavenger();
1439 ALWAYS_INLINE
bool shouldScavenge() const;
1441 #if !HAVE(DISPATCH_H)
1442 static NO_RETURN_WITH_VALUE
void* runScavengerThread(void*);
1443 NO_RETURN
void scavengerThread();
1445 // Keeps track of whether the background thread is actively scavenging memory every kScavengeDelayInSeconds, or
1446 // it's blocked waiting for more pages to be deleted.
1447 bool m_scavengeThreadActive
;
1449 pthread_mutex_t m_scavengeMutex
;
1450 pthread_cond_t m_scavengeCondition
;
1451 #else // !HAVE(DISPATCH_H)
1452 void periodicScavenge();
1454 dispatch_queue_t m_scavengeQueue
;
1455 dispatch_source_t m_scavengeTimer
;
1456 bool m_scavengingScheduled
;
1459 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1462 void TCMalloc_PageHeap::init()
1464 pagemap_
.init(MetaDataAlloc
);
1465 pagemap_cache_
= PageMapCache(0);
1469 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1470 free_committed_pages_
= 0;
1471 min_free_committed_pages_since_last_scavenge_
= 0;
1472 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1474 scavenge_counter_
= 0;
1475 // Start scavenging at kMaxPages list
1476 scavenge_index_
= kMaxPages
-1;
1477 COMPILE_ASSERT(kNumClasses
<= (1 << PageMapCache::kValuebits
), valuebits
);
1478 DLL_Init(&large_
.normal
);
1479 DLL_Init(&large_
.returned
);
1480 for (size_t i
= 0; i
< kMaxPages
; i
++) {
1481 DLL_Init(&free_
[i
].normal
);
1482 DLL_Init(&free_
[i
].returned
);
1485 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1486 initializeScavenger();
1487 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1490 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1492 #if !HAVE(DISPATCH_H)
1494 void TCMalloc_PageHeap::initializeScavenger()
1496 pthread_mutex_init(&m_scavengeMutex
, 0);
1497 pthread_cond_init(&m_scavengeCondition
, 0);
1498 m_scavengeThreadActive
= true;
1500 pthread_create(&thread
, 0, runScavengerThread
, this);
1503 void* TCMalloc_PageHeap::runScavengerThread(void* context
)
1505 static_cast<TCMalloc_PageHeap
*>(context
)->scavengerThread();
1507 // Without this, Visual Studio will complain that this method does not return a value.
1512 ALWAYS_INLINE
void TCMalloc_PageHeap::signalScavenger()
1514 if (!m_scavengeThreadActive
&& shouldScavenge())
1515 pthread_cond_signal(&m_scavengeCondition
);
1518 #else // !HAVE(DISPATCH_H)
1520 void TCMalloc_PageHeap::initializeScavenger()
1522 m_scavengeQueue
= dispatch_queue_create("com.apple.JavaScriptCore.FastMallocSavenger", NULL
);
1523 m_scavengeTimer
= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER
, 0, 0, m_scavengeQueue
);
1524 dispatch_time_t startTime
= dispatch_time(DISPATCH_TIME_NOW
, kScavengeDelayInSeconds
* NSEC_PER_SEC
);
1525 dispatch_source_set_timer(m_scavengeTimer
, startTime
, kScavengeDelayInSeconds
* NSEC_PER_SEC
, 1000 * NSEC_PER_USEC
);
1526 dispatch_source_set_event_handler(m_scavengeTimer
, ^{ periodicScavenge(); });
1527 m_scavengingScheduled
= false;
1530 ALWAYS_INLINE
void TCMalloc_PageHeap::signalScavenger()
1532 if (!m_scavengingScheduled
&& shouldScavenge()) {
1533 m_scavengingScheduled
= true;
1534 dispatch_resume(m_scavengeTimer
);
1540 void TCMalloc_PageHeap::scavenge()
1542 size_t pagesToRelease
= min_free_committed_pages_since_last_scavenge_
* kScavengePercentage
;
1543 size_t targetPageCount
= std::max
<size_t>(kMinimumFreeCommittedPageCount
, free_committed_pages_
- pagesToRelease
);
1545 while (free_committed_pages_
> targetPageCount
) {
1546 for (int i
= kMaxPages
; i
> 0 && free_committed_pages_
>= targetPageCount
; i
--) {
1547 SpanList
* slist
= (static_cast<size_t>(i
) == kMaxPages
) ? &large_
: &free_
[i
];
1548 // If the span size is bigger than kMinSpanListsWithSpans pages return all the spans in the list, else return all but 1 span.
1549 // Return only 50% of a spanlist at a time so spans of size 1 are not the only ones left.
1550 size_t numSpansToReturn
= (i
> kMinSpanListsWithSpans
) ? DLL_Length(&slist
->normal
) : static_cast<size_t>(.5 * DLL_Length(&slist
->normal
));
1551 for (int j
= 0; static_cast<size_t>(j
) < numSpansToReturn
&& !DLL_IsEmpty(&slist
->normal
) && free_committed_pages_
> targetPageCount
; j
++) {
1552 Span
* s
= slist
->normal
.prev
;
1554 ASSERT(!s
->decommitted
);
1555 if (!s
->decommitted
) {
1556 TCMalloc_SystemRelease(reinterpret_cast<void*>(s
->start
<< kPageShift
),
1557 static_cast<size_t>(s
->length
<< kPageShift
));
1558 ASSERT(free_committed_pages_
>= s
->length
);
1559 free_committed_pages_
-= s
->length
;
1560 s
->decommitted
= true;
1562 DLL_Prepend(&slist
->returned
, s
);
1567 min_free_committed_pages_since_last_scavenge_
= free_committed_pages_
;
1570 ALWAYS_INLINE
bool TCMalloc_PageHeap::shouldScavenge() const
1572 return free_committed_pages_
> kMinimumFreeCommittedPageCount
;
1575 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1577 inline Span
* TCMalloc_PageHeap::New(Length n
) {
1581 // Find first size >= n that has a non-empty list
1582 for (Length s
= n
; s
< kMaxPages
; s
++) {
1584 bool released
= false;
1585 if (!DLL_IsEmpty(&free_
[s
].normal
)) {
1586 // Found normal span
1587 ll
= &free_
[s
].normal
;
1588 } else if (!DLL_IsEmpty(&free_
[s
].returned
)) {
1589 // Found returned span; reallocate it
1590 ll
= &free_
[s
].returned
;
1593 // Keep looking in larger classes
1597 Span
* result
= ll
->next
;
1598 Carve(result
, n
, released
);
1599 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1600 // The newly allocated memory is from a span that's in the normal span list (already committed). Update the
1601 // free committed pages count.
1602 ASSERT(free_committed_pages_
>= n
);
1603 free_committed_pages_
-= n
;
1604 if (free_committed_pages_
< min_free_committed_pages_since_last_scavenge_
)
1605 min_free_committed_pages_since_last_scavenge_
= free_committed_pages_
;
1606 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1612 Span
* result
= AllocLarge(n
);
1613 if (result
!= NULL
) {
1614 ASSERT_SPAN_COMMITTED(result
);
1618 // Grow the heap and try again
1624 return AllocLarge(n
);
1627 Span
* TCMalloc_PageHeap::AllocLarge(Length n
) {
1628 // find the best span (closest to n in size).
1629 // The following loops implements address-ordered best-fit.
1630 bool from_released
= false;
1633 // Search through normal list
1634 for (Span
* span
= large_
.normal
.next
;
1635 span
!= &large_
.normal
;
1636 span
= span
->next
) {
1637 if (span
->length
>= n
) {
1639 || (span
->length
< best
->length
)
1640 || ((span
->length
== best
->length
) && (span
->start
< best
->start
))) {
1642 from_released
= false;
1647 // Search through released list in case it has a better fit
1648 for (Span
* span
= large_
.returned
.next
;
1649 span
!= &large_
.returned
;
1650 span
= span
->next
) {
1651 if (span
->length
>= n
) {
1653 || (span
->length
< best
->length
)
1654 || ((span
->length
== best
->length
) && (span
->start
< best
->start
))) {
1656 from_released
= true;
1662 Carve(best
, n
, from_released
);
1663 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1664 // The newly allocated memory is from a span that's in the normal span list (already committed). Update the
1665 // free committed pages count.
1666 ASSERT(free_committed_pages_
>= n
);
1667 free_committed_pages_
-= n
;
1668 if (free_committed_pages_
< min_free_committed_pages_since_last_scavenge_
)
1669 min_free_committed_pages_since_last_scavenge_
= free_committed_pages_
;
1670 #endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1678 Span
* TCMalloc_PageHeap::Split(Span
* span
, Length n
) {
1680 ASSERT(n
< span
->length
);
1681 ASSERT(!span
->free
);
1682 ASSERT(span
->sizeclass
== 0);
1683 Event(span
, 'T', n
);
1685 const Length extra
= span
->length
- n
;
1686 Span
* leftover
= NewSpan(span
->start
+ n
, extra
);
1687 Event(leftover
, 'U', extra
);
1688 RecordSpan(leftover
);
1689 pagemap_
.set(span
->start
+ n
- 1, span
); // Update map from pageid to span
1695 inline void TCMalloc_PageHeap::Carve(Span
* span
, Length n
, bool released
) {
1699 Event(span
, 'A', n
);
1702 // If the span chosen to carve from is decommited, commit the entire span at once to avoid committing spans 1 page at a time.
1703 ASSERT(span
->decommitted
);
1704 TCMalloc_SystemCommit(reinterpret_cast<void*>(span
->start
<< kPageShift
), static_cast<size_t>(span
->length
<< kPageShift
));
1705 span
->decommitted
= false;
1706 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1707 free_committed_pages_
+= span
->length
;
1711 const int extra
= static_cast<int>(span
->length
- n
);
1714 Span
* leftover
= NewSpan(span
->start
+ n
, extra
);
1716 leftover
->decommitted
= false;
1717 Event(leftover
, 'S', extra
);
1718 RecordSpan(leftover
);
1720 // Place leftover span on appropriate free list
1721 SpanList
* listpair
= (static_cast<size_t>(extra
) < kMaxPages
) ? &free_
[extra
] : &large_
;
1722 Span
* dst
= &listpair
->normal
;
1723 DLL_Prepend(dst
, leftover
);
1726 pagemap_
.set(span
->start
+ n
- 1, span
);
1730 static ALWAYS_INLINE
void mergeDecommittedStates(Span
* destination
, Span
* other
)
1732 if (destination
->decommitted
&& !other
->decommitted
) {
1733 TCMalloc_SystemRelease(reinterpret_cast<void*>(other
->start
<< kPageShift
),
1734 static_cast<size_t>(other
->length
<< kPageShift
));
1735 } else if (other
->decommitted
&& !destination
->decommitted
) {
1736 TCMalloc_SystemRelease(reinterpret_cast<void*>(destination
->start
<< kPageShift
),
1737 static_cast<size_t>(destination
->length
<< kPageShift
));
1738 destination
->decommitted
= true;
1742 inline void TCMalloc_PageHeap::Delete(Span
* span
) {
1744 ASSERT(!span
->free
);
1745 ASSERT(span
->length
> 0);
1746 ASSERT(GetDescriptor(span
->start
) == span
);
1747 ASSERT(GetDescriptor(span
->start
+ span
->length
- 1) == span
);
1748 span
->sizeclass
= 0;
1749 #ifndef NO_TCMALLOC_SAMPLES
1753 // Coalesce -- we guarantee that "p" != 0, so no bounds checking
1754 // necessary. We do not bother resetting the stale pagemap
1755 // entries for the pieces we are merging together because we only
1756 // care about the pagemap entries for the boundaries.
1757 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1758 // Track the total size of the neighboring free spans that are committed.
1759 Length neighboringCommittedSpansLength
= 0;
1761 const PageID p
= span
->start
;
1762 const Length n
= span
->length
;
1763 Span
* prev
= GetDescriptor(p
-1);
1764 if (prev
!= NULL
&& prev
->free
) {
1765 // Merge preceding span into this span
1766 ASSERT(prev
->start
+ prev
->length
== p
);
1767 const Length len
= prev
->length
;
1768 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1769 if (!prev
->decommitted
)
1770 neighboringCommittedSpansLength
+= len
;
1772 mergeDecommittedStates(span
, prev
);
1776 span
->length
+= len
;
1777 pagemap_
.set(span
->start
, span
);
1778 Event(span
, 'L', len
);
1780 Span
* next
= GetDescriptor(p
+n
);
1781 if (next
!= NULL
&& next
->free
) {
1782 // Merge next span into this span
1783 ASSERT(next
->start
== p
+n
);
1784 const Length len
= next
->length
;
1785 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1786 if (!next
->decommitted
)
1787 neighboringCommittedSpansLength
+= len
;
1789 mergeDecommittedStates(span
, next
);
1792 span
->length
+= len
;
1793 pagemap_
.set(span
->start
+ span
->length
- 1, span
);
1794 Event(span
, 'R', len
);
1797 Event(span
, 'D', span
->length
);
1799 if (span
->decommitted
) {
1800 if (span
->length
< kMaxPages
)
1801 DLL_Prepend(&free_
[span
->length
].returned
, span
);
1803 DLL_Prepend(&large_
.returned
, span
);
1805 if (span
->length
< kMaxPages
)
1806 DLL_Prepend(&free_
[span
->length
].normal
, span
);
1808 DLL_Prepend(&large_
.normal
, span
);
1812 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1813 if (span
->decommitted
) {
1814 // If the merged span is decommitted, that means we decommitted any neighboring spans that were
1815 // committed. Update the free committed pages count.
1816 free_committed_pages_
-= neighboringCommittedSpansLength
;
1817 if (free_committed_pages_
< min_free_committed_pages_since_last_scavenge_
)
1818 min_free_committed_pages_since_last_scavenge_
= free_committed_pages_
;
1820 // If the merged span remains committed, add the deleted span's size to the free committed pages count.
1821 free_committed_pages_
+= n
;
1824 // Make sure the scavenge thread becomes active if we have enough freed pages to release some back to the system.
1827 IncrementalScavenge(n
);
1833 #if !USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1834 void TCMalloc_PageHeap::IncrementalScavenge(Length n
) {
1835 // Fast path; not yet time to release memory
1836 scavenge_counter_
-= n
;
1837 if (scavenge_counter_
>= 0) return; // Not yet time to scavenge
1839 static const size_t kDefaultReleaseDelay
= 64;
1841 // Find index of free list to scavenge
1842 size_t index
= scavenge_index_
+ 1;
1843 for (size_t i
= 0; i
< kMaxPages
+1; i
++) {
1844 if (index
> kMaxPages
) index
= 0;
1845 SpanList
* slist
= (index
== kMaxPages
) ? &large_
: &free_
[index
];
1846 if (!DLL_IsEmpty(&slist
->normal
)) {
1847 // Release the last span on the normal portion of this list
1848 Span
* s
= slist
->normal
.prev
;
1850 TCMalloc_SystemRelease(reinterpret_cast<void*>(s
->start
<< kPageShift
),
1851 static_cast<size_t>(s
->length
<< kPageShift
));
1852 s
->decommitted
= true;
1853 DLL_Prepend(&slist
->returned
, s
);
1855 scavenge_counter_
= std::max
<size_t>(16UL, std::min
<size_t>(kDefaultReleaseDelay
, kDefaultReleaseDelay
- (free_pages_
/ kDefaultReleaseDelay
)));
1857 if (index
== kMaxPages
&& !DLL_IsEmpty(&slist
->normal
))
1858 scavenge_index_
= index
- 1;
1860 scavenge_index_
= index
;
1866 // Nothing to scavenge, delay for a while
1867 scavenge_counter_
= kDefaultReleaseDelay
;
1871 void TCMalloc_PageHeap::RegisterSizeClass(Span
* span
, size_t sc
) {
1872 // Associate span object with all interior pages as well
1873 ASSERT(!span
->free
);
1874 ASSERT(GetDescriptor(span
->start
) == span
);
1875 ASSERT(GetDescriptor(span
->start
+span
->length
-1) == span
);
1876 Event(span
, 'C', sc
);
1877 span
->sizeclass
= static_cast<unsigned int>(sc
);
1878 for (Length i
= 1; i
< span
->length
-1; i
++) {
1879 pagemap_
.set(span
->start
+i
, span
);
1884 size_t TCMalloc_PageHeap::ReturnedBytes() const {
1886 for (unsigned s
= 0; s
< kMaxPages
; s
++) {
1887 const int r_length
= DLL_Length(&free_
[s
].returned
);
1888 unsigned r_pages
= s
* r_length
;
1889 result
+= r_pages
<< kPageShift
;
1892 for (Span
* s
= large_
.returned
.next
; s
!= &large_
.returned
; s
= s
->next
)
1893 result
+= s
->length
<< kPageShift
;
1899 static double PagesToMB(uint64_t pages
) {
1900 return (pages
<< kPageShift
) / 1048576.0;
1903 void TCMalloc_PageHeap::Dump(TCMalloc_Printer
* out
) {
1904 int nonempty_sizes
= 0;
1905 for (int s
= 0; s
< kMaxPages
; s
++) {
1906 if (!DLL_IsEmpty(&free_
[s
].normal
) || !DLL_IsEmpty(&free_
[s
].returned
)) {
1910 out
->printf("------------------------------------------------\n");
1911 out
->printf("PageHeap: %d sizes; %6.1f MB free\n",
1912 nonempty_sizes
, PagesToMB(free_pages_
));
1913 out
->printf("------------------------------------------------\n");
1914 uint64_t total_normal
= 0;
1915 uint64_t total_returned
= 0;
1916 for (int s
= 0; s
< kMaxPages
; s
++) {
1917 const int n_length
= DLL_Length(&free_
[s
].normal
);
1918 const int r_length
= DLL_Length(&free_
[s
].returned
);
1919 if (n_length
+ r_length
> 0) {
1920 uint64_t n_pages
= s
* n_length
;
1921 uint64_t r_pages
= s
* r_length
;
1922 total_normal
+= n_pages
;
1923 total_returned
+= r_pages
;
1924 out
->printf("%6u pages * %6u spans ~ %6.1f MB; %6.1f MB cum"
1925 "; unmapped: %6.1f MB; %6.1f MB cum\n",
1927 (n_length
+ r_length
),
1928 PagesToMB(n_pages
+ r_pages
),
1929 PagesToMB(total_normal
+ total_returned
),
1931 PagesToMB(total_returned
));
1935 uint64_t n_pages
= 0;
1936 uint64_t r_pages
= 0;
1939 out
->printf("Normal large spans:\n");
1940 for (Span
* s
= large_
.normal
.next
; s
!= &large_
.normal
; s
= s
->next
) {
1941 out
->printf(" [ %6" PRIuS
" pages ] %6.1f MB\n",
1942 s
->length
, PagesToMB(s
->length
));
1943 n_pages
+= s
->length
;
1946 out
->printf("Unmapped large spans:\n");
1947 for (Span
* s
= large_
.returned
.next
; s
!= &large_
.returned
; s
= s
->next
) {
1948 out
->printf(" [ %6" PRIuS
" pages ] %6.1f MB\n",
1949 s
->length
, PagesToMB(s
->length
));
1950 r_pages
+= s
->length
;
1953 total_normal
+= n_pages
;
1954 total_returned
+= r_pages
;
1955 out
->printf(">255 large * %6u spans ~ %6.1f MB; %6.1f MB cum"
1956 "; unmapped: %6.1f MB; %6.1f MB cum\n",
1957 (n_spans
+ r_spans
),
1958 PagesToMB(n_pages
+ r_pages
),
1959 PagesToMB(total_normal
+ total_returned
),
1961 PagesToMB(total_returned
));
1965 bool TCMalloc_PageHeap::GrowHeap(Length n
) {
1966 ASSERT(kMaxPages
>= kMinSystemAlloc
);
1967 if (n
> kMaxValidPages
) return false;
1968 Length ask
= (n
>kMinSystemAlloc
) ? n
: static_cast<Length
>(kMinSystemAlloc
);
1970 void* ptr
= TCMalloc_SystemAlloc(ask
<< kPageShift
, &actual_size
, kPageSize
);
1973 // Try growing just "n" pages
1975 ptr
= TCMalloc_SystemAlloc(ask
<< kPageShift
, &actual_size
, kPageSize
);
1977 if (ptr
== NULL
) return false;
1979 ask
= actual_size
>> kPageShift
;
1981 uint64_t old_system_bytes
= system_bytes_
;
1982 system_bytes_
+= (ask
<< kPageShift
);
1983 const PageID p
= reinterpret_cast<uintptr_t>(ptr
) >> kPageShift
;
1986 // If we have already a lot of pages allocated, just pre allocate a bunch of
1987 // memory for the page map. This prevents fragmentation by pagemap metadata
1988 // when a program keeps allocating and freeing large blocks.
1990 if (old_system_bytes
< kPageMapBigAllocationThreshold
1991 && system_bytes_
>= kPageMapBigAllocationThreshold
) {
1992 pagemap_
.PreallocateMoreMemory();
1995 // Make sure pagemap_ has entries for all of the new pages.
1996 // Plus ensure one before and one after so coalescing code
1997 // does not need bounds-checking.
1998 if (pagemap_
.Ensure(p
-1, ask
+2)) {
1999 // Pretend the new area is allocated and then Delete() it to
2000 // cause any necessary coalescing to occur.
2002 // We do not adjust free_pages_ here since Delete() will do it for us.
2003 Span
* span
= NewSpan(p
, ask
);
2009 // We could not allocate memory within "pagemap_"
2010 // TODO: Once we can return memory to the system, return the new span
2015 bool TCMalloc_PageHeap::Check() {
2016 ASSERT(free_
[0].normal
.next
== &free_
[0].normal
);
2017 ASSERT(free_
[0].returned
.next
== &free_
[0].returned
);
2018 CheckList(&large_
.normal
, kMaxPages
, 1000000000);
2019 CheckList(&large_
.returned
, kMaxPages
, 1000000000);
2020 for (Length s
= 1; s
< kMaxPages
; s
++) {
2021 CheckList(&free_
[s
].normal
, s
, s
);
2022 CheckList(&free_
[s
].returned
, s
, s
);
2028 bool TCMalloc_PageHeap::CheckList(Span
*, Length
, Length
) {
2032 bool TCMalloc_PageHeap::CheckList(Span
* list
, Length min_pages
, Length max_pages
) {
2033 for (Span
* s
= list
->next
; s
!= list
; s
= s
->next
) {
2034 CHECK_CONDITION(s
->free
);
2035 CHECK_CONDITION(s
->length
>= min_pages
);
2036 CHECK_CONDITION(s
->length
<= max_pages
);
2037 CHECK_CONDITION(GetDescriptor(s
->start
) == s
);
2038 CHECK_CONDITION(GetDescriptor(s
->start
+s
->length
-1) == s
);
2044 static void ReleaseFreeList(Span
* list
, Span
* returned
) {
2045 // Walk backwards through list so that when we push these
2046 // spans on the "returned" list, we preserve the order.
2047 while (!DLL_IsEmpty(list
)) {
2048 Span
* s
= list
->prev
;
2050 DLL_Prepend(returned
, s
);
2051 TCMalloc_SystemRelease(reinterpret_cast<void*>(s
->start
<< kPageShift
),
2052 static_cast<size_t>(s
->length
<< kPageShift
));
2056 void TCMalloc_PageHeap::ReleaseFreePages() {
2057 for (Length s
= 0; s
< kMaxPages
; s
++) {
2058 ReleaseFreeList(&free_
[s
].normal
, &free_
[s
].returned
);
2060 ReleaseFreeList(&large_
.normal
, &large_
.returned
);
2064 //-------------------------------------------------------------------
2066 //-------------------------------------------------------------------
2068 class TCMalloc_ThreadCache_FreeList
{
2070 void* list_
; // Linked list of nodes
2071 uint16_t length_
; // Current length
2072 uint16_t lowater_
; // Low water mark for list length
2081 // Return current length of list
2082 int length() const {
2087 bool empty() const {
2088 return list_
== NULL
;
2091 // Low-water mark management
2092 int lowwatermark() const { return lowater_
; }
2093 void clear_lowwatermark() { lowater_
= length_
; }
2095 ALWAYS_INLINE
void Push(void* ptr
) {
2096 SLL_Push(&list_
, ptr
);
2100 void PushRange(int N
, void *start
, void *end
) {
2101 SLL_PushRange(&list_
, start
, end
);
2102 length_
= length_
+ static_cast<uint16_t>(N
);
2105 void PopRange(int N
, void **start
, void **end
) {
2106 SLL_PopRange(&list_
, N
, start
, end
);
2107 ASSERT(length_
>= N
);
2108 length_
= length_
- static_cast<uint16_t>(N
);
2109 if (length_
< lowater_
) lowater_
= length_
;
2112 ALWAYS_INLINE
void* Pop() {
2113 ASSERT(list_
!= NULL
);
2115 if (length_
< lowater_
) lowater_
= length_
;
2116 return SLL_Pop(&list_
);
2120 template <class Finder
, class Reader
>
2121 void enumerateFreeObjects(Finder
& finder
, const Reader
& reader
)
2123 for (void* nextObject
= list_
; nextObject
; nextObject
= *reader(reinterpret_cast<void**>(nextObject
)))
2124 finder
.visit(nextObject
);
2129 //-------------------------------------------------------------------
2130 // Data kept per thread
2131 //-------------------------------------------------------------------
2133 class TCMalloc_ThreadCache
{
2135 typedef TCMalloc_ThreadCache_FreeList FreeList
;
2137 typedef DWORD ThreadIdentifier
;
2139 typedef pthread_t ThreadIdentifier
;
2142 size_t size_
; // Combined size of data
2143 ThreadIdentifier tid_
; // Which thread owns it
2144 bool in_setspecific_
; // Called pthread_setspecific?
2145 FreeList list_
[kNumClasses
]; // Array indexed by size-class
2147 // We sample allocations, biased by the size of the allocation
2148 uint32_t rnd_
; // Cheap random number generator
2149 size_t bytes_until_sample_
; // Bytes until we sample next
2151 // Allocate a new heap. REQUIRES: pageheap_lock is held.
2152 static inline TCMalloc_ThreadCache
* NewHeap(ThreadIdentifier tid
);
2154 // Use only as pthread thread-specific destructor function.
2155 static void DestroyThreadCache(void* ptr
);
2157 // All ThreadCache objects are kept in a linked list (for stats collection)
2158 TCMalloc_ThreadCache
* next_
;
2159 TCMalloc_ThreadCache
* prev_
;
2161 void Init(ThreadIdentifier tid
);
2164 // Accessors (mostly just for printing stats)
2165 int freelist_length(size_t cl
) const { return list_
[cl
].length(); }
2167 // Total byte size in cache
2168 size_t Size() const { return size_
; }
2170 ALWAYS_INLINE
void* Allocate(size_t size
);
2171 void Deallocate(void* ptr
, size_t size_class
);
2173 ALWAYS_INLINE
void FetchFromCentralCache(size_t cl
, size_t allocationSize
);
2174 void ReleaseToCentralCache(size_t cl
, int N
);
2178 // Record allocation of "k" bytes. Return true iff allocation
2179 // should be sampled
2180 bool SampleAllocation(size_t k
);
2182 // Pick next sampling point
2183 void PickNextSample(size_t k
);
2185 static void InitModule();
2186 static void InitTSD();
2187 static TCMalloc_ThreadCache
* GetThreadHeap();
2188 static TCMalloc_ThreadCache
* GetCache();
2189 static TCMalloc_ThreadCache
* GetCacheIfPresent();
2190 static TCMalloc_ThreadCache
* CreateCacheIfNecessary();
2191 static void DeleteCache(TCMalloc_ThreadCache
* heap
);
2192 static void BecomeIdle();
2193 static void RecomputeThreadCacheSize();
2196 template <class Finder
, class Reader
>
2197 void enumerateFreeObjects(Finder
& finder
, const Reader
& reader
)
2199 for (unsigned sizeClass
= 0; sizeClass
< kNumClasses
; sizeClass
++)
2200 list_
[sizeClass
].enumerateFreeObjects(finder
, reader
);
2205 //-------------------------------------------------------------------
2206 // Data kept per size-class in central cache
2207 //-------------------------------------------------------------------
2209 class TCMalloc_Central_FreeList
{
2211 void Init(size_t cl
);
2213 // These methods all do internal locking.
2215 // Insert the specified range into the central freelist. N is the number of
2216 // elements in the range.
2217 void InsertRange(void *start
, void *end
, int N
);
2219 // Returns the actual number of fetched elements into N.
2220 void RemoveRange(void **start
, void **end
, int *N
);
2222 // Returns the number of free objects in cache.
2224 SpinLockHolder
h(&lock_
);
2228 // Returns the number of free objects in the transfer cache.
2230 SpinLockHolder
h(&lock_
);
2231 return used_slots_
* num_objects_to_move
[size_class_
];
2235 template <class Finder
, class Reader
>
2236 void enumerateFreeObjects(Finder
& finder
, const Reader
& reader
, TCMalloc_Central_FreeList
* remoteCentralFreeList
)
2238 for (Span
* span
= &empty_
; span
&& span
!= &empty_
; span
= (span
->next
? reader(span
->next
) : 0))
2239 ASSERT(!span
->objects
);
2241 ASSERT(!nonempty_
.objects
);
2242 static const ptrdiff_t nonemptyOffset
= reinterpret_cast<const char*>(&nonempty_
) - reinterpret_cast<const char*>(this);
2244 Span
* remoteNonempty
= reinterpret_cast<Span
*>(reinterpret_cast<char*>(remoteCentralFreeList
) + nonemptyOffset
);
2245 Span
* remoteSpan
= nonempty_
.next
;
2247 for (Span
* span
= reader(remoteSpan
); span
&& remoteSpan
!= remoteNonempty
; remoteSpan
= span
->next
, span
= (span
->next
? reader(span
->next
) : 0)) {
2248 for (void* nextObject
= span
->objects
; nextObject
; nextObject
= *reader(reinterpret_cast<void**>(nextObject
)))
2249 finder
.visit(nextObject
);
2255 // REQUIRES: lock_ is held
2256 // Remove object from cache and return.
2257 // Return NULL if no free entries in cache.
2258 void* FetchFromSpans();
2260 // REQUIRES: lock_ is held
2261 // Remove object from cache and return. Fetches
2262 // from pageheap if cache is empty. Only returns
2263 // NULL on allocation failure.
2264 void* FetchFromSpansSafe();
2266 // REQUIRES: lock_ is held
2267 // Release a linked list of objects to spans.
2268 // May temporarily release lock_.
2269 void ReleaseListToSpans(void *start
);
2271 // REQUIRES: lock_ is held
2272 // Release an object to spans.
2273 // May temporarily release lock_.
2274 ALWAYS_INLINE
void ReleaseToSpans(void* object
);
2276 // REQUIRES: lock_ is held
2277 // Populate cache by fetching from the page heap.
2278 // May temporarily release lock_.
2279 ALWAYS_INLINE
void Populate();
2281 // REQUIRES: lock is held.
2282 // Tries to make room for a TCEntry. If the cache is full it will try to
2283 // expand it at the cost of some other cache size. Return false if there is
2285 bool MakeCacheSpace();
2287 // REQUIRES: lock_ for locked_size_class is held.
2288 // Picks a "random" size class to steal TCEntry slot from. In reality it
2289 // just iterates over the sizeclasses but does so without taking a lock.
2290 // Returns true on success.
2291 // May temporarily lock a "random" size class.
2292 static ALWAYS_INLINE
bool EvictRandomSizeClass(size_t locked_size_class
, bool force
);
2294 // REQUIRES: lock_ is *not* held.
2295 // Tries to shrink the Cache. If force is true it will relase objects to
2296 // spans if it allows it to shrink the cache. Return false if it failed to
2297 // shrink the cache. Decrements cache_size_ on succeess.
2298 // May temporarily take lock_. If it takes lock_, the locked_size_class
2299 // lock is released to the thread from holding two size class locks
2300 // concurrently which could lead to a deadlock.
2301 bool ShrinkCache(int locked_size_class
, bool force
);
2303 // This lock protects all the data members. cached_entries and cache_size_
2304 // may be looked at without holding the lock.
2307 // We keep linked lists of empty and non-empty spans.
2308 size_t size_class_
; // My size class
2309 Span empty_
; // Dummy header for list of empty spans
2310 Span nonempty_
; // Dummy header for list of non-empty spans
2311 size_t counter_
; // Number of free objects in cache entry
2313 // Here we reserve space for TCEntry cache slots. Since one size class can
2314 // end up getting all the TCEntries quota in the system we just preallocate
2315 // sufficient number of entries here.
2316 TCEntry tc_slots_
[kNumTransferEntries
];
2318 // Number of currently used cached entries in tc_slots_. This variable is
2319 // updated under a lock but can be read without one.
2320 int32_t used_slots_
;
2321 // The current number of slots for this size class. This is an
2322 // adaptive value that is increased if there is lots of traffic
2323 // on a given size class.
2324 int32_t cache_size_
;
2327 // Pad each CentralCache object to multiple of 64 bytes
2328 class TCMalloc_Central_FreeListPadded
: public TCMalloc_Central_FreeList
{
2330 char pad_
[(64 - (sizeof(TCMalloc_Central_FreeList
) % 64)) % 64];
2333 //-------------------------------------------------------------------
2335 //-------------------------------------------------------------------
2337 // Central cache -- a collection of free-lists, one per size-class.
2338 // We have a separate lock per free-list to reduce contention.
2339 static TCMalloc_Central_FreeListPadded central_cache
[kNumClasses
];
2341 // Page-level allocator
2342 static SpinLock pageheap_lock
= SPINLOCK_INITIALIZER
;
2345 static void* pageheap_memory
[(sizeof(TCMalloc_PageHeap
) + sizeof(void*) - 1) / sizeof(void*)] __attribute__((aligned
));
2347 static AllocAlignmentInteger pageheap_memory
[(sizeof(TCMalloc_PageHeap
) + sizeof(AllocAlignmentInteger
) - 1) / sizeof(AllocAlignmentInteger
)];
2349 static bool phinited
= false;
2351 // Avoid extra level of indirection by making "pageheap" be just an alias
2352 // of pageheap_memory.
2355 TCMalloc_PageHeap
* m_pageHeap
;
2358 static inline TCMalloc_PageHeap
* getPageHeap()
2360 PageHeapUnion u
= { &pageheap_memory
[0] };
2361 return u
.m_pageHeap
;
2364 #define pageheap getPageHeap()
2366 #if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
2368 #if !HAVE(DISPATCH_H)
2370 static void sleep(unsigned seconds
)
2372 ::Sleep(seconds
* 1000);
2376 void TCMalloc_PageHeap::scavengerThread()
2378 #if HAVE(PTHREAD_SETNAME_NP)
2379 pthread_setname_np("JavaScriptCore: FastMalloc scavenger");
2383 if (!shouldScavenge()) {
2384 pthread_mutex_lock(&m_scavengeMutex
);
2385 m_scavengeThreadActive
= false;
2386 // Block until there are enough free committed pages to release back to the system.
2387 pthread_cond_wait(&m_scavengeCondition
, &m_scavengeMutex
);
2388 m_scavengeThreadActive
= true;
2389 pthread_mutex_unlock(&m_scavengeMutex
);
2391 sleep(kScavengeDelayInSeconds
);
2393 SpinLockHolder
h(&pageheap_lock
);
2394 pageheap
->scavenge();
2401 void TCMalloc_PageHeap::periodicScavenge()
2404 SpinLockHolder
h(&pageheap_lock
);
2405 pageheap
->scavenge();
2408 if (!shouldScavenge()) {
2409 m_scavengingScheduled
= false;
2410 dispatch_suspend(m_scavengeTimer
);
2413 #endif // HAVE(DISPATCH_H)
2417 // If TLS is available, we also store a copy
2418 // of the per-thread object in a __thread variable
2419 // since __thread variables are faster to read
2420 // than pthread_getspecific(). We still need
2421 // pthread_setspecific() because __thread
2422 // variables provide no way to run cleanup
2423 // code when a thread is destroyed.
2425 static __thread TCMalloc_ThreadCache
*threadlocal_heap
;
2427 // Thread-specific key. Initialization here is somewhat tricky
2428 // because some Linux startup code invokes malloc() before it
2429 // is in a good enough state to handle pthread_keycreate().
2430 // Therefore, we use TSD keys only after tsd_inited is set to true.
2431 // Until then, we use a slow path to get the heap object.
2432 static bool tsd_inited
= false;
2433 #if USE(PTHREAD_GETSPECIFIC_DIRECT)
2434 static pthread_key_t heap_key
= __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY0
;
2436 static pthread_key_t heap_key
;
2439 DWORD tlsIndex
= TLS_OUT_OF_INDEXES
;
2442 static ALWAYS_INLINE
void setThreadHeap(TCMalloc_ThreadCache
* heap
)
2444 // still do pthread_setspecific when using MSVC fast TLS to
2445 // benefit from the delete callback.
2446 pthread_setspecific(heap_key
, heap
);
2448 TlsSetValue(tlsIndex
, heap
);
2452 // Allocator for thread heaps
2453 static PageHeapAllocator
<TCMalloc_ThreadCache
> threadheap_allocator
;
2455 // Linked list of heap objects. Protected by pageheap_lock.
2456 static TCMalloc_ThreadCache
* thread_heaps
= NULL
;
2457 static int thread_heap_count
= 0;
2459 // Overall thread cache size. Protected by pageheap_lock.
2460 static size_t overall_thread_cache_size
= kDefaultOverallThreadCacheSize
;
2462 // Global per-thread cache size. Writes are protected by
2463 // pageheap_lock. Reads are done without any locking, which should be
2464 // fine as long as size_t can be written atomically and we don't place
2465 // invariants between this variable and other pieces of state.
2466 static volatile size_t per_thread_cache_size
= kMaxThreadCacheSize
;
2468 //-------------------------------------------------------------------
2469 // Central cache implementation
2470 //-------------------------------------------------------------------
2472 void TCMalloc_Central_FreeList::Init(size_t cl
) {
2476 DLL_Init(&nonempty_
);
2481 ASSERT(cache_size_
<= kNumTransferEntries
);
2484 void TCMalloc_Central_FreeList::ReleaseListToSpans(void* start
) {
2486 void *next
= SLL_Next(start
);
2487 ReleaseToSpans(start
);
2492 ALWAYS_INLINE
void TCMalloc_Central_FreeList::ReleaseToSpans(void* object
) {
2493 const PageID p
= reinterpret_cast<uintptr_t>(object
) >> kPageShift
;
2494 Span
* span
= pageheap
->GetDescriptor(p
);
2495 ASSERT(span
!= NULL
);
2496 ASSERT(span
->refcount
> 0);
2498 // If span is empty, move it to non-empty list
2499 if (span
->objects
== NULL
) {
2501 DLL_Prepend(&nonempty_
, span
);
2502 Event(span
, 'N', 0);
2505 // The following check is expensive, so it is disabled by default
2507 // Check that object does not occur in list
2509 for (void* p
= span
->objects
; p
!= NULL
; p
= *((void**) p
)) {
2510 ASSERT(p
!= object
);
2513 ASSERT(got
+ span
->refcount
==
2514 (span
->length
<<kPageShift
)/ByteSizeForClass(span
->sizeclass
));
2519 if (span
->refcount
== 0) {
2520 Event(span
, '#', 0);
2521 counter_
-= (span
->length
<<kPageShift
) / ByteSizeForClass(span
->sizeclass
);
2524 // Release central list lock while operating on pageheap
2527 SpinLockHolder
h(&pageheap_lock
);
2528 pageheap
->Delete(span
);
2532 *(reinterpret_cast<void**>(object
)) = span
->objects
;
2533 span
->objects
= object
;
2537 ALWAYS_INLINE
bool TCMalloc_Central_FreeList::EvictRandomSizeClass(
2538 size_t locked_size_class
, bool force
) {
2539 static int race_counter
= 0;
2540 int t
= race_counter
++; // Updated without a lock, but who cares.
2541 if (t
>= static_cast<int>(kNumClasses
)) {
2542 while (t
>= static_cast<int>(kNumClasses
)) {
2548 ASSERT(t
< static_cast<int>(kNumClasses
));
2549 if (t
== static_cast<int>(locked_size_class
)) return false;
2550 return central_cache
[t
].ShrinkCache(static_cast<int>(locked_size_class
), force
);
2553 bool TCMalloc_Central_FreeList::MakeCacheSpace() {
2554 // Is there room in the cache?
2555 if (used_slots_
< cache_size_
) return true;
2556 // Check if we can expand this cache?
2557 if (cache_size_
== kNumTransferEntries
) return false;
2558 // Ok, we'll try to grab an entry from some other size class.
2559 if (EvictRandomSizeClass(size_class_
, false) ||
2560 EvictRandomSizeClass(size_class_
, true)) {
2561 // Succeeded in evicting, we're going to make our cache larger.
2570 class LockInverter
{
2572 SpinLock
*held_
, *temp_
;
2574 inline explicit LockInverter(SpinLock
* held
, SpinLock
*temp
)
2575 : held_(held
), temp_(temp
) { held_
->Unlock(); temp_
->Lock(); }
2576 inline ~LockInverter() { temp_
->Unlock(); held_
->Lock(); }
2580 bool TCMalloc_Central_FreeList::ShrinkCache(int locked_size_class
, bool force
) {
2581 // Start with a quick check without taking a lock.
2582 if (cache_size_
== 0) return false;
2583 // We don't evict from a full cache unless we are 'forcing'.
2584 if (force
== false && used_slots_
== cache_size_
) return false;
2586 // Grab lock, but first release the other lock held by this thread. We use
2587 // the lock inverter to ensure that we never hold two size class locks
2588 // concurrently. That can create a deadlock because there is no well
2589 // defined nesting order.
2590 LockInverter
li(¢ral_cache
[locked_size_class
].lock_
, &lock_
);
2591 ASSERT(used_slots_
<= cache_size_
);
2592 ASSERT(0 <= cache_size_
);
2593 if (cache_size_
== 0) return false;
2594 if (used_slots_
== cache_size_
) {
2595 if (force
== false) return false;
2596 // ReleaseListToSpans releases the lock, so we have to make all the
2597 // updates to the central list before calling it.
2600 ReleaseListToSpans(tc_slots_
[used_slots_
].head
);
2607 void TCMalloc_Central_FreeList::InsertRange(void *start
, void *end
, int N
) {
2608 SpinLockHolder
h(&lock_
);
2609 if (N
== num_objects_to_move
[size_class_
] &&
2611 int slot
= used_slots_
++;
2613 ASSERT(slot
< kNumTransferEntries
);
2614 TCEntry
*entry
= &tc_slots_
[slot
];
2615 entry
->head
= start
;
2619 ReleaseListToSpans(start
);
2622 void TCMalloc_Central_FreeList::RemoveRange(void **start
, void **end
, int *N
) {
2626 SpinLockHolder
h(&lock_
);
2627 if (num
== num_objects_to_move
[size_class_
] && used_slots_
> 0) {
2628 int slot
= --used_slots_
;
2630 TCEntry
*entry
= &tc_slots_
[slot
];
2631 *start
= entry
->head
;
2636 // TODO: Prefetch multiple TCEntries?
2637 void *tail
= FetchFromSpansSafe();
2639 // We are completely out of memory.
2640 *start
= *end
= NULL
;
2645 SLL_SetNext(tail
, NULL
);
2648 while (count
< num
) {
2649 void *t
= FetchFromSpans();
2660 void* TCMalloc_Central_FreeList::FetchFromSpansSafe() {
2661 void *t
= FetchFromSpans();
2664 t
= FetchFromSpans();
2669 void* TCMalloc_Central_FreeList::FetchFromSpans() {
2670 if (DLL_IsEmpty(&nonempty_
)) return NULL
;
2671 Span
* span
= nonempty_
.next
;
2673 ASSERT(span
->objects
!= NULL
);
2674 ASSERT_SPAN_COMMITTED(span
);
2676 void* result
= span
->objects
;
2677 span
->objects
= *(reinterpret_cast<void**>(result
));
2678 if (span
->objects
== NULL
) {
2679 // Move to empty list
2681 DLL_Prepend(&empty_
, span
);
2682 Event(span
, 'E', 0);
2688 // Fetch memory from the system and add to the central cache freelist.
2689 ALWAYS_INLINE
void TCMalloc_Central_FreeList::Populate() {
2690 // Release central list lock while operating on pageheap
2692 const size_t npages
= class_to_pages
[size_class_
];
2696 SpinLockHolder
h(&pageheap_lock
);
2697 span
= pageheap
->New(npages
);
2698 if (span
) pageheap
->RegisterSizeClass(span
, size_class_
);
2701 MESSAGE("allocation failed: %d\n", errno
);
2705 ASSERT_SPAN_COMMITTED(span
);
2706 ASSERT(span
->length
== npages
);
2707 // Cache sizeclass info eagerly. Locking is not necessary.
2708 // (Instead of being eager, we could just replace any stale info
2709 // about this span, but that seems to be no better in practice.)
2710 for (size_t i
= 0; i
< npages
; i
++) {
2711 pageheap
->CacheSizeClass(span
->start
+ i
, size_class_
);
2714 // Split the block into pieces and add to the free-list
2715 // TODO: coloring of objects to avoid cache conflicts?
2716 void** tail
= &span
->objects
;
2717 char* ptr
= reinterpret_cast<char*>(span
->start
<< kPageShift
);
2718 char* limit
= ptr
+ (npages
<< kPageShift
);
2719 const size_t size
= ByteSizeForClass(size_class_
);
2722 while ((nptr
= ptr
+ size
) <= limit
) {
2724 tail
= reinterpret_cast<void**>(ptr
);
2728 ASSERT(ptr
<= limit
);
2730 span
->refcount
= 0; // No sub-object in use yet
2732 // Add span to list of non-empty spans
2734 DLL_Prepend(&nonempty_
, span
);
2738 //-------------------------------------------------------------------
2739 // TCMalloc_ThreadCache implementation
2740 //-------------------------------------------------------------------
2742 inline bool TCMalloc_ThreadCache::SampleAllocation(size_t k
) {
2743 if (bytes_until_sample_
< k
) {
2747 bytes_until_sample_
-= k
;
2752 void TCMalloc_ThreadCache::Init(ThreadIdentifier tid
) {
2757 in_setspecific_
= false;
2758 for (size_t cl
= 0; cl
< kNumClasses
; ++cl
) {
2762 // Initialize RNG -- run it for a bit to get to good values
2763 bytes_until_sample_
= 0;
2764 rnd_
= static_cast<uint32_t>(reinterpret_cast<uintptr_t>(this));
2765 for (int i
= 0; i
< 100; i
++) {
2766 PickNextSample(static_cast<size_t>(FLAGS_tcmalloc_sample_parameter
* 2));
2770 void TCMalloc_ThreadCache::Cleanup() {
2771 // Put unused memory back into central cache
2772 for (size_t cl
= 0; cl
< kNumClasses
; ++cl
) {
2773 if (list_
[cl
].length() > 0) {
2774 ReleaseToCentralCache(cl
, list_
[cl
].length());
2779 ALWAYS_INLINE
void* TCMalloc_ThreadCache::Allocate(size_t size
) {
2780 ASSERT(size
<= kMaxSize
);
2781 const size_t cl
= SizeClass(size
);
2782 FreeList
* list
= &list_
[cl
];
2783 size_t allocationSize
= ByteSizeForClass(cl
);
2784 if (list
->empty()) {
2785 FetchFromCentralCache(cl
, allocationSize
);
2786 if (list
->empty()) return NULL
;
2788 size_
-= allocationSize
;
2792 inline void TCMalloc_ThreadCache::Deallocate(void* ptr
, size_t cl
) {
2793 size_
+= ByteSizeForClass(cl
);
2794 FreeList
* list
= &list_
[cl
];
2796 // If enough data is free, put back into central cache
2797 if (list
->length() > kMaxFreeListLength
) {
2798 ReleaseToCentralCache(cl
, num_objects_to_move
[cl
]);
2800 if (size_
>= per_thread_cache_size
) Scavenge();
2803 // Remove some objects of class "cl" from central cache and add to thread heap
2804 ALWAYS_INLINE
void TCMalloc_ThreadCache::FetchFromCentralCache(size_t cl
, size_t allocationSize
) {
2805 int fetch_count
= num_objects_to_move
[cl
];
2807 central_cache
[cl
].RemoveRange(&start
, &end
, &fetch_count
);
2808 list_
[cl
].PushRange(fetch_count
, start
, end
);
2809 size_
+= allocationSize
* fetch_count
;
2812 // Remove some objects of class "cl" from thread heap and add to central cache
2813 inline void TCMalloc_ThreadCache::ReleaseToCentralCache(size_t cl
, int N
) {
2815 FreeList
* src
= &list_
[cl
];
2816 if (N
> src
->length()) N
= src
->length();
2817 size_
-= N
*ByteSizeForClass(cl
);
2819 // We return prepackaged chains of the correct size to the central cache.
2820 // TODO: Use the same format internally in the thread caches?
2821 int batch_size
= num_objects_to_move
[cl
];
2822 while (N
> batch_size
) {
2824 src
->PopRange(batch_size
, &head
, &tail
);
2825 central_cache
[cl
].InsertRange(head
, tail
, batch_size
);
2829 src
->PopRange(N
, &head
, &tail
);
2830 central_cache
[cl
].InsertRange(head
, tail
, N
);
2833 // Release idle memory to the central cache
2834 inline void TCMalloc_ThreadCache::Scavenge() {
2835 // If the low-water mark for the free list is L, it means we would
2836 // not have had to allocate anything from the central cache even if
2837 // we had reduced the free list size by L. We aim to get closer to
2838 // that situation by dropping L/2 nodes from the free list. This
2839 // may not release much memory, but if so we will call scavenge again
2840 // pretty soon and the low-water marks will be high on that call.
2841 //int64 start = CycleClock::Now();
2843 for (size_t cl
= 0; cl
< kNumClasses
; cl
++) {
2844 FreeList
* list
= &list_
[cl
];
2845 const int lowmark
= list
->lowwatermark();
2847 const int drop
= (lowmark
> 1) ? lowmark
/2 : 1;
2848 ReleaseToCentralCache(cl
, drop
);
2850 list
->clear_lowwatermark();
2853 //int64 finish = CycleClock::Now();
2855 //MESSAGE("GC: %.0f ns\n", ct.CyclesToUsec(finish-start)*1000.0);
2858 void TCMalloc_ThreadCache::PickNextSample(size_t k
) {
2859 // Make next "random" number
2860 // x^32+x^22+x^2+x^1+1 is a primitive polynomial for random numbers
2861 static const uint32_t kPoly
= (1 << 22) | (1 << 2) | (1 << 1) | (1 << 0);
2863 rnd_
= (r
<< 1) ^ ((static_cast<int32_t>(r
) >> 31) & kPoly
);
2865 // Next point is "rnd_ % (sample_period)". I.e., average
2866 // increment is "sample_period/2".
2867 const int flag_value
= static_cast<int>(FLAGS_tcmalloc_sample_parameter
);
2868 static int last_flag_value
= -1;
2870 if (flag_value
!= last_flag_value
) {
2871 SpinLockHolder
h(&sample_period_lock
);
2873 for (i
= 0; i
< (static_cast<int>(sizeof(primes_list
)/sizeof(primes_list
[0])) - 1); i
++) {
2874 if (primes_list
[i
] >= flag_value
) {
2878 sample_period
= primes_list
[i
];
2879 last_flag_value
= flag_value
;
2882 bytes_until_sample_
+= rnd_
% sample_period
;
2884 if (k
> (static_cast<size_t>(-1) >> 2)) {
2885 // If the user has asked for a huge allocation then it is possible
2886 // for the code below to loop infinitely. Just return (note that
2887 // this throws off the sampling accuracy somewhat, but a user who
2888 // is allocating more than 1G of memory at a time can live with a
2889 // minor inaccuracy in profiling of small allocations, and also
2890 // would rather not wait for the loop below to terminate).
2894 while (bytes_until_sample_
< k
) {
2895 // Increase bytes_until_sample_ by enough average sampling periods
2896 // (sample_period >> 1) to allow us to sample past the current
2898 bytes_until_sample_
+= (sample_period
>> 1);
2901 bytes_until_sample_
-= k
;
2904 void TCMalloc_ThreadCache::InitModule() {
2905 // There is a slight potential race here because of double-checked
2906 // locking idiom. However, as long as the program does a small
2907 // allocation before switching to multi-threaded mode, we will be
2908 // fine. We increase the chances of doing such a small allocation
2909 // by doing one in the constructor of the module_enter_exit_hook
2910 // object declared below.
2911 SpinLockHolder
h(&pageheap_lock
);
2917 threadheap_allocator
.Init();
2918 span_allocator
.Init();
2919 span_allocator
.New(); // Reduce cache conflicts
2920 span_allocator
.New(); // Reduce cache conflicts
2921 stacktrace_allocator
.Init();
2922 DLL_Init(&sampled_objects
);
2923 for (size_t i
= 0; i
< kNumClasses
; ++i
) {
2924 central_cache
[i
].Init(i
);
2928 #if defined(WTF_CHANGES) && OS(DARWIN)
2929 FastMallocZone::init();
2934 inline TCMalloc_ThreadCache
* TCMalloc_ThreadCache::NewHeap(ThreadIdentifier tid
) {
2935 // Create the heap and add it to the linked list
2936 TCMalloc_ThreadCache
*heap
= threadheap_allocator
.New();
2938 heap
->next_
= thread_heaps
;
2940 if (thread_heaps
!= NULL
) thread_heaps
->prev_
= heap
;
2941 thread_heaps
= heap
;
2942 thread_heap_count
++;
2943 RecomputeThreadCacheSize();
2947 inline TCMalloc_ThreadCache
* TCMalloc_ThreadCache::GetThreadHeap() {
2949 // __thread is faster, but only when the kernel supports it
2950 if (KernelSupportsTLS())
2951 return threadlocal_heap
;
2952 #elif COMPILER(MSVC)
2953 return static_cast<TCMalloc_ThreadCache
*>(TlsGetValue(tlsIndex
));
2955 return static_cast<TCMalloc_ThreadCache
*>(pthread_getspecific(heap_key
));
2959 inline TCMalloc_ThreadCache
* TCMalloc_ThreadCache::GetCache() {
2960 TCMalloc_ThreadCache
* ptr
= NULL
;
2964 ptr
= GetThreadHeap();
2966 if (ptr
== NULL
) ptr
= CreateCacheIfNecessary();
2970 // In deletion paths, we do not try to create a thread-cache. This is
2971 // because we may be in the thread destruction code and may have
2972 // already cleaned up the cache for this thread.
2973 inline TCMalloc_ThreadCache
* TCMalloc_ThreadCache::GetCacheIfPresent() {
2974 if (!tsd_inited
) return NULL
;
2975 void* const p
= GetThreadHeap();
2976 return reinterpret_cast<TCMalloc_ThreadCache
*>(p
);
2979 void TCMalloc_ThreadCache::InitTSD() {
2980 ASSERT(!tsd_inited
);
2981 #if USE(PTHREAD_GETSPECIFIC_DIRECT)
2982 pthread_key_init_np(heap_key
, DestroyThreadCache
);
2984 pthread_key_create(&heap_key
, DestroyThreadCache
);
2987 tlsIndex
= TlsAlloc();
2992 // We may have used a fake pthread_t for the main thread. Fix it.
2994 memset(&zero
, 0, sizeof(zero
));
2997 SpinLockHolder
h(&pageheap_lock
);
2999 ASSERT(pageheap_lock
.IsHeld());
3001 for (TCMalloc_ThreadCache
* h
= thread_heaps
; h
!= NULL
; h
= h
->next_
) {
3004 h
->tid_
= GetCurrentThreadId();
3007 if (pthread_equal(h
->tid_
, zero
)) {
3008 h
->tid_
= pthread_self();
3014 TCMalloc_ThreadCache
* TCMalloc_ThreadCache::CreateCacheIfNecessary() {
3015 // Initialize per-thread data if necessary
3016 TCMalloc_ThreadCache
* heap
= NULL
;
3018 SpinLockHolder
h(&pageheap_lock
);
3025 me
= GetCurrentThreadId();
3028 // Early on in glibc's life, we cannot even call pthread_self()
3031 memset(&me
, 0, sizeof(me
));
3033 me
= pthread_self();
3037 // This may be a recursive malloc call from pthread_setspecific()
3038 // In that case, the heap for this thread has already been created
3039 // and added to the linked list. So we search for that first.
3040 for (TCMalloc_ThreadCache
* h
= thread_heaps
; h
!= NULL
; h
= h
->next_
) {
3042 if (h
->tid_
== me
) {
3044 if (pthread_equal(h
->tid_
, me
)) {
3051 if (heap
== NULL
) heap
= NewHeap(me
);
3054 // We call pthread_setspecific() outside the lock because it may
3055 // call malloc() recursively. The recursive call will never get
3056 // here again because it will find the already allocated heap in the
3057 // linked list of heaps.
3058 if (!heap
->in_setspecific_
&& tsd_inited
) {
3059 heap
->in_setspecific_
= true;
3060 setThreadHeap(heap
);
3065 void TCMalloc_ThreadCache::BecomeIdle() {
3066 if (!tsd_inited
) return; // No caches yet
3067 TCMalloc_ThreadCache
* heap
= GetThreadHeap();
3068 if (heap
== NULL
) return; // No thread cache to remove
3069 if (heap
->in_setspecific_
) return; // Do not disturb the active caller
3071 heap
->in_setspecific_
= true;
3072 pthread_setspecific(heap_key
, NULL
);
3074 // Also update the copy in __thread
3075 threadlocal_heap
= NULL
;
3077 heap
->in_setspecific_
= false;
3078 if (GetThreadHeap() == heap
) {
3079 // Somehow heap got reinstated by a recursive call to malloc
3080 // from pthread_setspecific. We give up in this case.
3084 // We can now get rid of the heap
3088 void TCMalloc_ThreadCache::DestroyThreadCache(void* ptr
) {
3089 // Note that "ptr" cannot be NULL since pthread promises not
3090 // to invoke the destructor on NULL values, but for safety,
3092 if (ptr
== NULL
) return;
3094 // Prevent fast path of GetThreadHeap() from returning heap.
3095 threadlocal_heap
= NULL
;
3097 DeleteCache(reinterpret_cast<TCMalloc_ThreadCache
*>(ptr
));
3100 void TCMalloc_ThreadCache::DeleteCache(TCMalloc_ThreadCache
* heap
) {
3101 // Remove all memory from heap
3104 // Remove from linked list
3105 SpinLockHolder
h(&pageheap_lock
);
3106 if (heap
->next_
!= NULL
) heap
->next_
->prev_
= heap
->prev_
;
3107 if (heap
->prev_
!= NULL
) heap
->prev_
->next_
= heap
->next_
;
3108 if (thread_heaps
== heap
) thread_heaps
= heap
->next_
;
3109 thread_heap_count
--;
3110 RecomputeThreadCacheSize();
3112 threadheap_allocator
.Delete(heap
);
3115 void TCMalloc_ThreadCache::RecomputeThreadCacheSize() {
3116 // Divide available space across threads
3117 int n
= thread_heap_count
> 0 ? thread_heap_count
: 1;
3118 size_t space
= overall_thread_cache_size
/ n
;
3120 // Limit to allowed range
3121 if (space
< kMinThreadCacheSize
) space
= kMinThreadCacheSize
;
3122 if (space
> kMaxThreadCacheSize
) space
= kMaxThreadCacheSize
;
3124 per_thread_cache_size
= space
;
3127 void TCMalloc_ThreadCache::Print() const {
3128 for (size_t cl
= 0; cl
< kNumClasses
; ++cl
) {
3129 MESSAGE(" %5" PRIuS
" : %4d len; %4d lo\n",
3130 ByteSizeForClass(cl
),
3132 list_
[cl
].lowwatermark());
3136 // Extract interesting stats
3137 struct TCMallocStats
{
3138 uint64_t system_bytes
; // Bytes alloced from system
3139 uint64_t thread_bytes
; // Bytes in thread caches
3140 uint64_t central_bytes
; // Bytes in central cache
3141 uint64_t transfer_bytes
; // Bytes in central transfer cache
3142 uint64_t pageheap_bytes
; // Bytes in page heap
3143 uint64_t metadata_bytes
; // Bytes alloced for metadata
3147 // Get stats into "r". Also get per-size-class counts if class_count != NULL
3148 static void ExtractStats(TCMallocStats
* r
, uint64_t* class_count
) {
3149 r
->central_bytes
= 0;
3150 r
->transfer_bytes
= 0;
3151 for (int cl
= 0; cl
< kNumClasses
; ++cl
) {
3152 const int length
= central_cache
[cl
].length();
3153 const int tc_length
= central_cache
[cl
].tc_length();
3154 r
->central_bytes
+= static_cast<uint64_t>(ByteSizeForClass(cl
)) * length
;
3155 r
->transfer_bytes
+=
3156 static_cast<uint64_t>(ByteSizeForClass(cl
)) * tc_length
;
3157 if (class_count
) class_count
[cl
] = length
+ tc_length
;
3160 // Add stats from per-thread heaps
3161 r
->thread_bytes
= 0;
3163 SpinLockHolder
h(&pageheap_lock
);
3164 for (TCMalloc_ThreadCache
* h
= thread_heaps
; h
!= NULL
; h
= h
->next_
) {
3165 r
->thread_bytes
+= h
->Size();
3167 for (size_t cl
= 0; cl
< kNumClasses
; ++cl
) {
3168 class_count
[cl
] += h
->freelist_length(cl
);
3175 SpinLockHolder
h(&pageheap_lock
);
3176 r
->system_bytes
= pageheap
->SystemBytes();
3177 r
->metadata_bytes
= metadata_system_bytes
;
3178 r
->pageheap_bytes
= pageheap
->FreeBytes();
3184 // WRITE stats to "out"
3185 static void DumpStats(TCMalloc_Printer
* out
, int level
) {
3186 TCMallocStats stats
;
3187 uint64_t class_count
[kNumClasses
];
3188 ExtractStats(&stats
, (level
>= 2 ? class_count
: NULL
));
3191 out
->printf("------------------------------------------------\n");
3192 uint64_t cumulative
= 0;
3193 for (int cl
= 0; cl
< kNumClasses
; ++cl
) {
3194 if (class_count
[cl
] > 0) {
3195 uint64_t class_bytes
= class_count
[cl
] * ByteSizeForClass(cl
);
3196 cumulative
+= class_bytes
;
3197 out
->printf("class %3d [ %8" PRIuS
" bytes ] : "
3198 "%8" PRIu64
" objs; %5.1f MB; %5.1f cum MB\n",
3199 cl
, ByteSizeForClass(cl
),
3201 class_bytes
/ 1048576.0,
3202 cumulative
/ 1048576.0);
3206 SpinLockHolder
h(&pageheap_lock
);
3207 pageheap
->Dump(out
);
3210 const uint64_t bytes_in_use
= stats
.system_bytes
3211 - stats
.pageheap_bytes
3212 - stats
.central_bytes
3213 - stats
.transfer_bytes
3214 - stats
.thread_bytes
;
3216 out
->printf("------------------------------------------------\n"
3217 "MALLOC: %12" PRIu64
" Heap size\n"
3218 "MALLOC: %12" PRIu64
" Bytes in use by application\n"
3219 "MALLOC: %12" PRIu64
" Bytes free in page heap\n"
3220 "MALLOC: %12" PRIu64
" Bytes free in central cache\n"
3221 "MALLOC: %12" PRIu64
" Bytes free in transfer cache\n"
3222 "MALLOC: %12" PRIu64
" Bytes free in thread caches\n"
3223 "MALLOC: %12" PRIu64
" Spans in use\n"
3224 "MALLOC: %12" PRIu64
" Thread heaps in use\n"
3225 "MALLOC: %12" PRIu64
" Metadata allocated\n"
3226 "------------------------------------------------\n",
3229 stats
.pageheap_bytes
,
3230 stats
.central_bytes
,
3231 stats
.transfer_bytes
,
3233 uint64_t(span_allocator
.inuse()),
3234 uint64_t(threadheap_allocator
.inuse()),
3235 stats
.metadata_bytes
);
3238 static void PrintStats(int level
) {
3239 const int kBufferSize
= 16 << 10;
3240 char* buffer
= new char[kBufferSize
];
3241 TCMalloc_Printer
printer(buffer
, kBufferSize
);
3242 DumpStats(&printer
, level
);
3243 write(STDERR_FILENO
, buffer
, strlen(buffer
));
3247 static void** DumpStackTraces() {
3248 // Count how much space we need
3249 int needed_slots
= 0;
3251 SpinLockHolder
h(&pageheap_lock
);
3252 for (Span
* s
= sampled_objects
.next
; s
!= &sampled_objects
; s
= s
->next
) {
3253 StackTrace
* stack
= reinterpret_cast<StackTrace
*>(s
->objects
);
3254 needed_slots
+= 3 + stack
->depth
;
3256 needed_slots
+= 100; // Slop in case sample grows
3257 needed_slots
+= needed_slots
/8; // An extra 12.5% slop
3260 void** result
= new void*[needed_slots
];
3261 if (result
== NULL
) {
3262 MESSAGE("tcmalloc: could not allocate %d slots for stack traces\n",
3267 SpinLockHolder
h(&pageheap_lock
);
3269 for (Span
* s
= sampled_objects
.next
; s
!= &sampled_objects
; s
= s
->next
) {
3270 ASSERT(used_slots
< needed_slots
); // Need to leave room for terminator
3271 StackTrace
* stack
= reinterpret_cast<StackTrace
*>(s
->objects
);
3272 if (used_slots
+ 3 + stack
->depth
>= needed_slots
) {
3277 result
[used_slots
+0] = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
3278 result
[used_slots
+1] = reinterpret_cast<void*>(stack
->size
);
3279 result
[used_slots
+2] = reinterpret_cast<void*>(stack
->depth
);
3280 for (int d
= 0; d
< stack
->depth
; d
++) {
3281 result
[used_slots
+3+d
] = stack
->stack
[d
];
3283 used_slots
+= 3 + stack
->depth
;
3285 result
[used_slots
] = reinterpret_cast<void*>(static_cast<uintptr_t>(0));
3292 // TCMalloc's support for extra malloc interfaces
3293 class TCMallocImplementation
: public MallocExtension
{
3295 virtual void GetStats(char* buffer
, int buffer_length
) {
3296 ASSERT(buffer_length
> 0);
3297 TCMalloc_Printer
printer(buffer
, buffer_length
);
3299 // Print level one stats unless lots of space is available
3300 if (buffer_length
< 10000) {
3301 DumpStats(&printer
, 1);
3303 DumpStats(&printer
, 2);
3307 virtual void** ReadStackTraces() {
3308 return DumpStackTraces();
3311 virtual bool GetNumericProperty(const char* name
, size_t* value
) {
3312 ASSERT(name
!= NULL
);
3314 if (strcmp(name
, "generic.current_allocated_bytes") == 0) {
3315 TCMallocStats stats
;
3316 ExtractStats(&stats
, NULL
);
3317 *value
= stats
.system_bytes
3318 - stats
.thread_bytes
3319 - stats
.central_bytes
3320 - stats
.pageheap_bytes
;
3324 if (strcmp(name
, "generic.heap_size") == 0) {
3325 TCMallocStats stats
;
3326 ExtractStats(&stats
, NULL
);
3327 *value
= stats
.system_bytes
;
3331 if (strcmp(name
, "tcmalloc.slack_bytes") == 0) {
3332 // We assume that bytes in the page heap are not fragmented too
3333 // badly, and are therefore available for allocation.
3334 SpinLockHolder
l(&pageheap_lock
);
3335 *value
= pageheap
->FreeBytes();
3339 if (strcmp(name
, "tcmalloc.max_total_thread_cache_bytes") == 0) {
3340 SpinLockHolder
l(&pageheap_lock
);
3341 *value
= overall_thread_cache_size
;
3345 if (strcmp(name
, "tcmalloc.current_total_thread_cache_bytes") == 0) {
3346 TCMallocStats stats
;
3347 ExtractStats(&stats
, NULL
);
3348 *value
= stats
.thread_bytes
;
3355 virtual bool SetNumericProperty(const char* name
, size_t value
) {
3356 ASSERT(name
!= NULL
);
3358 if (strcmp(name
, "tcmalloc.max_total_thread_cache_bytes") == 0) {
3359 // Clip the value to a reasonable range
3360 if (value
< kMinThreadCacheSize
) value
= kMinThreadCacheSize
;
3361 if (value
> (1<<30)) value
= (1<<30); // Limit to 1GB
3363 SpinLockHolder
l(&pageheap_lock
);
3364 overall_thread_cache_size
= static_cast<size_t>(value
);
3365 TCMalloc_ThreadCache::RecomputeThreadCacheSize();
3372 virtual void MarkThreadIdle() {
3373 TCMalloc_ThreadCache::BecomeIdle();
3376 virtual void ReleaseFreeMemory() {
3377 SpinLockHolder
h(&pageheap_lock
);
3378 pageheap
->ReleaseFreePages();
3383 // The constructor allocates an object to ensure that initialization
3384 // runs before main(), and therefore we do not have a chance to become
3385 // multi-threaded before initialization. We also create the TSD key
3386 // here. Presumably by the time this constructor runs, glibc is in
3387 // good enough shape to handle pthread_key_create().
3389 // The constructor also takes the opportunity to tell STL to use
3390 // tcmalloc. We want to do this early, before construct time, so
3391 // all user STL allocations go through tcmalloc (which works really
3394 // The destructor prints stats when the program exits.
3395 class TCMallocGuard
{
3399 #ifdef HAVE_TLS // this is true if the cc/ld/libc combo support TLS
3400 // Check whether the kernel also supports TLS (needs to happen at runtime)
3401 CheckIfKernelSupportsTLS();
3404 #ifdef WIN32 // patch the windows VirtualAlloc, etc.
3405 PatchWindowsFunctions(); // defined in windows/patch_functions.cc
3409 TCMalloc_ThreadCache::InitTSD();
3412 MallocExtension::Register(new TCMallocImplementation
);
3418 const char* env
= getenv("MALLOCSTATS");
3420 int level
= atoi(env
);
3421 if (level
< 1) level
= 1;
3425 UnpatchWindowsFunctions();
3432 static TCMallocGuard module_enter_exit_hook
;
3436 //-------------------------------------------------------------------
3437 // Helpers for the exported routines below
3438 //-------------------------------------------------------------------
3442 static Span
* DoSampledAllocation(size_t size
) {
3444 // Grab the stack trace outside the heap lock
3446 tmp
.depth
= GetStackTrace(tmp
.stack
, kMaxStackDepth
, 1);
3449 SpinLockHolder
h(&pageheap_lock
);
3451 Span
*span
= pageheap
->New(pages(size
== 0 ? 1 : size
));
3456 // Allocate stack trace
3457 StackTrace
*stack
= stacktrace_allocator
.New();
3458 if (stack
== NULL
) {
3459 // Sampling failed because of lack of memory
3465 span
->objects
= stack
;
3466 DLL_Prepend(&sampled_objects
, span
);
3472 static inline bool CheckCachedSizeClass(void *ptr
) {
3473 PageID p
= reinterpret_cast<uintptr_t>(ptr
) >> kPageShift
;
3474 size_t cached_value
= pageheap
->GetSizeClassIfCached(p
);
3475 return cached_value
== 0 ||
3476 cached_value
== pageheap
->GetDescriptor(p
)->sizeclass
;
3479 static inline void* CheckedMallocResult(void *result
)
3481 ASSERT(result
== 0 || CheckCachedSizeClass(result
));
3485 static inline void* SpanToMallocResult(Span
*span
) {
3486 ASSERT_SPAN_COMMITTED(span
);
3487 pageheap
->CacheSizeClass(span
->start
, 0);
3489 CheckedMallocResult(reinterpret_cast<void*>(span
->start
<< kPageShift
));
3493 template <bool crashOnFailure
>
3495 static ALWAYS_INLINE
void* do_malloc(size_t size
) {
3499 ASSERT(!isForbidden());
3502 // The following call forces module initialization
3503 TCMalloc_ThreadCache
* heap
= TCMalloc_ThreadCache::GetCache();
3505 if ((FLAGS_tcmalloc_sample_parameter
> 0) && heap
->SampleAllocation(size
)) {
3506 Span
* span
= DoSampledAllocation(size
);
3508 ret
= SpanToMallocResult(span
);
3512 if (size
> kMaxSize
) {
3513 // Use page-level allocator
3514 SpinLockHolder
h(&pageheap_lock
);
3515 Span
* span
= pageheap
->New(pages(size
));
3517 ret
= SpanToMallocResult(span
);
3520 // The common case, and also the simplest. This just pops the
3521 // size-appropriate freelist, afer replenishing it if it's empty.
3522 ret
= CheckedMallocResult(heap
->Allocate(size
));
3526 if (crashOnFailure
) // This branch should be optimized out by the compiler.
3535 static ALWAYS_INLINE
void do_free(void* ptr
) {
3536 if (ptr
== NULL
) return;
3537 ASSERT(pageheap
!= NULL
); // Should not call free() before malloc()
3538 const PageID p
= reinterpret_cast<uintptr_t>(ptr
) >> kPageShift
;
3540 size_t cl
= pageheap
->GetSizeClassIfCached(p
);
3543 span
= pageheap
->GetDescriptor(p
);
3544 cl
= span
->sizeclass
;
3545 pageheap
->CacheSizeClass(p
, cl
);
3548 #ifndef NO_TCMALLOC_SAMPLES
3549 ASSERT(!pageheap
->GetDescriptor(p
)->sample
);
3551 TCMalloc_ThreadCache
* heap
= TCMalloc_ThreadCache::GetCacheIfPresent();
3553 heap
->Deallocate(ptr
, cl
);
3555 // Delete directly into central cache
3556 SLL_SetNext(ptr
, NULL
);
3557 central_cache
[cl
].InsertRange(ptr
, ptr
, 1);
3560 SpinLockHolder
h(&pageheap_lock
);
3561 ASSERT(reinterpret_cast<uintptr_t>(ptr
) % kPageSize
== 0);
3562 ASSERT(span
!= NULL
&& span
->start
== p
);
3563 #ifndef NO_TCMALLOC_SAMPLES
3566 stacktrace_allocator
.Delete(reinterpret_cast<StackTrace
*>(span
->objects
));
3567 span
->objects
= NULL
;
3570 pageheap
->Delete(span
);
3575 // For use by exported routines below that want specific alignments
3577 // Note: this code can be slow, and can significantly fragment memory.
3578 // The expectation is that memalign/posix_memalign/valloc/pvalloc will
3579 // not be invoked very often. This requirement simplifies our
3580 // implementation and allows us to tune for expected allocation
3582 static void* do_memalign(size_t align
, size_t size
) {
3583 ASSERT((align
& (align
- 1)) == 0);
3585 if (pageheap
== NULL
) TCMalloc_ThreadCache::InitModule();
3587 // Allocate at least one byte to avoid boundary conditions below
3588 if (size
== 0) size
= 1;
3590 if (size
<= kMaxSize
&& align
< kPageSize
) {
3591 // Search through acceptable size classes looking for one with
3592 // enough alignment. This depends on the fact that
3593 // InitSizeClasses() currently produces several size classes that
3594 // are aligned at powers of two. We will waste time and space if
3595 // we miss in the size class array, but that is deemed acceptable
3596 // since memalign() should be used rarely.
3597 size_t cl
= SizeClass(size
);
3598 while (cl
< kNumClasses
&& ((class_to_size
[cl
] & (align
- 1)) != 0)) {
3601 if (cl
< kNumClasses
) {
3602 TCMalloc_ThreadCache
* heap
= TCMalloc_ThreadCache::GetCache();
3603 return CheckedMallocResult(heap
->Allocate(class_to_size
[cl
]));
3607 // We will allocate directly from the page heap
3608 SpinLockHolder
h(&pageheap_lock
);
3610 if (align
<= kPageSize
) {
3611 // Any page-level allocation will be fine
3612 // TODO: We could put the rest of this page in the appropriate
3613 // TODO: cache but it does not seem worth it.
3614 Span
* span
= pageheap
->New(pages(size
));
3615 return span
== NULL
? NULL
: SpanToMallocResult(span
);
3618 // Allocate extra pages and carve off an aligned portion
3619 const Length alloc
= pages(size
+ align
);
3620 Span
* span
= pageheap
->New(alloc
);
3621 if (span
== NULL
) return NULL
;
3623 // Skip starting portion so that we end up aligned
3625 while ((((span
->start
+skip
) << kPageShift
) & (align
- 1)) != 0) {
3628 ASSERT(skip
< alloc
);
3630 Span
* rest
= pageheap
->Split(span
, skip
);
3631 pageheap
->Delete(span
);
3635 // Skip trailing portion that we do not need to return
3636 const Length needed
= pages(size
);
3637 ASSERT(span
->length
>= needed
);
3638 if (span
->length
> needed
) {
3639 Span
* trailer
= pageheap
->Split(span
, needed
);
3640 pageheap
->Delete(trailer
);
3642 return SpanToMallocResult(span
);
3646 // Helpers for use by exported routines below:
3649 static inline void do_malloc_stats() {
3654 static inline int do_mallopt(int, int) {
3655 return 1; // Indicates error
3658 #ifdef HAVE_STRUCT_MALLINFO // mallinfo isn't defined on freebsd, for instance
3659 static inline struct mallinfo
do_mallinfo() {
3660 TCMallocStats stats
;
3661 ExtractStats(&stats
, NULL
);
3663 // Just some of the fields are filled in.
3664 struct mallinfo info
;
3665 memset(&info
, 0, sizeof(info
));
3667 // Unfortunately, the struct contains "int" field, so some of the
3668 // size values will be truncated.
3669 info
.arena
= static_cast<int>(stats
.system_bytes
);
3670 info
.fsmblks
= static_cast<int>(stats
.thread_bytes
3671 + stats
.central_bytes
3672 + stats
.transfer_bytes
);
3673 info
.fordblks
= static_cast<int>(stats
.pageheap_bytes
);
3674 info
.uordblks
= static_cast<int>(stats
.system_bytes
3675 - stats
.thread_bytes
3676 - stats
.central_bytes
3677 - stats
.transfer_bytes
3678 - stats
.pageheap_bytes
);
3684 //-------------------------------------------------------------------
3685 // Exported routines
3686 //-------------------------------------------------------------------
3688 // CAVEAT: The code structure below ensures that MallocHook methods are always
3689 // called from the stack frame of the invoked allocation function.
3690 // heap-checker.cc depends on this to start a stack trace from
3691 // the call to the (de)allocation function.
3696 #define do_malloc do_malloc<crashOnFailure>
3698 template <bool crashOnFailure
>
3699 ALWAYS_INLINE
void* malloc(size_t);
3701 void* fastMalloc(size_t size
)
3703 return malloc
<true>(size
);
3706 TryMallocReturnValue
tryFastMalloc(size_t size
)
3708 return malloc
<false>(size
);
3711 template <bool crashOnFailure
>
3714 void* malloc(size_t size
) {
3715 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3716 if (std::numeric_limits
<size_t>::max() - sizeof(AllocAlignmentInteger
) <= size
) // If overflow would occur...
3718 size
+= sizeof(AllocAlignmentInteger
);
3719 void* result
= do_malloc(size
);
3723 *static_cast<AllocAlignmentInteger
*>(result
) = Internal::AllocTypeMalloc
;
3724 result
= static_cast<AllocAlignmentInteger
*>(result
) + 1;
3726 void* result
= do_malloc(size
);
3730 MallocHook::InvokeNewHook(result
, size
);
3738 void free(void* ptr
) {
3740 MallocHook::InvokeDeleteHook(ptr
);
3743 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3747 AllocAlignmentInteger
* header
= Internal::fastMallocMatchValidationValue(ptr
);
3748 if (*header
!= Internal::AllocTypeMalloc
)
3749 Internal::fastMallocMatchFailed(ptr
);
3759 template <bool crashOnFailure
>
3760 ALWAYS_INLINE
void* calloc(size_t, size_t);
3762 void* fastCalloc(size_t n
, size_t elem_size
)
3764 return calloc
<true>(n
, elem_size
);
3767 TryMallocReturnValue
tryFastCalloc(size_t n
, size_t elem_size
)
3769 return calloc
<false>(n
, elem_size
);
3772 template <bool crashOnFailure
>
3775 void* calloc(size_t n
, size_t elem_size
) {
3776 size_t totalBytes
= n
* elem_size
;
3778 // Protect against overflow
3779 if (n
> 1 && elem_size
&& (totalBytes
/ elem_size
) != n
)
3782 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3783 if (std::numeric_limits
<size_t>::max() - sizeof(AllocAlignmentInteger
) <= totalBytes
) // If overflow would occur...
3786 totalBytes
+= sizeof(AllocAlignmentInteger
);
3787 void* result
= do_malloc(totalBytes
);
3791 memset(result
, 0, totalBytes
);
3792 *static_cast<AllocAlignmentInteger
*>(result
) = Internal::AllocTypeMalloc
;
3793 result
= static_cast<AllocAlignmentInteger
*>(result
) + 1;
3795 void* result
= do_malloc(totalBytes
);
3796 if (result
!= NULL
) {
3797 memset(result
, 0, totalBytes
);
3802 MallocHook::InvokeNewHook(result
, totalBytes
);
3807 // Since cfree isn't used anywhere, we don't compile it in.
3812 void cfree(void* ptr
) {
3814 MallocHook::InvokeDeleteHook(ptr
);
3823 template <bool crashOnFailure
>
3824 ALWAYS_INLINE
void* realloc(void*, size_t);
3826 void* fastRealloc(void* old_ptr
, size_t new_size
)
3828 return realloc
<true>(old_ptr
, new_size
);
3831 TryMallocReturnValue
tryFastRealloc(void* old_ptr
, size_t new_size
)
3833 return realloc
<false>(old_ptr
, new_size
);
3836 template <bool crashOnFailure
>
3839 void* realloc(void* old_ptr
, size_t new_size
) {
3840 if (old_ptr
== NULL
) {
3841 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3842 void* result
= malloc(new_size
);
3844 void* result
= do_malloc(new_size
);
3846 MallocHook::InvokeNewHook(result
, new_size
);
3851 if (new_size
== 0) {
3853 MallocHook::InvokeDeleteHook(old_ptr
);
3859 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3860 if (std::numeric_limits
<size_t>::max() - sizeof(AllocAlignmentInteger
) <= new_size
) // If overflow would occur...
3862 new_size
+= sizeof(AllocAlignmentInteger
);
3863 AllocAlignmentInteger
* header
= Internal::fastMallocMatchValidationValue(old_ptr
);
3864 if (*header
!= Internal::AllocTypeMalloc
)
3865 Internal::fastMallocMatchFailed(old_ptr
);
3869 // Get the size of the old entry
3870 const PageID p
= reinterpret_cast<uintptr_t>(old_ptr
) >> kPageShift
;
3871 size_t cl
= pageheap
->GetSizeClassIfCached(p
);
3875 span
= pageheap
->GetDescriptor(p
);
3876 cl
= span
->sizeclass
;
3877 pageheap
->CacheSizeClass(p
, cl
);
3880 old_size
= ByteSizeForClass(cl
);
3882 ASSERT(span
!= NULL
);
3883 old_size
= span
->length
<< kPageShift
;
3886 // Reallocate if the new size is larger than the old size,
3887 // or if the new size is significantly smaller than the old size.
3888 if ((new_size
> old_size
) || (AllocationSize(new_size
) < old_size
)) {
3889 // Need to reallocate
3890 void* new_ptr
= do_malloc(new_size
);
3891 if (new_ptr
== NULL
) {
3895 MallocHook::InvokeNewHook(new_ptr
, new_size
);
3897 memcpy(new_ptr
, old_ptr
, ((old_size
< new_size
) ? old_size
: new_size
));
3899 MallocHook::InvokeDeleteHook(old_ptr
);
3901 // We could use a variant of do_free() that leverages the fact
3902 // that we already know the sizeclass of old_ptr. The benefit
3903 // would be small, so don't bother.
3905 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3906 new_ptr
= static_cast<AllocAlignmentInteger
*>(new_ptr
) + 1;
3910 #if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3911 old_ptr
= static_cast<AllocAlignmentInteger
*>(old_ptr
) + 1; // Set old_ptr back to the user pointer.
3921 static SpinLock set_new_handler_lock
= SPINLOCK_INITIALIZER
;
3923 static inline void* cpp_alloc(size_t size
, bool nothrow
) {
3925 void* p
= do_malloc(size
);
3929 if (p
== NULL
) { // allocation failed
3930 // Get the current new handler. NB: this function is not
3931 // thread-safe. We make a feeble stab at making it so here, but
3932 // this lock only protects against tcmalloc interfering with
3933 // itself, not with other libraries calling set_new_handler.
3934 std::new_handler nh
;
3936 SpinLockHolder
h(&set_new_handler_lock
);
3937 nh
= std::set_new_handler(0);
3938 (void) std::set_new_handler(nh
);
3940 // If no new_handler is established, the allocation failed.
3942 if (nothrow
) return 0;
3943 throw std::bad_alloc();
3945 // Otherwise, try the new_handler. If it returns, retry the
3946 // allocation. If it throws std::bad_alloc, fail the allocation.
3947 // if it throws something else, don't interfere.
3950 } catch (const std::bad_alloc
&) {
3951 if (!nothrow
) throw;
3954 } else { // allocation success
3961 #if ENABLE(GLOBAL_FASTMALLOC_NEW)
3963 void* operator new(size_t size
) {
3964 void* p
= cpp_alloc(size
, false);
3965 // We keep this next instruction out of cpp_alloc for a reason: when
3966 // it's in, and new just calls cpp_alloc, the optimizer may fold the
3967 // new call into cpp_alloc, which messes up our whole section-based
3968 // stacktracing (see ATTRIBUTE_SECTION, above). This ensures cpp_alloc
3969 // isn't the last thing this fn calls, and prevents the folding.
3970 MallocHook::InvokeNewHook(p
, size
);
3974 void* operator new(size_t size
, const std::nothrow_t
&) __THROW
{
3975 void* p
= cpp_alloc(size
, true);
3976 MallocHook::InvokeNewHook(p
, size
);
3980 void operator delete(void* p
) __THROW
{
3981 MallocHook::InvokeDeleteHook(p
);
3985 void operator delete(void* p
, const std::nothrow_t
&) __THROW
{
3986 MallocHook::InvokeDeleteHook(p
);
3990 void* operator new[](size_t size
) {
3991 void* p
= cpp_alloc(size
, false);
3992 // We keep this next instruction out of cpp_alloc for a reason: when
3993 // it's in, and new just calls cpp_alloc, the optimizer may fold the
3994 // new call into cpp_alloc, which messes up our whole section-based
3995 // stacktracing (see ATTRIBUTE_SECTION, above). This ensures cpp_alloc
3996 // isn't the last thing this fn calls, and prevents the folding.
3997 MallocHook::InvokeNewHook(p
, size
);
4001 void* operator new[](size_t size
, const std::nothrow_t
&) __THROW
{
4002 void* p
= cpp_alloc(size
, true);
4003 MallocHook::InvokeNewHook(p
, size
);
4007 void operator delete[](void* p
) __THROW
{
4008 MallocHook::InvokeDeleteHook(p
);
4012 void operator delete[](void* p
, const std::nothrow_t
&) __THROW
{
4013 MallocHook::InvokeDeleteHook(p
);
4019 extern "C" void* memalign(size_t align
, size_t size
) __THROW
{
4020 void* result
= do_memalign(align
, size
);
4021 MallocHook::InvokeNewHook(result
, size
);
4025 extern "C" int posix_memalign(void** result_ptr
, size_t align
, size_t size
)
4027 if (((align
% sizeof(void*)) != 0) ||
4028 ((align
& (align
- 1)) != 0) ||
4033 void* result
= do_memalign(align
, size
);
4034 MallocHook::InvokeNewHook(result
, size
);
4035 if (result
== NULL
) {
4038 *result_ptr
= result
;
4043 static size_t pagesize
= 0;
4045 extern "C" void* valloc(size_t size
) __THROW
{
4046 // Allocate page-aligned object of length >= size bytes
4047 if (pagesize
== 0) pagesize
= getpagesize();
4048 void* result
= do_memalign(pagesize
, size
);
4049 MallocHook::InvokeNewHook(result
, size
);
4053 extern "C" void* pvalloc(size_t size
) __THROW
{
4054 // Round up size to a multiple of pagesize
4055 if (pagesize
== 0) pagesize
= getpagesize();
4056 size
= (size
+ pagesize
- 1) & ~(pagesize
- 1);
4057 void* result
= do_memalign(pagesize
, size
);
4058 MallocHook::InvokeNewHook(result
, size
);
4062 extern "C" void malloc_stats(void) {
4066 extern "C" int mallopt(int cmd
, int value
) {
4067 return do_mallopt(cmd
, value
);
4070 #ifdef HAVE_STRUCT_MALLINFO
4071 extern "C" struct mallinfo
mallinfo(void) {
4072 return do_mallinfo();
4076 //-------------------------------------------------------------------
4077 // Some library routines on RedHat 9 allocate memory using malloc()
4078 // and free it using __libc_free() (or vice-versa). Since we provide
4079 // our own implementations of malloc/free, we need to make sure that
4080 // the __libc_XXX variants (defined as part of glibc) also point to
4081 // the same implementations.
4082 //-------------------------------------------------------------------
4084 #if defined(__GLIBC__)
4086 #if COMPILER(GCC) && !defined(__MACH__) && defined(HAVE___ATTRIBUTE__)
4087 // Potentially faster variants that use the gcc alias extension.
4088 // Mach-O (Darwin) does not support weak aliases, hence the __MACH__ check.
4089 # define ALIAS(x) __attribute__ ((weak, alias (x)))
4090 void* __libc_malloc(size_t size
) ALIAS("malloc");
4091 void __libc_free(void* ptr
) ALIAS("free");
4092 void* __libc_realloc(void* ptr
, size_t size
) ALIAS("realloc");
4093 void* __libc_calloc(size_t n
, size_t size
) ALIAS("calloc");
4094 void __libc_cfree(void* ptr
) ALIAS("cfree");
4095 void* __libc_memalign(size_t align
, size_t s
) ALIAS("memalign");
4096 void* __libc_valloc(size_t size
) ALIAS("valloc");
4097 void* __libc_pvalloc(size_t size
) ALIAS("pvalloc");
4098 int __posix_memalign(void** r
, size_t a
, size_t s
) ALIAS("posix_memalign");
4100 # else /* not __GNUC__ */
4101 // Portable wrappers
4102 void* __libc_malloc(size_t size
) { return malloc(size
); }
4103 void __libc_free(void* ptr
) { free(ptr
); }
4104 void* __libc_realloc(void* ptr
, size_t size
) { return realloc(ptr
, size
); }
4105 void* __libc_calloc(size_t n
, size_t size
) { return calloc(n
, size
); }
4106 void __libc_cfree(void* ptr
) { cfree(ptr
); }
4107 void* __libc_memalign(size_t align
, size_t s
) { return memalign(align
, s
); }
4108 void* __libc_valloc(size_t size
) { return valloc(size
); }
4109 void* __libc_pvalloc(size_t size
) { return pvalloc(size
); }
4110 int __posix_memalign(void** r
, size_t a
, size_t s
) {
4111 return posix_memalign(r
, a
, s
);
4113 # endif /* __GNUC__ */
4115 #endif /* __GLIBC__ */
4117 // Override __libc_memalign in libc on linux boxes specially.
4118 // They have a bug in libc that causes them to (very rarely) allocate
4119 // with __libc_memalign() yet deallocate with free() and the
4120 // definitions above don't catch it.
4121 // This function is an exception to the rule of calling MallocHook method
4122 // from the stack frame of the allocation function;
4123 // heap-checker handles this special case explicitly.
4124 static void *MemalignOverride(size_t align
, size_t size
, const void *caller
)
4126 void* result
= do_memalign(align
, size
);
4127 MallocHook::InvokeNewHook(result
, size
);
4130 void *(*__memalign_hook
)(size_t, size_t, const void *) = MemalignOverride
;
4135 void releaseFastMallocFreeMemory()
4137 // Flush free pages in the current thread cache back to the page heap.
4138 // Low watermark mechanism in Scavenge() prevents full return on the first pass.
4139 // The second pass flushes everything.
4140 if (TCMalloc_ThreadCache
* threadCache
= TCMalloc_ThreadCache::GetCacheIfPresent()) {
4141 threadCache
->Scavenge();
4142 threadCache
->Scavenge();
4145 SpinLockHolder
h(&pageheap_lock
);
4146 pageheap
->ReleaseFreePages();
4149 FastMallocStatistics
fastMallocStatistics()
4151 FastMallocStatistics statistics
;
4153 SpinLockHolder
lockHolder(&pageheap_lock
);
4154 statistics
.reservedVMBytes
= static_cast<size_t>(pageheap
->SystemBytes());
4155 statistics
.committedVMBytes
= statistics
.reservedVMBytes
- pageheap
->ReturnedBytes();
4157 statistics
.freeListBytes
= 0;
4158 for (unsigned cl
= 0; cl
< kNumClasses
; ++cl
) {
4159 const int length
= central_cache
[cl
].length();
4160 const int tc_length
= central_cache
[cl
].tc_length();
4162 statistics
.freeListBytes
+= ByteSizeForClass(cl
) * (length
+ tc_length
);
4164 for (TCMalloc_ThreadCache
* threadCache
= thread_heaps
; threadCache
; threadCache
= threadCache
->next_
)
4165 statistics
.freeListBytes
+= threadCache
->Size();
4170 size_t fastMallocSize(const void* ptr
)
4172 const PageID p
= reinterpret_cast<uintptr_t>(ptr
) >> kPageShift
;
4173 Span
* span
= pageheap
->GetDescriptorEnsureSafe(p
);
4175 if (!span
|| span
->free
)
4178 for (void* free
= span
->objects
; free
!= NULL
; free
= *((void**) free
)) {
4183 if (size_t cl
= span
->sizeclass
)
4184 return ByteSizeForClass(cl
);
4186 return span
->length
<< kPageShift
;
4191 class FreeObjectFinder
{
4192 const RemoteMemoryReader
& m_reader
;
4193 HashSet
<void*> m_freeObjects
;
4196 FreeObjectFinder(const RemoteMemoryReader
& reader
) : m_reader(reader
) { }
4198 void visit(void* ptr
) { m_freeObjects
.add(ptr
); }
4199 bool isFreeObject(void* ptr
) const { return m_freeObjects
.contains(ptr
); }
4200 bool isFreeObject(vm_address_t ptr
) const { return isFreeObject(reinterpret_cast<void*>(ptr
)); }
4201 size_t freeObjectCount() const { return m_freeObjects
.size(); }
4203 void findFreeObjects(TCMalloc_ThreadCache
* threadCache
)
4205 for (; threadCache
; threadCache
= (threadCache
->next_
? m_reader(threadCache
->next_
) : 0))
4206 threadCache
->enumerateFreeObjects(*this, m_reader
);
4209 void findFreeObjects(TCMalloc_Central_FreeListPadded
* centralFreeList
, size_t numSizes
, TCMalloc_Central_FreeListPadded
* remoteCentralFreeList
)
4211 for (unsigned i
= 0; i
< numSizes
; i
++)
4212 centralFreeList
[i
].enumerateFreeObjects(*this, m_reader
, remoteCentralFreeList
+ i
);
4216 class PageMapFreeObjectFinder
{
4217 const RemoteMemoryReader
& m_reader
;
4218 FreeObjectFinder
& m_freeObjectFinder
;
4221 PageMapFreeObjectFinder(const RemoteMemoryReader
& reader
, FreeObjectFinder
& freeObjectFinder
)
4223 , m_freeObjectFinder(freeObjectFinder
)
4226 int visit(void* ptr
) const
4231 Span
* span
= m_reader(reinterpret_cast<Span
*>(ptr
));
4233 void* ptr
= reinterpret_cast<void*>(span
->start
<< kPageShift
);
4234 m_freeObjectFinder
.visit(ptr
);
4235 } else if (span
->sizeclass
) {
4236 // Walk the free list of the small-object span, keeping track of each object seen
4237 for (void* nextObject
= span
->objects
; nextObject
; nextObject
= *m_reader(reinterpret_cast<void**>(nextObject
)))
4238 m_freeObjectFinder
.visit(nextObject
);
4240 return span
->length
;
4244 class PageMapMemoryUsageRecorder
{
4247 unsigned m_typeMask
;
4248 vm_range_recorder_t
* m_recorder
;
4249 const RemoteMemoryReader
& m_reader
;
4250 const FreeObjectFinder
& m_freeObjectFinder
;
4252 HashSet
<void*> m_seenPointers
;
4253 Vector
<Span
*> m_coalescedSpans
;
4256 PageMapMemoryUsageRecorder(task_t task
, void* context
, unsigned typeMask
, vm_range_recorder_t
* recorder
, const RemoteMemoryReader
& reader
, const FreeObjectFinder
& freeObjectFinder
)
4258 , m_context(context
)
4259 , m_typeMask(typeMask
)
4260 , m_recorder(recorder
)
4262 , m_freeObjectFinder(freeObjectFinder
)
4265 ~PageMapMemoryUsageRecorder()
4267 ASSERT(!m_coalescedSpans
.size());
4270 void recordPendingRegions()
4272 Span
* lastSpan
= m_coalescedSpans
[m_coalescedSpans
.size() - 1];
4273 vm_range_t ptrRange
= { m_coalescedSpans
[0]->start
<< kPageShift
, 0 };
4274 ptrRange
.size
= (lastSpan
->start
<< kPageShift
) - ptrRange
.address
+ (lastSpan
->length
* kPageSize
);
4276 // Mark the memory region the spans represent as a candidate for containing pointers
4277 if (m_typeMask
& MALLOC_PTR_REGION_RANGE_TYPE
)
4278 (*m_recorder
)(m_task
, m_context
, MALLOC_PTR_REGION_RANGE_TYPE
, &ptrRange
, 1);
4280 if (!(m_typeMask
& MALLOC_PTR_IN_USE_RANGE_TYPE
)) {
4281 m_coalescedSpans
.clear();
4285 Vector
<vm_range_t
, 1024> allocatedPointers
;
4286 for (size_t i
= 0; i
< m_coalescedSpans
.size(); ++i
) {
4287 Span
*theSpan
= m_coalescedSpans
[i
];
4291 vm_address_t spanStartAddress
= theSpan
->start
<< kPageShift
;
4292 vm_size_t spanSizeInBytes
= theSpan
->length
* kPageSize
;
4294 if (!theSpan
->sizeclass
) {
4295 // If it's an allocated large object span, mark it as in use
4296 if (!m_freeObjectFinder
.isFreeObject(spanStartAddress
))
4297 allocatedPointers
.append((vm_range_t
){spanStartAddress
, spanSizeInBytes
});
4299 const size_t objectSize
= ByteSizeForClass(theSpan
->sizeclass
);
4301 // Mark each allocated small object within the span as in use
4302 const vm_address_t endOfSpan
= spanStartAddress
+ spanSizeInBytes
;
4303 for (vm_address_t object
= spanStartAddress
; object
+ objectSize
<= endOfSpan
; object
+= objectSize
) {
4304 if (!m_freeObjectFinder
.isFreeObject(object
))
4305 allocatedPointers
.append((vm_range_t
){object
, objectSize
});
4310 (*m_recorder
)(m_task
, m_context
, MALLOC_PTR_IN_USE_RANGE_TYPE
, allocatedPointers
.data(), allocatedPointers
.size());
4312 m_coalescedSpans
.clear();
4315 int visit(void* ptr
)
4320 Span
* span
= m_reader(reinterpret_cast<Span
*>(ptr
));
4324 if (m_seenPointers
.contains(ptr
))
4325 return span
->length
;
4326 m_seenPointers
.add(ptr
);
4328 if (!m_coalescedSpans
.size()) {
4329 m_coalescedSpans
.append(span
);
4330 return span
->length
;
4333 Span
* previousSpan
= m_coalescedSpans
[m_coalescedSpans
.size() - 1];
4334 vm_address_t previousSpanStartAddress
= previousSpan
->start
<< kPageShift
;
4335 vm_size_t previousSpanSizeInBytes
= previousSpan
->length
* kPageSize
;
4337 // If the new span is adjacent to the previous span, do nothing for now.
4338 vm_address_t spanStartAddress
= span
->start
<< kPageShift
;
4339 if (spanStartAddress
== previousSpanStartAddress
+ previousSpanSizeInBytes
) {
4340 m_coalescedSpans
.append(span
);
4341 return span
->length
;
4344 // New span is not adjacent to previous span, so record the spans coalesced so far.
4345 recordPendingRegions();
4346 m_coalescedSpans
.append(span
);
4348 return span
->length
;
4352 class AdminRegionRecorder
{
4355 unsigned m_typeMask
;
4356 vm_range_recorder_t
* m_recorder
;
4357 const RemoteMemoryReader
& m_reader
;
4359 Vector
<vm_range_t
, 1024> m_pendingRegions
;
4362 AdminRegionRecorder(task_t task
, void* context
, unsigned typeMask
, vm_range_recorder_t
* recorder
, const RemoteMemoryReader
& reader
)
4364 , m_context(context
)
4365 , m_typeMask(typeMask
)
4366 , m_recorder(recorder
)
4370 void recordRegion(vm_address_t ptr
, size_t size
)
4372 if (m_typeMask
& MALLOC_ADMIN_REGION_RANGE_TYPE
)
4373 m_pendingRegions
.append((vm_range_t
){ ptr
, size
});
4376 void visit(void *ptr
, size_t size
)
4378 recordRegion(reinterpret_cast<vm_address_t
>(ptr
), size
);
4381 void recordPendingRegions()
4383 if (m_pendingRegions
.size()) {
4384 (*m_recorder
)(m_task
, m_context
, MALLOC_ADMIN_REGION_RANGE_TYPE
, m_pendingRegions
.data(), m_pendingRegions
.size());
4385 m_pendingRegions
.clear();
4389 ~AdminRegionRecorder()
4391 ASSERT(!m_pendingRegions
.size());
4395 kern_return_t
FastMallocZone::enumerate(task_t task
, void* context
, unsigned typeMask
, vm_address_t zoneAddress
, memory_reader_t reader
, vm_range_recorder_t recorder
)
4397 RemoteMemoryReader
memoryReader(task
, reader
);
4401 FastMallocZone
* mzone
= memoryReader(reinterpret_cast<FastMallocZone
*>(zoneAddress
));
4402 TCMalloc_PageHeap
* pageHeap
= memoryReader(mzone
->m_pageHeap
);
4403 TCMalloc_ThreadCache
** threadHeapsPointer
= memoryReader(mzone
->m_threadHeaps
);
4404 TCMalloc_ThreadCache
* threadHeaps
= memoryReader(*threadHeapsPointer
);
4406 TCMalloc_Central_FreeListPadded
* centralCaches
= memoryReader(mzone
->m_centralCaches
, sizeof(TCMalloc_Central_FreeListPadded
) * kNumClasses
);
4408 FreeObjectFinder
finder(memoryReader
);
4409 finder
.findFreeObjects(threadHeaps
);
4410 finder
.findFreeObjects(centralCaches
, kNumClasses
, mzone
->m_centralCaches
);
4412 TCMalloc_PageHeap::PageMap
* pageMap
= &pageHeap
->pagemap_
;
4413 PageMapFreeObjectFinder
pageMapFinder(memoryReader
, finder
);
4414 pageMap
->visitValues(pageMapFinder
, memoryReader
);
4416 PageMapMemoryUsageRecorder
usageRecorder(task
, context
, typeMask
, recorder
, memoryReader
, finder
);
4417 pageMap
->visitValues(usageRecorder
, memoryReader
);
4418 usageRecorder
.recordPendingRegions();
4420 AdminRegionRecorder
adminRegionRecorder(task
, context
, typeMask
, recorder
, memoryReader
);
4421 pageMap
->visitAllocations(adminRegionRecorder
, memoryReader
);
4423 PageHeapAllocator
<Span
>* spanAllocator
= memoryReader(mzone
->m_spanAllocator
);
4424 PageHeapAllocator
<TCMalloc_ThreadCache
>* pageHeapAllocator
= memoryReader(mzone
->m_pageHeapAllocator
);
4426 spanAllocator
->recordAdministrativeRegions(adminRegionRecorder
, memoryReader
);
4427 pageHeapAllocator
->recordAdministrativeRegions(adminRegionRecorder
, memoryReader
);
4429 adminRegionRecorder
.recordPendingRegions();
4434 size_t FastMallocZone::size(malloc_zone_t
*, const void*)
4439 void* FastMallocZone::zoneMalloc(malloc_zone_t
*, size_t)
4444 void* FastMallocZone::zoneCalloc(malloc_zone_t
*, size_t, size_t)
4449 void FastMallocZone::zoneFree(malloc_zone_t
*, void* ptr
)
4451 // Due to <rdar://problem/5671357> zoneFree may be called by the system free even if the pointer
4452 // is not in this zone. When this happens, the pointer being freed was not allocated by any
4453 // zone so we need to print a useful error for the application developer.
4454 malloc_printf("*** error for object %p: pointer being freed was not allocated\n", ptr
);
4457 void* FastMallocZone::zoneRealloc(malloc_zone_t
*, void*, size_t)
4469 malloc_introspection_t jscore_fastmalloc_introspection
= { &FastMallocZone::enumerate
, &FastMallocZone::goodSize
, &FastMallocZone::check
, &FastMallocZone::print
,
4470 &FastMallocZone::log
, &FastMallocZone::forceLock
, &FastMallocZone::forceUnlock
, &FastMallocZone::statistics
4472 , 0 // zone_locked will not be called on the zone unless it advertises itself as version five or higher.
4477 FastMallocZone::FastMallocZone(TCMalloc_PageHeap
* pageHeap
, TCMalloc_ThreadCache
** threadHeaps
, TCMalloc_Central_FreeListPadded
* centralCaches
, PageHeapAllocator
<Span
>* spanAllocator
, PageHeapAllocator
<TCMalloc_ThreadCache
>* pageHeapAllocator
)
4478 : m_pageHeap(pageHeap
)
4479 , m_threadHeaps(threadHeaps
)
4480 , m_centralCaches(centralCaches
)
4481 , m_spanAllocator(spanAllocator
)
4482 , m_pageHeapAllocator(pageHeapAllocator
)
4484 memset(&m_zone
, 0, sizeof(m_zone
));
4486 m_zone
.zone_name
= "JavaScriptCore FastMalloc";
4487 m_zone
.size
= &FastMallocZone::size
;
4488 m_zone
.malloc
= &FastMallocZone::zoneMalloc
;
4489 m_zone
.calloc
= &FastMallocZone::zoneCalloc
;
4490 m_zone
.realloc
= &FastMallocZone::zoneRealloc
;
4491 m_zone
.free
= &FastMallocZone::zoneFree
;
4492 m_zone
.valloc
= &FastMallocZone::zoneValloc
;
4493 m_zone
.destroy
= &FastMallocZone::zoneDestroy
;
4494 m_zone
.introspect
= &jscore_fastmalloc_introspection
;
4495 malloc_zone_register(&m_zone
);
4499 void FastMallocZone::init()
4501 static FastMallocZone
zone(pageheap
, &thread_heaps
, static_cast<TCMalloc_Central_FreeListPadded
*>(central_cache
), &span_allocator
, &threadheap_allocator
);
4504 #endif // OS(DARWIN)
4507 #endif // WTF_CHANGES
4509 #endif // FORCE_SYSTEM_MALLOC