source: webkit/trunk/JavaScriptCore/wtf/FastMalloc.cpp@ 65104

Last change on this file since 65104 was 65091, checked in by [email protected], 15 years ago

2010-08-10 Patrick Gansterer <[email protected]>

Reviewed by Eric Seidel.

Make FastMalloc more portable.
https://bugs.webkit.org/show_bug.cgi?id=41790

  • wtf/FastMalloc.cpp: (WTF::TCMalloc_Central_FreeList::Populate): (WTF::TCMalloc_ThreadCache::CreateCacheIfNecessary):
  • Property svn:eol-style set to native
File size: 141.3 KB
Line 
1// Copyright (c) 2005, 2007, Google Inc.
2// All rights reserved.
3// Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9// * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11// * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15// * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31// ---
32// Author: Sanjay Ghemawat <[email protected]>
33//
34// A malloc that uses a per-thread cache to satisfy small malloc requests.
35// (The time for malloc/free of a small object drops from 300 ns to 50 ns.)
36//
37// See doc/tcmalloc.html for a high-level
38// description of how this malloc works.
39//
40// SYNCHRONIZATION
41// 1. The thread-specific lists are accessed without acquiring any locks.
42// This is safe because each such list is only accessed by one thread.
43// 2. We have a lock per central free-list, and hold it while manipulating
44// the central free list for a particular size.
45// 3. The central page allocator is protected by "pageheap_lock".
46// 4. The pagemap (which maps from page-number to descriptor),
47// can be read without holding any locks, and written while holding
48// the "pageheap_lock".
49// 5. To improve performance, a subset of the information one can get
50// from the pagemap is cached in a data structure, pagemap_cache_,
51// that atomically reads and writes its entries. This cache can be
52// read and written without locking.
53//
54// This multi-threaded access to the pagemap is safe for fairly
55// subtle reasons. We basically assume that when an object X is
56// allocated by thread A and deallocated by thread B, there must
57// have been appropriate synchronization in the handoff of object
58// X from thread A to thread B. The same logic applies to pagemap_cache_.
59//
60// THE PAGEID-TO-SIZECLASS CACHE
61// Hot PageID-to-sizeclass mappings are held by pagemap_cache_. If this cache
62// returns 0 for a particular PageID then that means "no information," not that
63// the sizeclass is 0. The cache may have stale information for pages that do
64// not hold the beginning of any free()'able object. Staleness is eliminated
65// in Populate() for pages with sizeclass > 0 objects, and in do_malloc() and
66// do_memalign() for all other relevant pages.
67//
68// TODO: Bias reclamation to larger addresses
69// TODO: implement mallinfo/mallopt
70// TODO: Better testing
71//
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.
76
77#include "config.h"
78#include "FastMalloc.h"
79
80#include "Assertions.h"
81#include <limits>
82#if ENABLE(JSC_MULTIPLE_THREADS)
83#include <pthread.h>
84#endif
85
86#ifndef NO_TCMALLOC_SAMPLES
87#ifdef WTF_CHANGES
88#define NO_TCMALLOC_SAMPLES
89#endif
90#endif
91
92#if !(defined(USE_SYSTEM_MALLOC) && USE_SYSTEM_MALLOC) && defined(NDEBUG)
93#define FORCE_SYSTEM_MALLOC 0
94#else
95#define FORCE_SYSTEM_MALLOC 1
96#endif
97
98// Use a background thread to periodically scavenge memory to release back to the system
99// 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.
100#if defined(BUILDING_ON_TIGER)
101#define USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY 0
102#else
103#define USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY 1
104#endif
105
106#ifndef NDEBUG
107namespace WTF {
108
109#if ENABLE(JSC_MULTIPLE_THREADS)
110static pthread_key_t isForbiddenKey;
111static pthread_once_t isForbiddenKeyOnce = PTHREAD_ONCE_INIT;
112static void initializeIsForbiddenKey()
113{
114 pthread_key_create(&isForbiddenKey, 0);
115}
116
117#if !ASSERT_DISABLED
118static bool isForbidden()
119{
120 pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
121 return !!pthread_getspecific(isForbiddenKey);
122}
123#endif
124
125void fastMallocForbid()
126{
127 pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
128 pthread_setspecific(isForbiddenKey, &isForbiddenKey);
129}
130
131void fastMallocAllow()
132{
133 pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
134 pthread_setspecific(isForbiddenKey, 0);
135}
136
137#else
138
139static bool staticIsForbidden;
140static bool isForbidden()
141{
142 return staticIsForbidden;
143}
144
145void fastMallocForbid()
146{
147 staticIsForbidden = true;
148}
149
150void fastMallocAllow()
151{
152 staticIsForbidden = false;
153}
154#endif // ENABLE(JSC_MULTIPLE_THREADS)
155
156} // namespace WTF
157#endif // NDEBUG
158
159#include <string.h>
160
161namespace WTF {
162
163#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
164
165namespace Internal {
166
167void fastMallocMatchFailed(void*)
168{
169 CRASH();
170}
171
172} // namespace Internal
173
174#endif
175
176void* fastZeroedMalloc(size_t n)
177{
178 void* result = fastMalloc(n);
179 memset(result, 0, n);
180 return result;
181}
182
183char* fastStrDup(const char* src)
184{
185 int len = strlen(src) + 1;
186 char* dup = static_cast<char*>(fastMalloc(len));
187
188 if (dup)
189 memcpy(dup, src, len);
190
191 return dup;
192}
193
194TryMallocReturnValue tryFastZeroedMalloc(size_t n)
195{
196 void* result;
197 if (!tryFastMalloc(n).getValue(result))
198 return 0;
199 memset(result, 0, n);
200 return result;
201}
202
203} // namespace WTF
204
205#if FORCE_SYSTEM_MALLOC
206
207#if PLATFORM(BREWMP)
208#include "brew/SystemMallocBrew.h"
209#endif
210
211#if OS(DARWIN)
212#include <malloc/malloc.h>
213#elif COMPILER(MSVC)
214#include <malloc.h>
215#endif
216
217namespace WTF {
218
219TryMallocReturnValue tryFastMalloc(size_t n)
220{
221 ASSERT(!isForbidden());
222
223#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
224 if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= n) // If overflow would occur...
225 return 0;
226
227 void* result = malloc(n + sizeof(AllocAlignmentInteger));
228 if (!result)
229 return 0;
230
231 *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
232 result = static_cast<AllocAlignmentInteger*>(result) + 1;
233
234 return result;
235#else
236 return malloc(n);
237#endif
238}
239
240void* fastMalloc(size_t n)
241{
242 ASSERT(!isForbidden());
243
244#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
245 TryMallocReturnValue returnValue = tryFastMalloc(n);
246 void* result;
247 returnValue.getValue(result);
248#else
249 void* result = malloc(n);
250#endif
251
252 if (!result) {
253#if PLATFORM(BREWMP)
254 // The behavior of malloc(0) is implementation defined.
255 // To make sure that fastMalloc never returns 0, retry with fastMalloc(1).
256 if (!n)
257 return fastMalloc(1);
258#endif
259 CRASH();
260 }
261
262 return result;
263}
264
265TryMallocReturnValue tryFastCalloc(size_t n_elements, size_t element_size)
266{
267 ASSERT(!isForbidden());
268
269#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
270 size_t totalBytes = n_elements * element_size;
271 if (n_elements > 1 && element_size && (totalBytes / element_size) != n_elements || (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= totalBytes))
272 return 0;
273
274 totalBytes += sizeof(AllocAlignmentInteger);
275 void* result = malloc(totalBytes);
276 if (!result)
277 return 0;
278
279 memset(result, 0, totalBytes);
280 *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
281 result = static_cast<AllocAlignmentInteger*>(result) + 1;
282 return result;
283#else
284 return calloc(n_elements, element_size);
285#endif
286}
287
288void* fastCalloc(size_t n_elements, size_t element_size)
289{
290 ASSERT(!isForbidden());
291
292#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
293 TryMallocReturnValue returnValue = tryFastCalloc(n_elements, element_size);
294 void* result;
295 returnValue.getValue(result);
296#else
297 void* result = calloc(n_elements, element_size);
298#endif
299
300 if (!result) {
301#if PLATFORM(BREWMP)
302 // If either n_elements or element_size is 0, the behavior of calloc is implementation defined.
303 // To make sure that fastCalloc never returns 0, retry with fastCalloc(1, 1).
304 if (!n_elements || !element_size)
305 return fastCalloc(1, 1);
306#endif
307 CRASH();
308 }
309
310 return result;
311}
312
313void fastFree(void* p)
314{
315 ASSERT(!isForbidden());
316
317#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
318 if (!p)
319 return;
320
321 AllocAlignmentInteger* header = Internal::fastMallocMatchValidationValue(p);
322 if (*header != Internal::AllocTypeMalloc)
323 Internal::fastMallocMatchFailed(p);
324 free(header);
325#else
326 free(p);
327#endif
328}
329
330TryMallocReturnValue tryFastRealloc(void* p, size_t n)
331{
332 ASSERT(!isForbidden());
333
334#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
335 if (p) {
336 if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= n) // If overflow would occur...
337 return 0;
338 AllocAlignmentInteger* header = Internal::fastMallocMatchValidationValue(p);
339 if (*header != Internal::AllocTypeMalloc)
340 Internal::fastMallocMatchFailed(p);
341 void* result = realloc(header, n + sizeof(AllocAlignmentInteger));
342 if (!result)
343 return 0;
344
345 // This should not be needed because the value is already there:
346 // *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
347 result = static_cast<AllocAlignmentInteger*>(result) + 1;
348 return result;
349 } else {
350 return fastMalloc(n);
351 }
352#else
353 return realloc(p, n);
354#endif
355}
356
357void* fastRealloc(void* p, size_t n)
358{
359 ASSERT(!isForbidden());
360
361#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
362 TryMallocReturnValue returnValue = tryFastRealloc(p, n);
363 void* result;
364 returnValue.getValue(result);
365#else
366 void* result = realloc(p, n);
367#endif
368
369 if (!result)
370 CRASH();
371 return result;
372}
373
374void releaseFastMallocFreeMemory() { }
375
376FastMallocStatistics fastMallocStatistics()
377{
378 FastMallocStatistics statistics = { 0, 0, 0 };
379 return statistics;
380}
381
382size_t fastMallocSize(const void* p)
383{
384#if OS(DARWIN)
385 return malloc_size(p);
386#elif COMPILER(MSVC)
387 return _msize(const_cast<void*>(p));
388#else
389 return 1;
390#endif
391}
392
393} // namespace WTF
394
395#if OS(DARWIN)
396// This symbol is present in the JavaScriptCore exports file even when FastMalloc is disabled.
397// It will never be used in this case, so it's type and value are less interesting than its presence.
398extern "C" const int jscore_fastmalloc_introspection = 0;
399#endif
400
401#else // FORCE_SYSTEM_MALLOC
402
403#if HAVE(STDINT_H)
404#include <stdint.h>
405#elif HAVE(INTTYPES_H)
406#include <inttypes.h>
407#else
408#include <sys/types.h>
409#endif
410
411#include "AlwaysInline.h"
412#include "Assertions.h"
413#include "TCPackedCache.h"
414#include "TCPageMap.h"
415#include "TCSpinLock.h"
416#include "TCSystemAlloc.h"
417#include <algorithm>
418#include <limits>
419#include <pthread.h>
420#include <stdarg.h>
421#include <stddef.h>
422#include <stdio.h>
423#if HAVE(ERRNO_H)
424#include <errno.h>
425#endif
426#if OS(UNIX)
427#include <unistd.h>
428#endif
429#if OS(WINDOWS)
430#ifndef WIN32_LEAN_AND_MEAN
431#define WIN32_LEAN_AND_MEAN
432#endif
433#include <windows.h>
434#endif
435
436#ifdef WTF_CHANGES
437
438#if OS(DARWIN)
439#include "MallocZoneSupport.h"
440#include <wtf/HashSet.h>
441#include <wtf/Vector.h>
442#endif
443#if HAVE(DISPATCH_H)
444#include <dispatch/dispatch.h>
445#endif
446
447
448#ifndef PRIuS
449#define PRIuS "zu"
450#endif
451
452// Calling pthread_getspecific through a global function pointer is faster than a normal
453// call to the function on Mac OS X, and it's used in performance-critical code. So we
454// use a function pointer. But that's not necessarily faster on other platforms, and we had
455// problems with this technique on Windows, so we'll do this only on Mac OS X.
456#if OS(DARWIN)
457static void* (*pthread_getspecific_function_pointer)(pthread_key_t) = pthread_getspecific;
458#define pthread_getspecific(key) pthread_getspecific_function_pointer(key)
459#endif
460
461#define DEFINE_VARIABLE(type, name, value, meaning) \
462 namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead { \
463 type FLAGS_##name(value); \
464 char FLAGS_no##name; \
465 } \
466 using FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead::FLAGS_##name
467
468#define DEFINE_int64(name, value, meaning) \
469 DEFINE_VARIABLE(int64_t, name, value, meaning)
470
471#define DEFINE_double(name, value, meaning) \
472 DEFINE_VARIABLE(double, name, value, meaning)
473
474namespace WTF {
475
476#define malloc fastMalloc
477#define calloc fastCalloc
478#define free fastFree
479#define realloc fastRealloc
480
481#define MESSAGE LOG_ERROR
482#define CHECK_CONDITION ASSERT
483
484#if OS(DARWIN)
485struct Span;
486class TCMalloc_Central_FreeListPadded;
487class TCMalloc_PageHeap;
488class TCMalloc_ThreadCache;
489template <typename T> class PageHeapAllocator;
490
491class FastMallocZone {
492public:
493 static void init();
494
495 static kern_return_t enumerate(task_t, void*, unsigned typeMmask, vm_address_t zoneAddress, memory_reader_t, vm_range_recorder_t);
496 static size_t goodSize(malloc_zone_t*, size_t size) { return size; }
497 static boolean_t check(malloc_zone_t*) { return true; }
498 static void print(malloc_zone_t*, boolean_t) { }
499 static void log(malloc_zone_t*, void*) { }
500 static void forceLock(malloc_zone_t*) { }
501 static void forceUnlock(malloc_zone_t*) { }
502 static void statistics(malloc_zone_t*, malloc_statistics_t* stats) { memset(stats, 0, sizeof(malloc_statistics_t)); }
503
504private:
505 FastMallocZone(TCMalloc_PageHeap*, TCMalloc_ThreadCache**, TCMalloc_Central_FreeListPadded*, PageHeapAllocator<Span>*, PageHeapAllocator<TCMalloc_ThreadCache>*);
506 static size_t size(malloc_zone_t*, const void*);
507 static void* zoneMalloc(malloc_zone_t*, size_t);
508 static void* zoneCalloc(malloc_zone_t*, size_t numItems, size_t size);
509 static void zoneFree(malloc_zone_t*, void*);
510 static void* zoneRealloc(malloc_zone_t*, void*, size_t);
511 static void* zoneValloc(malloc_zone_t*, size_t) { LOG_ERROR("valloc is not supported"); return 0; }
512 static void zoneDestroy(malloc_zone_t*) { }
513
514 malloc_zone_t m_zone;
515 TCMalloc_PageHeap* m_pageHeap;
516 TCMalloc_ThreadCache** m_threadHeaps;
517 TCMalloc_Central_FreeListPadded* m_centralCaches;
518 PageHeapAllocator<Span>* m_spanAllocator;
519 PageHeapAllocator<TCMalloc_ThreadCache>* m_pageHeapAllocator;
520};
521
522#endif
523
524#endif
525
526#ifndef WTF_CHANGES
527// This #ifdef should almost never be set. Set NO_TCMALLOC_SAMPLES if
528// you're porting to a system where you really can't get a stacktrace.
529#ifdef NO_TCMALLOC_SAMPLES
530// We use #define so code compiles even if you #include stacktrace.h somehow.
531# define GetStackTrace(stack, depth, skip) (0)
532#else
533# include <google/stacktrace.h>
534#endif
535#endif
536
537// Even if we have support for thread-local storage in the compiler
538// and linker, the OS may not support it. We need to check that at
539// runtime. Right now, we have to keep a manual set of "bad" OSes.
540#if defined(HAVE_TLS)
541 static bool kernel_supports_tls = false; // be conservative
542 static inline bool KernelSupportsTLS() {
543 return kernel_supports_tls;
544 }
545# if !HAVE_DECL_UNAME // if too old for uname, probably too old for TLS
546 static void CheckIfKernelSupportsTLS() {
547 kernel_supports_tls = false;
548 }
549# else
550# include <sys/utsname.h> // DECL_UNAME checked for <sys/utsname.h> too
551 static void CheckIfKernelSupportsTLS() {
552 struct utsname buf;
553 if (uname(&buf) != 0) { // should be impossible
554 MESSAGE("uname failed assuming no TLS support (errno=%d)\n", errno);
555 kernel_supports_tls = false;
556 } else if (strcasecmp(buf.sysname, "linux") == 0) {
557 // The linux case: the first kernel to support TLS was 2.6.0
558 if (buf.release[0] < '2' && buf.release[1] == '.') // 0.x or 1.x
559 kernel_supports_tls = false;
560 else if (buf.release[0] == '2' && buf.release[1] == '.' &&
561 buf.release[2] >= '0' && buf.release[2] < '6' &&
562 buf.release[3] == '.') // 2.0 - 2.5
563 kernel_supports_tls = false;
564 else
565 kernel_supports_tls = true;
566 } else { // some other kernel, we'll be optimisitic
567 kernel_supports_tls = true;
568 }
569 // TODO(csilvers): VLOG(1) the tls status once we support RAW_VLOG
570 }
571# endif // HAVE_DECL_UNAME
572#endif // HAVE_TLS
573
574// __THROW is defined in glibc systems. It means, counter-intuitively,
575// "This function will never throw an exception." It's an optional
576// optimization tool, but we may need to use it to match glibc prototypes.
577#ifndef __THROW // I guess we're not on a glibc system
578# define __THROW // __THROW is just an optimization, so ok to make it ""
579#endif
580
581//-------------------------------------------------------------------
582// Configuration
583//-------------------------------------------------------------------
584
585// Not all possible combinations of the following parameters make
586// sense. In particular, if kMaxSize increases, you may have to
587// increase kNumClasses as well.
588static const size_t kPageShift = 12;
589static const size_t kPageSize = 1 << kPageShift;
590static const size_t kMaxSize = 8u * kPageSize;
591static const size_t kAlignShift = 3;
592static const size_t kAlignment = 1 << kAlignShift;
593static const size_t kNumClasses = 68;
594
595// Allocates a big block of memory for the pagemap once we reach more than
596// 128MB
597static const size_t kPageMapBigAllocationThreshold = 128 << 20;
598
599// Minimum number of pages to fetch from system at a time. Must be
600// significantly bigger than kPageSize to amortize system-call
601// overhead, and also to reduce external fragementation. Also, we
602// should keep this value big because various incarnations of Linux
603// have small limits on the number of mmap() regions per
604// address-space.
605static const size_t kMinSystemAlloc = 1 << (20 - kPageShift);
606
607// Number of objects to move between a per-thread list and a central
608// list in one shot. We want this to be not too small so we can
609// amortize the lock overhead for accessing the central list. Making
610// it too big may temporarily cause unnecessary memory wastage in the
611// per-thread free list until the scavenger cleans up the list.
612static int num_objects_to_move[kNumClasses];
613
614// Maximum length we allow a per-thread free-list to have before we
615// move objects from it into the corresponding central free-list. We
616// want this big to avoid locking the central free-list too often. It
617// should not hurt to make this list somewhat big because the
618// scavenging code will shrink it down when its contents are not in use.
619static const int kMaxFreeListLength = 256;
620
621// Lower and upper bounds on the per-thread cache sizes
622static const size_t kMinThreadCacheSize = kMaxSize * 2;
623static const size_t kMaxThreadCacheSize = 2 << 20;
624
625// Default bound on the total amount of thread caches
626static const size_t kDefaultOverallThreadCacheSize = 16 << 20;
627
628// For all span-lengths < kMaxPages we keep an exact-size list.
629// REQUIRED: kMaxPages >= kMinSystemAlloc;
630static const size_t kMaxPages = kMinSystemAlloc;
631
632/* The smallest prime > 2^n */
633static int primes_list[] = {
634 // Small values might cause high rates of sampling
635 // and hence commented out.
636 // 2, 5, 11, 17, 37, 67, 131, 257,
637 // 521, 1031, 2053, 4099, 8209, 16411,
638 32771, 65537, 131101, 262147, 524309, 1048583,
639 2097169, 4194319, 8388617, 16777259, 33554467 };
640
641// Twice the approximate gap between sampling actions.
642// I.e., we take one sample approximately once every
643// tcmalloc_sample_parameter/2
644// bytes of allocation, i.e., ~ once every 128KB.
645// Must be a prime number.
646#ifdef NO_TCMALLOC_SAMPLES
647DEFINE_int64(tcmalloc_sample_parameter, 0,
648 "Unused: code is compiled with NO_TCMALLOC_SAMPLES");
649static size_t sample_period = 0;
650#else
651DEFINE_int64(tcmalloc_sample_parameter, 262147,
652 "Twice the approximate gap between sampling actions."
653 " Must be a prime number. Otherwise will be rounded up to a "
654 " larger prime number");
655static size_t sample_period = 262147;
656#endif
657
658// Protects sample_period above
659static SpinLock sample_period_lock = SPINLOCK_INITIALIZER;
660
661// Parameters for controlling how fast memory is returned to the OS.
662
663DEFINE_double(tcmalloc_release_rate, 1,
664 "Rate at which we release unused memory to the system. "
665 "Zero means we never release memory back to the system. "
666 "Increase this flag to return memory faster; decrease it "
667 "to return memory slower. Reasonable rates are in the "
668 "range [0,10]");
669
670//-------------------------------------------------------------------
671// Mapping from size to size_class and vice versa
672//-------------------------------------------------------------------
673
674// Sizes <= 1024 have an alignment >= 8. So for such sizes we have an
675// array indexed by ceil(size/8). Sizes > 1024 have an alignment >= 128.
676// So for these larger sizes we have an array indexed by ceil(size/128).
677//
678// We flatten both logical arrays into one physical array and use
679// arithmetic to compute an appropriate index. The constants used by
680// ClassIndex() were selected to make the flattening work.
681//
682// Examples:
683// Size Expression Index
684// -------------------------------------------------------
685// 0 (0 + 7) / 8 0
686// 1 (1 + 7) / 8 1
687// ...
688// 1024 (1024 + 7) / 8 128
689// 1025 (1025 + 127 + (120<<7)) / 128 129
690// ...
691// 32768 (32768 + 127 + (120<<7)) / 128 376
692static const size_t kMaxSmallSize = 1024;
693static const int shift_amount[2] = { 3, 7 }; // For divides by 8 or 128
694static const int add_amount[2] = { 7, 127 + (120 << 7) };
695static unsigned char class_array[377];
696
697// Compute index of the class_array[] entry for a given size
698static inline int ClassIndex(size_t s) {
699 const int i = (s > kMaxSmallSize);
700 return static_cast<int>((s + add_amount[i]) >> shift_amount[i]);
701}
702
703// Mapping from size class to max size storable in that class
704static size_t class_to_size[kNumClasses];
705
706// Mapping from size class to number of pages to allocate at a time
707static size_t class_to_pages[kNumClasses];
708
709// TransferCache is used to cache transfers of num_objects_to_move[size_class]
710// back and forth between thread caches and the central cache for a given size
711// class.
712struct TCEntry {
713 void *head; // Head of chain of objects.
714 void *tail; // Tail of chain of objects.
715};
716// A central cache freelist can have anywhere from 0 to kNumTransferEntries
717// slots to put link list chains into. To keep memory usage bounded the total
718// number of TCEntries across size classes is fixed. Currently each size
719// class is initially given one TCEntry which also means that the maximum any
720// one class can have is kNumClasses.
721static const int kNumTransferEntries = kNumClasses;
722
723// Note: the following only works for "n"s that fit in 32-bits, but
724// that is fine since we only use it for small sizes.
725static inline int LgFloor(size_t n) {
726 int log = 0;
727 for (int i = 4; i >= 0; --i) {
728 int shift = (1 << i);
729 size_t x = n >> shift;
730 if (x != 0) {
731 n = x;
732 log += shift;
733 }
734 }
735 ASSERT(n == 1);
736 return log;
737}
738
739// Some very basic linked list functions for dealing with using void * as
740// storage.
741
742static inline void *SLL_Next(void *t) {
743 return *(reinterpret_cast<void**>(t));
744}
745
746static inline void SLL_SetNext(void *t, void *n) {
747 *(reinterpret_cast<void**>(t)) = n;
748}
749
750static inline void SLL_Push(void **list, void *element) {
751 SLL_SetNext(element, *list);
752 *list = element;
753}
754
755static inline void *SLL_Pop(void **list) {
756 void *result = *list;
757 *list = SLL_Next(*list);
758 return result;
759}
760
761
762// Remove N elements from a linked list to which head points. head will be
763// modified to point to the new head. start and end will point to the first
764// and last nodes of the range. Note that end will point to NULL after this
765// function is called.
766static inline void SLL_PopRange(void **head, int N, void **start, void **end) {
767 if (N == 0) {
768 *start = NULL;
769 *end = NULL;
770 return;
771 }
772
773 void *tmp = *head;
774 for (int i = 1; i < N; ++i) {
775 tmp = SLL_Next(tmp);
776 }
777
778 *start = *head;
779 *end = tmp;
780 *head = SLL_Next(tmp);
781 // Unlink range from list.
782 SLL_SetNext(tmp, NULL);
783}
784
785static inline void SLL_PushRange(void **head, void *start, void *end) {
786 if (!start) return;
787 SLL_SetNext(end, *head);
788 *head = start;
789}
790
791static inline size_t SLL_Size(void *head) {
792 int count = 0;
793 while (head) {
794 count++;
795 head = SLL_Next(head);
796 }
797 return count;
798}
799
800// Setup helper functions.
801
802static ALWAYS_INLINE size_t SizeClass(size_t size) {
803 return class_array[ClassIndex(size)];
804}
805
806// Get the byte-size for a specified class
807static ALWAYS_INLINE size_t ByteSizeForClass(size_t cl) {
808 return class_to_size[cl];
809}
810static int NumMoveSize(size_t size) {
811 if (size == 0) return 0;
812 // Use approx 64k transfers between thread and central caches.
813 int num = static_cast<int>(64.0 * 1024.0 / size);
814 if (num < 2) num = 2;
815 // Clamp well below kMaxFreeListLength to avoid ping pong between central
816 // and thread caches.
817 if (num > static_cast<int>(0.8 * kMaxFreeListLength))
818 num = static_cast<int>(0.8 * kMaxFreeListLength);
819
820 // Also, avoid bringing in too many objects into small object free
821 // lists. There are lots of such lists, and if we allow each one to
822 // fetch too many at a time, we end up having to scavenge too often
823 // (especially when there are lots of threads and each thread gets a
824 // small allowance for its thread cache).
825 //
826 // TODO: Make thread cache free list sizes dynamic so that we do not
827 // have to equally divide a fixed resource amongst lots of threads.
828 if (num > 32) num = 32;
829
830 return num;
831}
832
833// Initialize the mapping arrays
834static void InitSizeClasses() {
835 // Do some sanity checking on add_amount[]/shift_amount[]/class_array[]
836 if (ClassIndex(0) < 0) {
837 MESSAGE("Invalid class index %d for size 0\n", ClassIndex(0));
838 CRASH();
839 }
840 if (static_cast<size_t>(ClassIndex(kMaxSize)) >= sizeof(class_array)) {
841 MESSAGE("Invalid class index %d for kMaxSize\n", ClassIndex(kMaxSize));
842 CRASH();
843 }
844
845 // Compute the size classes we want to use
846 size_t sc = 1; // Next size class to assign
847 unsigned char alignshift = kAlignShift;
848 int last_lg = -1;
849 for (size_t size = kAlignment; size <= kMaxSize; size += (1 << alignshift)) {
850 int lg = LgFloor(size);
851 if (lg > last_lg) {
852 // Increase alignment every so often.
853 //
854 // Since we double the alignment every time size doubles and
855 // size >= 128, this means that space wasted due to alignment is
856 // at most 16/128 i.e., 12.5%. Plus we cap the alignment at 256
857 // bytes, so the space wasted as a percentage starts falling for
858 // sizes > 2K.
859 if ((lg >= 7) && (alignshift < 8)) {
860 alignshift++;
861 }
862 last_lg = lg;
863 }
864
865 // Allocate enough pages so leftover is less than 1/8 of total.
866 // This bounds wasted space to at most 12.5%.
867 size_t psize = kPageSize;
868 while ((psize % size) > (psize >> 3)) {
869 psize += kPageSize;
870 }
871 const size_t my_pages = psize >> kPageShift;
872
873 if (sc > 1 && my_pages == class_to_pages[sc-1]) {
874 // See if we can merge this into the previous class without
875 // increasing the fragmentation of the previous class.
876 const size_t my_objects = (my_pages << kPageShift) / size;
877 const size_t prev_objects = (class_to_pages[sc-1] << kPageShift)
878 / class_to_size[sc-1];
879 if (my_objects == prev_objects) {
880 // Adjust last class to include this size
881 class_to_size[sc-1] = size;
882 continue;
883 }
884 }
885
886 // Add new class
887 class_to_pages[sc] = my_pages;
888 class_to_size[sc] = size;
889 sc++;
890 }
891 if (sc != kNumClasses) {
892 MESSAGE("wrong number of size classes: found %" PRIuS " instead of %d\n",
893 sc, int(kNumClasses));
894 CRASH();
895 }
896
897 // Initialize the mapping arrays
898 int next_size = 0;
899 for (unsigned char c = 1; c < kNumClasses; c++) {
900 const size_t max_size_in_class = class_to_size[c];
901 for (size_t s = next_size; s <= max_size_in_class; s += kAlignment) {
902 class_array[ClassIndex(s)] = c;
903 }
904 next_size = static_cast<int>(max_size_in_class + kAlignment);
905 }
906
907 // Double-check sizes just to be safe
908 for (size_t size = 0; size <= kMaxSize; size++) {
909 const size_t sc = SizeClass(size);
910 if (sc == 0) {
911 MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
912 CRASH();
913 }
914 if (sc > 1 && size <= class_to_size[sc-1]) {
915 MESSAGE("Allocating unnecessarily large class %" PRIuS " for %" PRIuS
916 "\n", sc, size);
917 CRASH();
918 }
919 if (sc >= kNumClasses) {
920 MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
921 CRASH();
922 }
923 const size_t s = class_to_size[sc];
924 if (size > s) {
925 MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
926 CRASH();
927 }
928 if (s == 0) {
929 MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
930 CRASH();
931 }
932 }
933
934 // Initialize the num_objects_to_move array.
935 for (size_t cl = 1; cl < kNumClasses; ++cl) {
936 num_objects_to_move[cl] = NumMoveSize(ByteSizeForClass(cl));
937 }
938
939#ifndef WTF_CHANGES
940 if (false) {
941 // Dump class sizes and maximum external wastage per size class
942 for (size_t cl = 1; cl < kNumClasses; ++cl) {
943 const int alloc_size = class_to_pages[cl] << kPageShift;
944 const int alloc_objs = alloc_size / class_to_size[cl];
945 const int min_used = (class_to_size[cl-1] + 1) * alloc_objs;
946 const int max_waste = alloc_size - min_used;
947 MESSAGE("SC %3d [ %8d .. %8d ] from %8d ; %2.0f%% maxwaste\n",
948 int(cl),
949 int(class_to_size[cl-1] + 1),
950 int(class_to_size[cl]),
951 int(class_to_pages[cl] << kPageShift),
952 max_waste * 100.0 / alloc_size
953 );
954 }
955 }
956#endif
957}
958
959// -------------------------------------------------------------------------
960// Simple allocator for objects of a specified type. External locking
961// is required before accessing one of these objects.
962// -------------------------------------------------------------------------
963
964// Metadata allocator -- keeps stats about how many bytes allocated
965static uint64_t metadata_system_bytes = 0;
966static void* MetaDataAlloc(size_t bytes) {
967 void* result = TCMalloc_SystemAlloc(bytes, 0);
968 if (result != NULL) {
969 metadata_system_bytes += bytes;
970 }
971 return result;
972}
973
974template <class T>
975class PageHeapAllocator {
976 private:
977 // How much to allocate from system at a time
978 static const size_t kAllocIncrement = 32 << 10;
979
980 // Aligned size of T
981 static const size_t kAlignedSize
982 = (((sizeof(T) + kAlignment - 1) / kAlignment) * kAlignment);
983
984 // Free area from which to carve new objects
985 char* free_area_;
986 size_t free_avail_;
987
988 // Linked list of all regions allocated by this allocator
989 void* allocated_regions_;
990
991 // Free list of already carved objects
992 void* free_list_;
993
994 // Number of allocated but unfreed objects
995 int inuse_;
996
997 public:
998 void Init() {
999 ASSERT(kAlignedSize <= kAllocIncrement);
1000 inuse_ = 0;
1001 allocated_regions_ = 0;
1002 free_area_ = NULL;
1003 free_avail_ = 0;
1004 free_list_ = NULL;
1005 }
1006
1007 T* New() {
1008 // Consult free list
1009 void* result;
1010 if (free_list_ != NULL) {
1011 result = free_list_;
1012 free_list_ = *(reinterpret_cast<void**>(result));
1013 } else {
1014 if (free_avail_ < kAlignedSize) {
1015 // Need more room
1016 char* new_allocation = reinterpret_cast<char*>(MetaDataAlloc(kAllocIncrement));
1017 if (!new_allocation)
1018 CRASH();
1019
1020 *(void**)new_allocation = allocated_regions_;
1021 allocated_regions_ = new_allocation;
1022 free_area_ = new_allocation + kAlignedSize;
1023 free_avail_ = kAllocIncrement - kAlignedSize;
1024 }
1025 result = free_area_;
1026 free_area_ += kAlignedSize;
1027 free_avail_ -= kAlignedSize;
1028 }
1029 inuse_++;
1030 return reinterpret_cast<T*>(result);
1031 }
1032
1033 void Delete(T* p) {
1034 *(reinterpret_cast<void**>(p)) = free_list_;
1035 free_list_ = p;
1036 inuse_--;
1037 }
1038
1039 int inuse() const { return inuse_; }
1040
1041#if defined(WTF_CHANGES) && OS(DARWIN)
1042 template <class Recorder>
1043 void recordAdministrativeRegions(Recorder& recorder, const RemoteMemoryReader& reader)
1044 {
1045 vm_address_t adminAllocation = reinterpret_cast<vm_address_t>(allocated_regions_);
1046 while (adminAllocation) {
1047 recorder.recordRegion(adminAllocation, kAllocIncrement);
1048 adminAllocation = *reader(reinterpret_cast<vm_address_t*>(adminAllocation));
1049 }
1050 }
1051#endif
1052};
1053
1054// -------------------------------------------------------------------------
1055// Span - a contiguous run of pages
1056// -------------------------------------------------------------------------
1057
1058// Type that can hold a page number
1059typedef uintptr_t PageID;
1060
1061// Type that can hold the length of a run of pages
1062typedef uintptr_t Length;
1063
1064static const Length kMaxValidPages = (~static_cast<Length>(0)) >> kPageShift;
1065
1066// Convert byte size into pages. This won't overflow, but may return
1067// an unreasonably large value if bytes is huge enough.
1068static inline Length pages(size_t bytes) {
1069 return (bytes >> kPageShift) +
1070 ((bytes & (kPageSize - 1)) > 0 ? 1 : 0);
1071}
1072
1073// Convert a user size into the number of bytes that will actually be
1074// allocated
1075static size_t AllocationSize(size_t bytes) {
1076 if (bytes > kMaxSize) {
1077 // Large object: we allocate an integral number of pages
1078 ASSERT(bytes <= (kMaxValidPages << kPageShift));
1079 return pages(bytes) << kPageShift;
1080 } else {
1081 // Small object: find the size class to which it belongs
1082 return ByteSizeForClass(SizeClass(bytes));
1083 }
1084}
1085
1086// Information kept for a span (a contiguous run of pages).
1087struct Span {
1088 PageID start; // Starting page number
1089 Length length; // Number of pages in span
1090 Span* next; // Used when in link list
1091 Span* prev; // Used when in link list
1092 void* objects; // Linked list of free objects
1093 unsigned int free : 1; // Is the span free
1094#ifndef NO_TCMALLOC_SAMPLES
1095 unsigned int sample : 1; // Sampled object?
1096#endif
1097 unsigned int sizeclass : 8; // Size-class for small objects (or 0)
1098 unsigned int refcount : 11; // Number of non-free objects
1099 bool decommitted : 1;
1100
1101#undef SPAN_HISTORY
1102#ifdef SPAN_HISTORY
1103 // For debugging, we can keep a log events per span
1104 int nexthistory;
1105 char history[64];
1106 int value[64];
1107#endif
1108};
1109
1110#define ASSERT_SPAN_COMMITTED(span) ASSERT(!span->decommitted)
1111
1112#ifdef SPAN_HISTORY
1113void Event(Span* span, char op, int v = 0) {
1114 span->history[span->nexthistory] = op;
1115 span->value[span->nexthistory] = v;
1116 span->nexthistory++;
1117 if (span->nexthistory == sizeof(span->history)) span->nexthistory = 0;
1118}
1119#else
1120#define Event(s,o,v) ((void) 0)
1121#endif
1122
1123// Allocator/deallocator for spans
1124static PageHeapAllocator<Span> span_allocator;
1125static Span* NewSpan(PageID p, Length len) {
1126 Span* result = span_allocator.New();
1127 memset(result, 0, sizeof(*result));
1128 result->start = p;
1129 result->length = len;
1130#ifdef SPAN_HISTORY
1131 result->nexthistory = 0;
1132#endif
1133 return result;
1134}
1135
1136static inline void DeleteSpan(Span* span) {
1137#ifndef NDEBUG
1138 // In debug mode, trash the contents of deleted Spans
1139 memset(span, 0x3f, sizeof(*span));
1140#endif
1141 span_allocator.Delete(span);
1142}
1143
1144// -------------------------------------------------------------------------
1145// Doubly linked list of spans.
1146// -------------------------------------------------------------------------
1147
1148static inline void DLL_Init(Span* list) {
1149 list->next = list;
1150 list->prev = list;
1151}
1152
1153static inline void DLL_Remove(Span* span) {
1154 span->prev->next = span->next;
1155 span->next->prev = span->prev;
1156 span->prev = NULL;
1157 span->next = NULL;
1158}
1159
1160static ALWAYS_INLINE bool DLL_IsEmpty(const Span* list) {
1161 return list->next == list;
1162}
1163
1164static int DLL_Length(const Span* list) {
1165 int result = 0;
1166 for (Span* s = list->next; s != list; s = s->next) {
1167 result++;
1168 }
1169 return result;
1170}
1171
1172#if 0 /* Not needed at the moment -- causes compiler warnings if not used */
1173static void DLL_Print(const char* label, const Span* list) {
1174 MESSAGE("%-10s %p:", label, list);
1175 for (const Span* s = list->next; s != list; s = s->next) {
1176 MESSAGE(" <%p,%u,%u>", s, s->start, s->length);
1177 }
1178 MESSAGE("\n");
1179}
1180#endif
1181
1182static inline void DLL_Prepend(Span* list, Span* span) {
1183 ASSERT(span->next == NULL);
1184 ASSERT(span->prev == NULL);
1185 span->next = list->next;
1186 span->prev = list;
1187 list->next->prev = span;
1188 list->next = span;
1189}
1190
1191// -------------------------------------------------------------------------
1192// Stack traces kept for sampled allocations
1193// The following state is protected by pageheap_lock_.
1194// -------------------------------------------------------------------------
1195
1196// size/depth are made the same size as a pointer so that some generic
1197// code below can conveniently cast them back and forth to void*.
1198static const int kMaxStackDepth = 31;
1199struct StackTrace {
1200 uintptr_t size; // Size of object
1201 uintptr_t depth; // Number of PC values stored in array below
1202 void* stack[kMaxStackDepth];
1203};
1204static PageHeapAllocator<StackTrace> stacktrace_allocator;
1205static Span sampled_objects;
1206
1207// -------------------------------------------------------------------------
1208// Map from page-id to per-page data
1209// -------------------------------------------------------------------------
1210
1211// We use PageMap2<> for 32-bit and PageMap3<> for 64-bit machines.
1212// We also use a simple one-level cache for hot PageID-to-sizeclass mappings,
1213// because sometimes the sizeclass is all the information we need.
1214
1215// Selector class -- general selector uses 3-level map
1216template <int BITS> class MapSelector {
1217 public:
1218 typedef TCMalloc_PageMap3<BITS-kPageShift> Type;
1219 typedef PackedCache<BITS, uint64_t> CacheType;
1220};
1221
1222#if defined(WTF_CHANGES)
1223#if CPU(X86_64)
1224// On all known X86-64 platforms, the upper 16 bits are always unused and therefore
1225// can be excluded from the PageMap key.
1226// See http://en.wikipedia.org/wiki/X86-64#Virtual_address_space_details
1227
1228static const size_t kBitsUnusedOn64Bit = 16;
1229#else
1230static const size_t kBitsUnusedOn64Bit = 0;
1231#endif
1232
1233// A three-level map for 64-bit machines
1234template <> class MapSelector<64> {
1235 public:
1236 typedef TCMalloc_PageMap3<64 - kPageShift - kBitsUnusedOn64Bit> Type;
1237 typedef PackedCache<64, uint64_t> CacheType;
1238};
1239#endif
1240
1241// A two-level map for 32-bit machines
1242template <> class MapSelector<32> {
1243 public:
1244 typedef TCMalloc_PageMap2<32 - kPageShift> Type;
1245 typedef PackedCache<32 - kPageShift, uint16_t> CacheType;
1246};
1247
1248// -------------------------------------------------------------------------
1249// Page-level allocator
1250// * Eager coalescing
1251//
1252// Heap for page-level allocation. We allow allocating and freeing a
1253// contiguous runs of pages (called a "span").
1254// -------------------------------------------------------------------------
1255
1256#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1257// The page heap maintains a free list for spans that are no longer in use by
1258// the central cache or any thread caches. We use a background thread to
1259// periodically scan the free list and release a percentage of it back to the OS.
1260
1261// If free_committed_pages_ exceeds kMinimumFreeCommittedPageCount, the
1262// background thread:
1263// - wakes up
1264// - pauses for kScavengeDelayInSeconds
1265// - returns to the OS a percentage of the memory that remained unused during
1266// that pause (kScavengePercentage * min_free_committed_pages_since_last_scavenge_)
1267// The goal of this strategy is to reduce memory pressure in a timely fashion
1268// while avoiding thrashing the OS allocator.
1269
1270// Time delay before the page heap scavenger will consider returning pages to
1271// the OS.
1272static const int kScavengeDelayInSeconds = 2;
1273
1274// Approximate percentage of free committed pages to return to the OS in one
1275// scavenge.
1276static const float kScavengePercentage = .5f;
1277
1278// number of span lists to keep spans in when memory is returned.
1279static const int kMinSpanListsWithSpans = 32;
1280
1281// Number of free committed pages that we want to keep around. The minimum number of pages used when there
1282// is 1 span in each of the first kMinSpanListsWithSpans spanlists. Currently 528 pages.
1283static const size_t kMinimumFreeCommittedPageCount = kMinSpanListsWithSpans * ((1.0f+kMinSpanListsWithSpans) / 2.0f);
1284
1285#endif
1286
1287class TCMalloc_PageHeap {
1288 public:
1289 void init();
1290
1291 // Allocate a run of "n" pages. Returns zero if out of memory.
1292 Span* New(Length n);
1293
1294 // Delete the span "[p, p+n-1]".
1295 // REQUIRES: span was returned by earlier call to New() and
1296 // has not yet been deleted.
1297 void Delete(Span* span);
1298
1299 // Mark an allocated span as being used for small objects of the
1300 // specified size-class.
1301 // REQUIRES: span was returned by an earlier call to New()
1302 // and has not yet been deleted.
1303 void RegisterSizeClass(Span* span, size_t sc);
1304
1305 // Split an allocated span into two spans: one of length "n" pages
1306 // followed by another span of length "span->length - n" pages.
1307 // Modifies "*span" to point to the first span of length "n" pages.
1308 // Returns a pointer to the second span.
1309 //
1310 // REQUIRES: "0 < n < span->length"
1311 // REQUIRES: !span->free
1312 // REQUIRES: span->sizeclass == 0
1313 Span* Split(Span* span, Length n);
1314
1315 // Return the descriptor for the specified page.
1316 inline Span* GetDescriptor(PageID p) const {
1317 return reinterpret_cast<Span*>(pagemap_.get(p));
1318 }
1319
1320#ifdef WTF_CHANGES
1321 inline Span* GetDescriptorEnsureSafe(PageID p)
1322 {
1323 pagemap_.Ensure(p, 1);
1324 return GetDescriptor(p);
1325 }
1326
1327 size_t ReturnedBytes() const;
1328#endif
1329
1330 // Dump state to stderr
1331#ifndef WTF_CHANGES
1332 void Dump(TCMalloc_Printer* out);
1333#endif
1334
1335 // Return number of bytes allocated from system
1336 inline uint64_t SystemBytes() const { return system_bytes_; }
1337
1338 // Return number of free bytes in heap
1339 uint64_t FreeBytes() const {
1340 return (static_cast<uint64_t>(free_pages_) << kPageShift);
1341 }
1342
1343 bool Check();
1344 bool CheckList(Span* list, Length min_pages, Length max_pages);
1345
1346 // Release all pages on the free list for reuse by the OS:
1347 void ReleaseFreePages();
1348
1349 // Return 0 if we have no information, or else the correct sizeclass for p.
1350 // Reads and writes to pagemap_cache_ do not require locking.
1351 // The entries are 64 bits on 64-bit hardware and 16 bits on
1352 // 32-bit hardware, and we don't mind raciness as long as each read of
1353 // an entry yields a valid entry, not a partially updated entry.
1354 size_t GetSizeClassIfCached(PageID p) const {
1355 return pagemap_cache_.GetOrDefault(p, 0);
1356 }
1357 void CacheSizeClass(PageID p, size_t cl) const { pagemap_cache_.Put(p, cl); }
1358
1359 private:
1360 // Pick the appropriate map and cache types based on pointer size
1361 typedef MapSelector<8*sizeof(uintptr_t)>::Type PageMap;
1362 typedef MapSelector<8*sizeof(uintptr_t)>::CacheType PageMapCache;
1363 PageMap pagemap_;
1364 mutable PageMapCache pagemap_cache_;
1365
1366 // We segregate spans of a given size into two circular linked
1367 // lists: one for normal spans, and one for spans whose memory
1368 // has been returned to the system.
1369 struct SpanList {
1370 Span normal;
1371 Span returned;
1372 };
1373
1374 // List of free spans of length >= kMaxPages
1375 SpanList large_;
1376
1377 // Array mapping from span length to a doubly linked list of free spans
1378 SpanList free_[kMaxPages];
1379
1380 // Number of pages kept in free lists
1381 uintptr_t free_pages_;
1382
1383 // Bytes allocated from system
1384 uint64_t system_bytes_;
1385
1386#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1387 // Number of pages kept in free lists that are still committed.
1388 Length free_committed_pages_;
1389
1390 // Minimum number of free committed pages since last scavenge. (Can be 0 if
1391 // we've committed new pages since the last scavenge.)
1392 Length min_free_committed_pages_since_last_scavenge_;
1393#endif
1394
1395 bool GrowHeap(Length n);
1396
1397 // REQUIRES span->length >= n
1398 // Remove span from its free list, and move any leftover part of
1399 // span into appropriate free lists. Also update "span" to have
1400 // length exactly "n" and mark it as non-free so it can be returned
1401 // to the client.
1402 //
1403 // "released" is true iff "span" was found on a "returned" list.
1404 void Carve(Span* span, Length n, bool released);
1405
1406 void RecordSpan(Span* span) {
1407 pagemap_.set(span->start, span);
1408 if (span->length > 1) {
1409 pagemap_.set(span->start + span->length - 1, span);
1410 }
1411 }
1412
1413 // Allocate a large span of length == n. If successful, returns a
1414 // span of exactly the specified length. Else, returns NULL.
1415 Span* AllocLarge(Length n);
1416
1417#if !USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1418 // Incrementally release some memory to the system.
1419 // IncrementalScavenge(n) is called whenever n pages are freed.
1420 void IncrementalScavenge(Length n);
1421#endif
1422
1423 // Number of pages to deallocate before doing more scavenging
1424 int64_t scavenge_counter_;
1425
1426 // Index of last free list we scavenged
1427 size_t scavenge_index_;
1428
1429#if defined(WTF_CHANGES) && OS(DARWIN)
1430 friend class FastMallocZone;
1431#endif
1432
1433#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1434 void initializeScavenger();
1435 ALWAYS_INLINE void signalScavenger();
1436 void scavenge();
1437 ALWAYS_INLINE bool shouldScavenge() const;
1438
1439#if !HAVE(DISPATCH_H)
1440 static NO_RETURN_WITH_VALUE void* runScavengerThread(void*);
1441 NO_RETURN void scavengerThread();
1442
1443 // Keeps track of whether the background thread is actively scavenging memory every kScavengeDelayInSeconds, or
1444 // it's blocked waiting for more pages to be deleted.
1445 bool m_scavengeThreadActive;
1446
1447 pthread_mutex_t m_scavengeMutex;
1448 pthread_cond_t m_scavengeCondition;
1449#else // !HAVE(DISPATCH_H)
1450 void periodicScavenge();
1451
1452 dispatch_queue_t m_scavengeQueue;
1453 dispatch_source_t m_scavengeTimer;
1454 bool m_scavengingScheduled;
1455#endif
1456
1457#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1458};
1459
1460void TCMalloc_PageHeap::init()
1461{
1462 pagemap_.init(MetaDataAlloc);
1463 pagemap_cache_ = PageMapCache(0);
1464 free_pages_ = 0;
1465 system_bytes_ = 0;
1466
1467#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1468 free_committed_pages_ = 0;
1469 min_free_committed_pages_since_last_scavenge_ = 0;
1470#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1471
1472 scavenge_counter_ = 0;
1473 // Start scavenging at kMaxPages list
1474 scavenge_index_ = kMaxPages-1;
1475 COMPILE_ASSERT(kNumClasses <= (1 << PageMapCache::kValuebits), valuebits);
1476 DLL_Init(&large_.normal);
1477 DLL_Init(&large_.returned);
1478 for (size_t i = 0; i < kMaxPages; i++) {
1479 DLL_Init(&free_[i].normal);
1480 DLL_Init(&free_[i].returned);
1481 }
1482
1483#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1484 initializeScavenger();
1485#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1486}
1487
1488#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1489
1490#if !HAVE(DISPATCH_H)
1491
1492void TCMalloc_PageHeap::initializeScavenger()
1493{
1494 pthread_mutex_init(&m_scavengeMutex, 0);
1495 pthread_cond_init(&m_scavengeCondition, 0);
1496 m_scavengeThreadActive = true;
1497 pthread_t thread;
1498 pthread_create(&thread, 0, runScavengerThread, this);
1499}
1500
1501void* TCMalloc_PageHeap::runScavengerThread(void* context)
1502{
1503 static_cast<TCMalloc_PageHeap*>(context)->scavengerThread();
1504#if COMPILER(MSVC)
1505 // Without this, Visual Studio will complain that this method does not return a value.
1506 return 0;
1507#endif
1508}
1509
1510ALWAYS_INLINE void TCMalloc_PageHeap::signalScavenger()
1511{
1512 if (!m_scavengeThreadActive && shouldScavenge())
1513 pthread_cond_signal(&m_scavengeCondition);
1514}
1515
1516#else // !HAVE(DISPATCH_H)
1517
1518void TCMalloc_PageHeap::initializeScavenger()
1519{
1520 m_scavengeQueue = dispatch_queue_create("com.apple.JavaScriptCore.FastMallocSavenger", NULL);
1521 m_scavengeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, m_scavengeQueue);
1522 dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, kScavengeDelayInSeconds * NSEC_PER_SEC);
1523 dispatch_source_set_timer(m_scavengeTimer, startTime, kScavengeDelayInSeconds * NSEC_PER_SEC, 1000 * NSEC_PER_USEC);
1524 dispatch_source_set_event_handler(m_scavengeTimer, ^{ periodicScavenge(); });
1525 m_scavengingScheduled = false;
1526}
1527
1528ALWAYS_INLINE void TCMalloc_PageHeap::signalScavenger()
1529{
1530 if (!m_scavengingScheduled && shouldScavenge()) {
1531 m_scavengingScheduled = true;
1532 dispatch_resume(m_scavengeTimer);
1533 }
1534}
1535
1536#endif
1537
1538void TCMalloc_PageHeap::scavenge()
1539{
1540 size_t pagesToRelease = min_free_committed_pages_since_last_scavenge_ * kScavengePercentage;
1541 size_t targetPageCount = std::max<size_t>(kMinimumFreeCommittedPageCount, free_committed_pages_ - pagesToRelease);
1542
1543 while (free_committed_pages_ > targetPageCount) {
1544 for (int i = kMaxPages; i > 0 && free_committed_pages_ >= targetPageCount; i--) {
1545 SpanList* slist = (static_cast<size_t>(i) == kMaxPages) ? &large_ : &free_[i];
1546 // If the span size is bigger than kMinSpanListsWithSpans pages return all the spans in the list, else return all but 1 span.
1547 // Return only 50% of a spanlist at a time so spans of size 1 are not the only ones left.
1548 size_t numSpansToReturn = (i > kMinSpanListsWithSpans) ? DLL_Length(&slist->normal) : static_cast<size_t>(.5 * DLL_Length(&slist->normal));
1549 for (int j = 0; static_cast<size_t>(j) < numSpansToReturn && !DLL_IsEmpty(&slist->normal) && free_committed_pages_ > targetPageCount; j++) {
1550 Span* s = slist->normal.prev;
1551 DLL_Remove(s);
1552 ASSERT(!s->decommitted);
1553 if (!s->decommitted) {
1554 TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
1555 static_cast<size_t>(s->length << kPageShift));
1556 ASSERT(free_committed_pages_ >= s->length);
1557 free_committed_pages_ -= s->length;
1558 s->decommitted = true;
1559 }
1560 DLL_Prepend(&slist->returned, s);
1561 }
1562 }
1563 }
1564
1565 min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
1566}
1567
1568ALWAYS_INLINE bool TCMalloc_PageHeap::shouldScavenge() const
1569{
1570 return free_committed_pages_ > kMinimumFreeCommittedPageCount;
1571}
1572
1573#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1574
1575inline Span* TCMalloc_PageHeap::New(Length n) {
1576 ASSERT(Check());
1577 ASSERT(n > 0);
1578
1579 // Find first size >= n that has a non-empty list
1580 for (Length s = n; s < kMaxPages; s++) {
1581 Span* ll = NULL;
1582 bool released = false;
1583 if (!DLL_IsEmpty(&free_[s].normal)) {
1584 // Found normal span
1585 ll = &free_[s].normal;
1586 } else if (!DLL_IsEmpty(&free_[s].returned)) {
1587 // Found returned span; reallocate it
1588 ll = &free_[s].returned;
1589 released = true;
1590 } else {
1591 // Keep looking in larger classes
1592 continue;
1593 }
1594
1595 Span* result = ll->next;
1596 Carve(result, n, released);
1597#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1598 // The newly allocated memory is from a span that's in the normal span list (already committed). Update the
1599 // free committed pages count.
1600 ASSERT(free_committed_pages_ >= n);
1601 free_committed_pages_ -= n;
1602 if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
1603 min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
1604#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1605 ASSERT(Check());
1606 free_pages_ -= n;
1607 return result;
1608 }
1609
1610 Span* result = AllocLarge(n);
1611 if (result != NULL) {
1612 ASSERT_SPAN_COMMITTED(result);
1613 return result;
1614 }
1615
1616 // Grow the heap and try again
1617 if (!GrowHeap(n)) {
1618 ASSERT(Check());
1619 return NULL;
1620 }
1621
1622 return AllocLarge(n);
1623}
1624
1625Span* TCMalloc_PageHeap::AllocLarge(Length n) {
1626 // find the best span (closest to n in size).
1627 // The following loops implements address-ordered best-fit.
1628 bool from_released = false;
1629 Span *best = NULL;
1630
1631 // Search through normal list
1632 for (Span* span = large_.normal.next;
1633 span != &large_.normal;
1634 span = span->next) {
1635 if (span->length >= n) {
1636 if ((best == NULL)
1637 || (span->length < best->length)
1638 || ((span->length == best->length) && (span->start < best->start))) {
1639 best = span;
1640 from_released = false;
1641 }
1642 }
1643 }
1644
1645 // Search through released list in case it has a better fit
1646 for (Span* span = large_.returned.next;
1647 span != &large_.returned;
1648 span = span->next) {
1649 if (span->length >= n) {
1650 if ((best == NULL)
1651 || (span->length < best->length)
1652 || ((span->length == best->length) && (span->start < best->start))) {
1653 best = span;
1654 from_released = true;
1655 }
1656 }
1657 }
1658
1659 if (best != NULL) {
1660 Carve(best, n, from_released);
1661#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1662 // The newly allocated memory is from a span that's in the normal span list (already committed). Update the
1663 // free committed pages count.
1664 ASSERT(free_committed_pages_ >= n);
1665 free_committed_pages_ -= n;
1666 if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
1667 min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
1668#endif // USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1669 ASSERT(Check());
1670 free_pages_ -= n;
1671 return best;
1672 }
1673 return NULL;
1674}
1675
1676Span* TCMalloc_PageHeap::Split(Span* span, Length n) {
1677 ASSERT(0 < n);
1678 ASSERT(n < span->length);
1679 ASSERT(!span->free);
1680 ASSERT(span->sizeclass == 0);
1681 Event(span, 'T', n);
1682
1683 const Length extra = span->length - n;
1684 Span* leftover = NewSpan(span->start + n, extra);
1685 Event(leftover, 'U', extra);
1686 RecordSpan(leftover);
1687 pagemap_.set(span->start + n - 1, span); // Update map from pageid to span
1688 span->length = n;
1689
1690 return leftover;
1691}
1692
1693inline void TCMalloc_PageHeap::Carve(Span* span, Length n, bool released) {
1694 ASSERT(n > 0);
1695 DLL_Remove(span);
1696 span->free = 0;
1697 Event(span, 'A', n);
1698
1699 if (released) {
1700 // If the span chosen to carve from is decommited, commit the entire span at once to avoid committing spans 1 page at a time.
1701 ASSERT(span->decommitted);
1702 TCMalloc_SystemCommit(reinterpret_cast<void*>(span->start << kPageShift), static_cast<size_t>(span->length << kPageShift));
1703 span->decommitted = false;
1704#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1705 free_committed_pages_ += span->length;
1706#endif
1707 }
1708
1709 const int extra = static_cast<int>(span->length - n);
1710 ASSERT(extra >= 0);
1711 if (extra > 0) {
1712 Span* leftover = NewSpan(span->start + n, extra);
1713 leftover->free = 1;
1714 leftover->decommitted = false;
1715 Event(leftover, 'S', extra);
1716 RecordSpan(leftover);
1717
1718 // Place leftover span on appropriate free list
1719 SpanList* listpair = (static_cast<size_t>(extra) < kMaxPages) ? &free_[extra] : &large_;
1720 Span* dst = &listpair->normal;
1721 DLL_Prepend(dst, leftover);
1722
1723 span->length = n;
1724 pagemap_.set(span->start + n - 1, span);
1725 }
1726}
1727
1728static ALWAYS_INLINE void mergeDecommittedStates(Span* destination, Span* other)
1729{
1730 if (destination->decommitted && !other->decommitted) {
1731 TCMalloc_SystemRelease(reinterpret_cast<void*>(other->start << kPageShift),
1732 static_cast<size_t>(other->length << kPageShift));
1733 } else if (other->decommitted && !destination->decommitted) {
1734 TCMalloc_SystemRelease(reinterpret_cast<void*>(destination->start << kPageShift),
1735 static_cast<size_t>(destination->length << kPageShift));
1736 destination->decommitted = true;
1737 }
1738}
1739
1740inline void TCMalloc_PageHeap::Delete(Span* span) {
1741 ASSERT(Check());
1742 ASSERT(!span->free);
1743 ASSERT(span->length > 0);
1744 ASSERT(GetDescriptor(span->start) == span);
1745 ASSERT(GetDescriptor(span->start + span->length - 1) == span);
1746 span->sizeclass = 0;
1747#ifndef NO_TCMALLOC_SAMPLES
1748 span->sample = 0;
1749#endif
1750
1751 // Coalesce -- we guarantee that "p" != 0, so no bounds checking
1752 // necessary. We do not bother resetting the stale pagemap
1753 // entries for the pieces we are merging together because we only
1754 // care about the pagemap entries for the boundaries.
1755#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1756 // Track the total size of the neighboring free spans that are committed.
1757 Length neighboringCommittedSpansLength = 0;
1758#endif
1759 const PageID p = span->start;
1760 const Length n = span->length;
1761 Span* prev = GetDescriptor(p-1);
1762 if (prev != NULL && prev->free) {
1763 // Merge preceding span into this span
1764 ASSERT(prev->start + prev->length == p);
1765 const Length len = prev->length;
1766#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1767 if (!prev->decommitted)
1768 neighboringCommittedSpansLength += len;
1769#endif
1770 mergeDecommittedStates(span, prev);
1771 DLL_Remove(prev);
1772 DeleteSpan(prev);
1773 span->start -= len;
1774 span->length += len;
1775 pagemap_.set(span->start, span);
1776 Event(span, 'L', len);
1777 }
1778 Span* next = GetDescriptor(p+n);
1779 if (next != NULL && next->free) {
1780 // Merge next span into this span
1781 ASSERT(next->start == p+n);
1782 const Length len = next->length;
1783#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1784 if (!next->decommitted)
1785 neighboringCommittedSpansLength += len;
1786#endif
1787 mergeDecommittedStates(span, next);
1788 DLL_Remove(next);
1789 DeleteSpan(next);
1790 span->length += len;
1791 pagemap_.set(span->start + span->length - 1, span);
1792 Event(span, 'R', len);
1793 }
1794
1795 Event(span, 'D', span->length);
1796 span->free = 1;
1797 if (span->decommitted) {
1798 if (span->length < kMaxPages)
1799 DLL_Prepend(&free_[span->length].returned, span);
1800 else
1801 DLL_Prepend(&large_.returned, span);
1802 } else {
1803 if (span->length < kMaxPages)
1804 DLL_Prepend(&free_[span->length].normal, span);
1805 else
1806 DLL_Prepend(&large_.normal, span);
1807 }
1808 free_pages_ += n;
1809
1810#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1811 if (span->decommitted) {
1812 // If the merged span is decommitted, that means we decommitted any neighboring spans that were
1813 // committed. Update the free committed pages count.
1814 free_committed_pages_ -= neighboringCommittedSpansLength;
1815 if (free_committed_pages_ < min_free_committed_pages_since_last_scavenge_)
1816 min_free_committed_pages_since_last_scavenge_ = free_committed_pages_;
1817 } else {
1818 // If the merged span remains committed, add the deleted span's size to the free committed pages count.
1819 free_committed_pages_ += n;
1820 }
1821
1822 // Make sure the scavenge thread becomes active if we have enough freed pages to release some back to the system.
1823 signalScavenger();
1824#else
1825 IncrementalScavenge(n);
1826#endif
1827
1828 ASSERT(Check());
1829}
1830
1831#if !USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
1832void TCMalloc_PageHeap::IncrementalScavenge(Length n) {
1833 // Fast path; not yet time to release memory
1834 scavenge_counter_ -= n;
1835 if (scavenge_counter_ >= 0) return; // Not yet time to scavenge
1836
1837 // If there is nothing to release, wait for so many pages before
1838 // scavenging again. With 4K pages, this comes to 16MB of memory.
1839 static const size_t kDefaultReleaseDelay = 1 << 8;
1840
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;
1849 DLL_Remove(s);
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);
1854
1855 scavenge_counter_ = std::max<size_t>(64UL, std::min<size_t>(kDefaultReleaseDelay, kDefaultReleaseDelay - (free_pages_ / kDefaultReleaseDelay)));
1856
1857 if (index == kMaxPages && !DLL_IsEmpty(&slist->normal))
1858 scavenge_index_ = index - 1;
1859 else
1860 scavenge_index_ = index;
1861 return;
1862 }
1863 index++;
1864 }
1865
1866 // Nothing to scavenge, delay for a while
1867 scavenge_counter_ = kDefaultReleaseDelay;
1868}
1869#endif
1870
1871void 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);
1880 }
1881}
1882
1883#ifdef WTF_CHANGES
1884size_t TCMalloc_PageHeap::ReturnedBytes() const {
1885 size_t result = 0;
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;
1890 }
1891
1892 for (Span* s = large_.returned.next; s != &large_.returned; s = s->next)
1893 result += s->length << kPageShift;
1894 return result;
1895}
1896#endif
1897
1898#ifndef WTF_CHANGES
1899static double PagesToMB(uint64_t pages) {
1900 return (pages << kPageShift) / 1048576.0;
1901}
1902
1903void 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)) {
1907 nonempty_sizes++;
1908 }
1909 }
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",
1926 s,
1927 (n_length + r_length),
1928 PagesToMB(n_pages + r_pages),
1929 PagesToMB(total_normal + total_returned),
1930 PagesToMB(r_pages),
1931 PagesToMB(total_returned));
1932 }
1933 }
1934
1935 uint64_t n_pages = 0;
1936 uint64_t r_pages = 0;
1937 int n_spans = 0;
1938 int r_spans = 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;
1944 n_spans++;
1945 }
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;
1951 r_spans++;
1952 }
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),
1960 PagesToMB(r_pages),
1961 PagesToMB(total_returned));
1962}
1963#endif
1964
1965bool 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);
1969 size_t actual_size;
1970 void* ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize);
1971 if (ptr == NULL) {
1972 if (n < ask) {
1973 // Try growing just "n" pages
1974 ask = n;
1975 ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize);
1976 }
1977 if (ptr == NULL) return false;
1978 }
1979 ask = actual_size >> kPageShift;
1980
1981 uint64_t old_system_bytes = system_bytes_;
1982 system_bytes_ += (ask << kPageShift);
1983 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
1984 ASSERT(p > 0);
1985
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.
1989
1990 if (old_system_bytes < kPageMapBigAllocationThreshold
1991 && system_bytes_ >= kPageMapBigAllocationThreshold) {
1992 pagemap_.PreallocateMoreMemory();
1993 }
1994
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.
2001 //
2002 // We do not adjust free_pages_ here since Delete() will do it for us.
2003 Span* span = NewSpan(p, ask);
2004 RecordSpan(span);
2005 Delete(span);
2006 ASSERT(Check());
2007 return true;
2008 } else {
2009 // We could not allocate memory within "pagemap_"
2010 // TODO: Once we can return memory to the system, return the new span
2011 return false;
2012 }
2013}
2014
2015bool 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);
2023 }
2024 return true;
2025}
2026
2027#if ASSERT_DISABLED
2028bool TCMalloc_PageHeap::CheckList(Span*, Length, Length) {
2029 return true;
2030}
2031#else
2032bool 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);
2039 }
2040 return true;
2041}
2042#endif
2043
2044static 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;
2049 DLL_Remove(s);
2050 DLL_Prepend(returned, s);
2051 TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
2052 static_cast<size_t>(s->length << kPageShift));
2053 }
2054}
2055
2056void TCMalloc_PageHeap::ReleaseFreePages() {
2057 for (Length s = 0; s < kMaxPages; s++) {
2058 ReleaseFreeList(&free_[s].normal, &free_[s].returned);
2059 }
2060 ReleaseFreeList(&large_.normal, &large_.returned);
2061 ASSERT(Check());
2062}
2063
2064//-------------------------------------------------------------------
2065// Free list
2066//-------------------------------------------------------------------
2067
2068class TCMalloc_ThreadCache_FreeList {
2069 private:
2070 void* list_; // Linked list of nodes
2071 uint16_t length_; // Current length
2072 uint16_t lowater_; // Low water mark for list length
2073
2074 public:
2075 void Init() {
2076 list_ = NULL;
2077 length_ = 0;
2078 lowater_ = 0;
2079 }
2080
2081 // Return current length of list
2082 int length() const {
2083 return length_;
2084 }
2085
2086 // Is list empty?
2087 bool empty() const {
2088 return list_ == NULL;
2089 }
2090
2091 // Low-water mark management
2092 int lowwatermark() const { return lowater_; }
2093 void clear_lowwatermark() { lowater_ = length_; }
2094
2095 ALWAYS_INLINE void Push(void* ptr) {
2096 SLL_Push(&list_, ptr);
2097 length_++;
2098 }
2099
2100 void PushRange(int N, void *start, void *end) {
2101 SLL_PushRange(&list_, start, end);
2102 length_ = length_ + static_cast<uint16_t>(N);
2103 }
2104
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_;
2110 }
2111
2112 ALWAYS_INLINE void* Pop() {
2113 ASSERT(list_ != NULL);
2114 length_--;
2115 if (length_ < lowater_) lowater_ = length_;
2116 return SLL_Pop(&list_);
2117 }
2118
2119#ifdef WTF_CHANGES
2120 template <class Finder, class Reader>
2121 void enumerateFreeObjects(Finder& finder, const Reader& reader)
2122 {
2123 for (void* nextObject = list_; nextObject; nextObject = *reader(reinterpret_cast<void**>(nextObject)))
2124 finder.visit(nextObject);
2125 }
2126#endif
2127};
2128
2129//-------------------------------------------------------------------
2130// Data kept per thread
2131//-------------------------------------------------------------------
2132
2133class TCMalloc_ThreadCache {
2134 private:
2135 typedef TCMalloc_ThreadCache_FreeList FreeList;
2136#if COMPILER(MSVC)
2137 typedef DWORD ThreadIdentifier;
2138#else
2139 typedef pthread_t ThreadIdentifier;
2140#endif
2141
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
2146
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
2150
2151 // Allocate a new heap. REQUIRES: pageheap_lock is held.
2152 static inline TCMalloc_ThreadCache* NewHeap(ThreadIdentifier tid);
2153
2154 // Use only as pthread thread-specific destructor function.
2155 static void DestroyThreadCache(void* ptr);
2156 public:
2157 // All ThreadCache objects are kept in a linked list (for stats collection)
2158 TCMalloc_ThreadCache* next_;
2159 TCMalloc_ThreadCache* prev_;
2160
2161 void Init(ThreadIdentifier tid);
2162 void Cleanup();
2163
2164 // Accessors (mostly just for printing stats)
2165 int freelist_length(size_t cl) const { return list_[cl].length(); }
2166
2167 // Total byte size in cache
2168 size_t Size() const { return size_; }
2169
2170 void* Allocate(size_t size);
2171 void Deallocate(void* ptr, size_t size_class);
2172
2173 void FetchFromCentralCache(size_t cl, size_t allocationSize);
2174 void ReleaseToCentralCache(size_t cl, int N);
2175 void Scavenge();
2176 void Print() const;
2177
2178 // Record allocation of "k" bytes. Return true iff allocation
2179 // should be sampled
2180 bool SampleAllocation(size_t k);
2181
2182 // Pick next sampling point
2183 void PickNextSample(size_t k);
2184
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();
2194
2195#ifdef WTF_CHANGES
2196 template <class Finder, class Reader>
2197 void enumerateFreeObjects(Finder& finder, const Reader& reader)
2198 {
2199 for (unsigned sizeClass = 0; sizeClass < kNumClasses; sizeClass++)
2200 list_[sizeClass].enumerateFreeObjects(finder, reader);
2201 }
2202#endif
2203};
2204
2205//-------------------------------------------------------------------
2206// Data kept per size-class in central cache
2207//-------------------------------------------------------------------
2208
2209class TCMalloc_Central_FreeList {
2210 public:
2211 void Init(size_t cl);
2212
2213 // These methods all do internal locking.
2214
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);
2218
2219 // Returns the actual number of fetched elements into N.
2220 void RemoveRange(void **start, void **end, int *N);
2221
2222 // Returns the number of free objects in cache.
2223 size_t length() {
2224 SpinLockHolder h(&lock_);
2225 return counter_;
2226 }
2227
2228 // Returns the number of free objects in the transfer cache.
2229 int tc_length() {
2230 SpinLockHolder h(&lock_);
2231 return used_slots_ * num_objects_to_move[size_class_];
2232 }
2233
2234#ifdef WTF_CHANGES
2235 template <class Finder, class Reader>
2236 void enumerateFreeObjects(Finder& finder, const Reader& reader, TCMalloc_Central_FreeList* remoteCentralFreeList)
2237 {
2238 for (Span* span = &empty_; span && span != &empty_; span = (span->next ? reader(span->next) : 0))
2239 ASSERT(!span->objects);
2240
2241 ASSERT(!nonempty_.objects);
2242 static const ptrdiff_t nonemptyOffset = reinterpret_cast<const char*>(&nonempty_) - reinterpret_cast<const char*>(this);
2243
2244 Span* remoteNonempty = reinterpret_cast<Span*>(reinterpret_cast<char*>(remoteCentralFreeList) + nonemptyOffset);
2245 Span* remoteSpan = nonempty_.next;
2246
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);
2250 }
2251 }
2252#endif
2253
2254 private:
2255 // REQUIRES: lock_ is held
2256 // Remove object from cache and return.
2257 // Return NULL if no free entries in cache.
2258 void* FetchFromSpans();
2259
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();
2265
2266 // REQUIRES: lock_ is held
2267 // Release a linked list of objects to spans.
2268 // May temporarily release lock_.
2269 void ReleaseListToSpans(void *start);
2270
2271 // REQUIRES: lock_ is held
2272 // Release an object to spans.
2273 // May temporarily release lock_.
2274 void ReleaseToSpans(void* object);
2275
2276 // REQUIRES: lock_ is held
2277 // Populate cache by fetching from the page heap.
2278 // May temporarily release lock_.
2279 void Populate();
2280
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
2284 // no space.
2285 bool MakeCacheSpace();
2286
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 bool EvictRandomSizeClass(size_t locked_size_class, bool force);
2293
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);
2302
2303 // This lock protects all the data members. cached_entries and cache_size_
2304 // may be looked at without holding the lock.
2305 SpinLock lock_;
2306
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
2312
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];
2317
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_;
2325};
2326
2327// Pad each CentralCache object to multiple of 64 bytes
2328class TCMalloc_Central_FreeListPadded : public TCMalloc_Central_FreeList {
2329 private:
2330 char pad_[(64 - (sizeof(TCMalloc_Central_FreeList) % 64)) % 64];
2331};
2332
2333//-------------------------------------------------------------------
2334// Global variables
2335//-------------------------------------------------------------------
2336
2337// Central cache -- a collection of free-lists, one per size-class.
2338// We have a separate lock per free-list to reduce contention.
2339static TCMalloc_Central_FreeListPadded central_cache[kNumClasses];
2340
2341// Page-level allocator
2342static SpinLock pageheap_lock = SPINLOCK_INITIALIZER;
2343static AllocAlignmentInteger pageheap_memory[(sizeof(TCMalloc_PageHeap) + sizeof(AllocAlignmentInteger) - 1) / sizeof(AllocAlignmentInteger)];
2344static bool phinited = false;
2345
2346// Avoid extra level of indirection by making "pageheap" be just an alias
2347// of pageheap_memory.
2348typedef union {
2349 void* m_memory;
2350 TCMalloc_PageHeap* m_pageHeap;
2351} PageHeapUnion;
2352
2353static inline TCMalloc_PageHeap* getPageHeap()
2354{
2355 PageHeapUnion u = { &pageheap_memory[0] };
2356 return u.m_pageHeap;
2357}
2358
2359#define pageheap getPageHeap()
2360
2361#if USE_BACKGROUND_THREAD_TO_SCAVENGE_MEMORY
2362
2363#if !HAVE(DISPATCH_H)
2364#if OS(WINDOWS)
2365static void sleep(unsigned seconds)
2366{
2367 ::Sleep(seconds * 1000);
2368}
2369#endif
2370
2371void TCMalloc_PageHeap::scavengerThread()
2372{
2373#if HAVE(PTHREAD_SETNAME_NP)
2374 pthread_setname_np("JavaScriptCore: FastMalloc scavenger");
2375#endif
2376
2377 while (1) {
2378 if (!shouldScavenge()) {
2379 pthread_mutex_lock(&m_scavengeMutex);
2380 m_scavengeThreadActive = false;
2381 // Block until there are enough free committed pages to release back to the system.
2382 pthread_cond_wait(&m_scavengeCondition, &m_scavengeMutex);
2383 m_scavengeThreadActive = true;
2384 pthread_mutex_unlock(&m_scavengeMutex);
2385 }
2386 sleep(kScavengeDelayInSeconds);
2387 {
2388 SpinLockHolder h(&pageheap_lock);
2389 pageheap->scavenge();
2390 }
2391 }
2392}
2393
2394#else
2395
2396void TCMalloc_PageHeap::periodicScavenge()
2397{
2398 {
2399 SpinLockHolder h(&pageheap_lock);
2400 pageheap->scavenge();
2401 }
2402
2403 if (!shouldScavenge()) {
2404 m_scavengingScheduled = false;
2405 dispatch_suspend(m_scavengeTimer);
2406 }
2407}
2408#endif // HAVE(DISPATCH_H)
2409
2410#endif
2411
2412// If TLS is available, we also store a copy
2413// of the per-thread object in a __thread variable
2414// since __thread variables are faster to read
2415// than pthread_getspecific(). We still need
2416// pthread_setspecific() because __thread
2417// variables provide no way to run cleanup
2418// code when a thread is destroyed.
2419#ifdef HAVE_TLS
2420static __thread TCMalloc_ThreadCache *threadlocal_heap;
2421#endif
2422// Thread-specific key. Initialization here is somewhat tricky
2423// because some Linux startup code invokes malloc() before it
2424// is in a good enough state to handle pthread_keycreate().
2425// Therefore, we use TSD keys only after tsd_inited is set to true.
2426// Until then, we use a slow path to get the heap object.
2427static bool tsd_inited = false;
2428static pthread_key_t heap_key;
2429#if COMPILER(MSVC)
2430DWORD tlsIndex = TLS_OUT_OF_INDEXES;
2431#endif
2432
2433static ALWAYS_INLINE void setThreadHeap(TCMalloc_ThreadCache* heap)
2434{
2435 // still do pthread_setspecific when using MSVC fast TLS to
2436 // benefit from the delete callback.
2437 pthread_setspecific(heap_key, heap);
2438#if COMPILER(MSVC)
2439 TlsSetValue(tlsIndex, heap);
2440#endif
2441}
2442
2443// Allocator for thread heaps
2444static PageHeapAllocator<TCMalloc_ThreadCache> threadheap_allocator;
2445
2446// Linked list of heap objects. Protected by pageheap_lock.
2447static TCMalloc_ThreadCache* thread_heaps = NULL;
2448static int thread_heap_count = 0;
2449
2450// Overall thread cache size. Protected by pageheap_lock.
2451static size_t overall_thread_cache_size = kDefaultOverallThreadCacheSize;
2452
2453// Global per-thread cache size. Writes are protected by
2454// pageheap_lock. Reads are done without any locking, which should be
2455// fine as long as size_t can be written atomically and we don't place
2456// invariants between this variable and other pieces of state.
2457static volatile size_t per_thread_cache_size = kMaxThreadCacheSize;
2458
2459//-------------------------------------------------------------------
2460// Central cache implementation
2461//-------------------------------------------------------------------
2462
2463void TCMalloc_Central_FreeList::Init(size_t cl) {
2464 lock_.Init();
2465 size_class_ = cl;
2466 DLL_Init(&empty_);
2467 DLL_Init(&nonempty_);
2468 counter_ = 0;
2469
2470 cache_size_ = 1;
2471 used_slots_ = 0;
2472 ASSERT(cache_size_ <= kNumTransferEntries);
2473}
2474
2475void TCMalloc_Central_FreeList::ReleaseListToSpans(void* start) {
2476 while (start) {
2477 void *next = SLL_Next(start);
2478 ReleaseToSpans(start);
2479 start = next;
2480 }
2481}
2482
2483ALWAYS_INLINE void TCMalloc_Central_FreeList::ReleaseToSpans(void* object) {
2484 const PageID p = reinterpret_cast<uintptr_t>(object) >> kPageShift;
2485 Span* span = pageheap->GetDescriptor(p);
2486 ASSERT(span != NULL);
2487 ASSERT(span->refcount > 0);
2488
2489 // If span is empty, move it to non-empty list
2490 if (span->objects == NULL) {
2491 DLL_Remove(span);
2492 DLL_Prepend(&nonempty_, span);
2493 Event(span, 'N', 0);
2494 }
2495
2496 // The following check is expensive, so it is disabled by default
2497 if (false) {
2498 // Check that object does not occur in list
2499 unsigned got = 0;
2500 for (void* p = span->objects; p != NULL; p = *((void**) p)) {
2501 ASSERT(p != object);
2502 got++;
2503 }
2504 ASSERT(got + span->refcount ==
2505 (span->length<<kPageShift)/ByteSizeForClass(span->sizeclass));
2506 }
2507
2508 counter_++;
2509 span->refcount--;
2510 if (span->refcount == 0) {
2511 Event(span, '#', 0);
2512 counter_ -= (span->length<<kPageShift) / ByteSizeForClass(span->sizeclass);
2513 DLL_Remove(span);
2514
2515 // Release central list lock while operating on pageheap
2516 lock_.Unlock();
2517 {
2518 SpinLockHolder h(&pageheap_lock);
2519 pageheap->Delete(span);
2520 }
2521 lock_.Lock();
2522 } else {
2523 *(reinterpret_cast<void**>(object)) = span->objects;
2524 span->objects = object;
2525 }
2526}
2527
2528ALWAYS_INLINE bool TCMalloc_Central_FreeList::EvictRandomSizeClass(
2529 size_t locked_size_class, bool force) {
2530 static int race_counter = 0;
2531 int t = race_counter++; // Updated without a lock, but who cares.
2532 if (t >= static_cast<int>(kNumClasses)) {
2533 while (t >= static_cast<int>(kNumClasses)) {
2534 t -= kNumClasses;
2535 }
2536 race_counter = t;
2537 }
2538 ASSERT(t >= 0);
2539 ASSERT(t < static_cast<int>(kNumClasses));
2540 if (t == static_cast<int>(locked_size_class)) return false;
2541 return central_cache[t].ShrinkCache(static_cast<int>(locked_size_class), force);
2542}
2543
2544bool TCMalloc_Central_FreeList::MakeCacheSpace() {
2545 // Is there room in the cache?
2546 if (used_slots_ < cache_size_) return true;
2547 // Check if we can expand this cache?
2548 if (cache_size_ == kNumTransferEntries) return false;
2549 // Ok, we'll try to grab an entry from some other size class.
2550 if (EvictRandomSizeClass(size_class_, false) ||
2551 EvictRandomSizeClass(size_class_, true)) {
2552 // Succeeded in evicting, we're going to make our cache larger.
2553 cache_size_++;
2554 return true;
2555 }
2556 return false;
2557}
2558
2559
2560namespace {
2561class LockInverter {
2562 private:
2563 SpinLock *held_, *temp_;
2564 public:
2565 inline explicit LockInverter(SpinLock* held, SpinLock *temp)
2566 : held_(held), temp_(temp) { held_->Unlock(); temp_->Lock(); }
2567 inline ~LockInverter() { temp_->Unlock(); held_->Lock(); }
2568};
2569}
2570
2571bool TCMalloc_Central_FreeList::ShrinkCache(int locked_size_class, bool force) {
2572 // Start with a quick check without taking a lock.
2573 if (cache_size_ == 0) return false;
2574 // We don't evict from a full cache unless we are 'forcing'.
2575 if (force == false && used_slots_ == cache_size_) return false;
2576
2577 // Grab lock, but first release the other lock held by this thread. We use
2578 // the lock inverter to ensure that we never hold two size class locks
2579 // concurrently. That can create a deadlock because there is no well
2580 // defined nesting order.
2581 LockInverter li(&central_cache[locked_size_class].lock_, &lock_);
2582 ASSERT(used_slots_ <= cache_size_);
2583 ASSERT(0 <= cache_size_);
2584 if (cache_size_ == 0) return false;
2585 if (used_slots_ == cache_size_) {
2586 if (force == false) return false;
2587 // ReleaseListToSpans releases the lock, so we have to make all the
2588 // updates to the central list before calling it.
2589 cache_size_--;
2590 used_slots_--;
2591 ReleaseListToSpans(tc_slots_[used_slots_].head);
2592 return true;
2593 }
2594 cache_size_--;
2595 return true;
2596}
2597
2598void TCMalloc_Central_FreeList::InsertRange(void *start, void *end, int N) {
2599 SpinLockHolder h(&lock_);
2600 if (N == num_objects_to_move[size_class_] &&
2601 MakeCacheSpace()) {
2602 int slot = used_slots_++;
2603 ASSERT(slot >=0);
2604 ASSERT(slot < kNumTransferEntries);
2605 TCEntry *entry = &tc_slots_[slot];
2606 entry->head = start;
2607 entry->tail = end;
2608 return;
2609 }
2610 ReleaseListToSpans(start);
2611}
2612
2613void TCMalloc_Central_FreeList::RemoveRange(void **start, void **end, int *N) {
2614 int num = *N;
2615 ASSERT(num > 0);
2616
2617 SpinLockHolder h(&lock_);
2618 if (num == num_objects_to_move[size_class_] && used_slots_ > 0) {
2619 int slot = --used_slots_;
2620 ASSERT(slot >= 0);
2621 TCEntry *entry = &tc_slots_[slot];
2622 *start = entry->head;
2623 *end = entry->tail;
2624 return;
2625 }
2626
2627 // TODO: Prefetch multiple TCEntries?
2628 void *tail = FetchFromSpansSafe();
2629 if (!tail) {
2630 // We are completely out of memory.
2631 *start = *end = NULL;
2632 *N = 0;
2633 return;
2634 }
2635
2636 SLL_SetNext(tail, NULL);
2637 void *head = tail;
2638 int count = 1;
2639 while (count < num) {
2640 void *t = FetchFromSpans();
2641 if (!t) break;
2642 SLL_Push(&head, t);
2643 count++;
2644 }
2645 *start = head;
2646 *end = tail;
2647 *N = count;
2648}
2649
2650
2651void* TCMalloc_Central_FreeList::FetchFromSpansSafe() {
2652 void *t = FetchFromSpans();
2653 if (!t) {
2654 Populate();
2655 t = FetchFromSpans();
2656 }
2657 return t;
2658}
2659
2660void* TCMalloc_Central_FreeList::FetchFromSpans() {
2661 if (DLL_IsEmpty(&nonempty_)) return NULL;
2662 Span* span = nonempty_.next;
2663
2664 ASSERT(span->objects != NULL);
2665 ASSERT_SPAN_COMMITTED(span);
2666 span->refcount++;
2667 void* result = span->objects;
2668 span->objects = *(reinterpret_cast<void**>(result));
2669 if (span->objects == NULL) {
2670 // Move to empty list
2671 DLL_Remove(span);
2672 DLL_Prepend(&empty_, span);
2673 Event(span, 'E', 0);
2674 }
2675 counter_--;
2676 return result;
2677}
2678
2679// Fetch memory from the system and add to the central cache freelist.
2680ALWAYS_INLINE void TCMalloc_Central_FreeList::Populate() {
2681 // Release central list lock while operating on pageheap
2682 lock_.Unlock();
2683 const size_t npages = class_to_pages[size_class_];
2684
2685 Span* span;
2686 {
2687 SpinLockHolder h(&pageheap_lock);
2688 span = pageheap->New(npages);
2689 if (span) pageheap->RegisterSizeClass(span, size_class_);
2690 }
2691 if (span == NULL) {
2692#if HAVE(ERRNO_H)
2693 MESSAGE("allocation failed: %d\n", errno);
2694#elif OS(WINDOWS)
2695 MESSAGE("allocation failed: %d\n", ::GetLastError());
2696#else
2697 MESSAGE("allocation failed\n");
2698#endif
2699 lock_.Lock();
2700 return;
2701 }
2702 ASSERT_SPAN_COMMITTED(span);
2703 ASSERT(span->length == npages);
2704 // Cache sizeclass info eagerly. Locking is not necessary.
2705 // (Instead of being eager, we could just replace any stale info
2706 // about this span, but that seems to be no better in practice.)
2707 for (size_t i = 0; i < npages; i++) {
2708 pageheap->CacheSizeClass(span->start + i, size_class_);
2709 }
2710
2711 // Split the block into pieces and add to the free-list
2712 // TODO: coloring of objects to avoid cache conflicts?
2713 void** tail = &span->objects;
2714 char* ptr = reinterpret_cast<char*>(span->start << kPageShift);
2715 char* limit = ptr + (npages << kPageShift);
2716 const size_t size = ByteSizeForClass(size_class_);
2717 int num = 0;
2718 char* nptr;
2719 while ((nptr = ptr + size) <= limit) {
2720 *tail = ptr;
2721 tail = reinterpret_cast<void**>(ptr);
2722 ptr = nptr;
2723 num++;
2724 }
2725 ASSERT(ptr <= limit);
2726 *tail = NULL;
2727 span->refcount = 0; // No sub-object in use yet
2728
2729 // Add span to list of non-empty spans
2730 lock_.Lock();
2731 DLL_Prepend(&nonempty_, span);
2732 counter_ += num;
2733}
2734
2735//-------------------------------------------------------------------
2736// TCMalloc_ThreadCache implementation
2737//-------------------------------------------------------------------
2738
2739inline bool TCMalloc_ThreadCache::SampleAllocation(size_t k) {
2740 if (bytes_until_sample_ < k) {
2741 PickNextSample(k);
2742 return true;
2743 } else {
2744 bytes_until_sample_ -= k;
2745 return false;
2746 }
2747}
2748
2749void TCMalloc_ThreadCache::Init(ThreadIdentifier tid) {
2750 size_ = 0;
2751 next_ = NULL;
2752 prev_ = NULL;
2753 tid_ = tid;
2754 in_setspecific_ = false;
2755 for (size_t cl = 0; cl < kNumClasses; ++cl) {
2756 list_[cl].Init();
2757 }
2758
2759 // Initialize RNG -- run it for a bit to get to good values
2760 bytes_until_sample_ = 0;
2761 rnd_ = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(this));
2762 for (int i = 0; i < 100; i++) {
2763 PickNextSample(static_cast<size_t>(FLAGS_tcmalloc_sample_parameter * 2));
2764 }
2765}
2766
2767void TCMalloc_ThreadCache::Cleanup() {
2768 // Put unused memory back into central cache
2769 for (size_t cl = 0; cl < kNumClasses; ++cl) {
2770 if (list_[cl].length() > 0) {
2771 ReleaseToCentralCache(cl, list_[cl].length());
2772 }
2773 }
2774}
2775
2776ALWAYS_INLINE void* TCMalloc_ThreadCache::Allocate(size_t size) {
2777 ASSERT(size <= kMaxSize);
2778 const size_t cl = SizeClass(size);
2779 FreeList* list = &list_[cl];
2780 size_t allocationSize = ByteSizeForClass(cl);
2781 if (list->empty()) {
2782 FetchFromCentralCache(cl, allocationSize);
2783 if (list->empty()) return NULL;
2784 }
2785 size_ -= allocationSize;
2786 return list->Pop();
2787}
2788
2789inline void TCMalloc_ThreadCache::Deallocate(void* ptr, size_t cl) {
2790 size_ += ByteSizeForClass(cl);
2791 FreeList* list = &list_[cl];
2792 list->Push(ptr);
2793 // If enough data is free, put back into central cache
2794 if (list->length() > kMaxFreeListLength) {
2795 ReleaseToCentralCache(cl, num_objects_to_move[cl]);
2796 }
2797 if (size_ >= per_thread_cache_size) Scavenge();
2798}
2799
2800// Remove some objects of class "cl" from central cache and add to thread heap
2801ALWAYS_INLINE void TCMalloc_ThreadCache::FetchFromCentralCache(size_t cl, size_t allocationSize) {
2802 int fetch_count = num_objects_to_move[cl];
2803 void *start, *end;
2804 central_cache[cl].RemoveRange(&start, &end, &fetch_count);
2805 list_[cl].PushRange(fetch_count, start, end);
2806 size_ += allocationSize * fetch_count;
2807}
2808
2809// Remove some objects of class "cl" from thread heap and add to central cache
2810inline void TCMalloc_ThreadCache::ReleaseToCentralCache(size_t cl, int N) {
2811 ASSERT(N > 0);
2812 FreeList* src = &list_[cl];
2813 if (N > src->length()) N = src->length();
2814 size_ -= N*ByteSizeForClass(cl);
2815
2816 // We return prepackaged chains of the correct size to the central cache.
2817 // TODO: Use the same format internally in the thread caches?
2818 int batch_size = num_objects_to_move[cl];
2819 while (N > batch_size) {
2820 void *tail, *head;
2821 src->PopRange(batch_size, &head, &tail);
2822 central_cache[cl].InsertRange(head, tail, batch_size);
2823 N -= batch_size;
2824 }
2825 void *tail, *head;
2826 src->PopRange(N, &head, &tail);
2827 central_cache[cl].InsertRange(head, tail, N);
2828}
2829
2830// Release idle memory to the central cache
2831inline void TCMalloc_ThreadCache::Scavenge() {
2832 // If the low-water mark for the free list is L, it means we would
2833 // not have had to allocate anything from the central cache even if
2834 // we had reduced the free list size by L. We aim to get closer to
2835 // that situation by dropping L/2 nodes from the free list. This
2836 // may not release much memory, but if so we will call scavenge again
2837 // pretty soon and the low-water marks will be high on that call.
2838 //int64 start = CycleClock::Now();
2839
2840 for (size_t cl = 0; cl < kNumClasses; cl++) {
2841 FreeList* list = &list_[cl];
2842 const int lowmark = list->lowwatermark();
2843 if (lowmark > 0) {
2844 const int drop = (lowmark > 1) ? lowmark/2 : 1;
2845 ReleaseToCentralCache(cl, drop);
2846 }
2847 list->clear_lowwatermark();
2848 }
2849
2850 //int64 finish = CycleClock::Now();
2851 //CycleTimer ct;
2852 //MESSAGE("GC: %.0f ns\n", ct.CyclesToUsec(finish-start)*1000.0);
2853}
2854
2855void TCMalloc_ThreadCache::PickNextSample(size_t k) {
2856 // Make next "random" number
2857 // x^32+x^22+x^2+x^1+1 is a primitive polynomial for random numbers
2858 static const uint32_t kPoly = (1 << 22) | (1 << 2) | (1 << 1) | (1 << 0);
2859 uint32_t r = rnd_;
2860 rnd_ = (r << 1) ^ ((static_cast<int32_t>(r) >> 31) & kPoly);
2861
2862 // Next point is "rnd_ % (sample_period)". I.e., average
2863 // increment is "sample_period/2".
2864 const int flag_value = static_cast<int>(FLAGS_tcmalloc_sample_parameter);
2865 static int last_flag_value = -1;
2866
2867 if (flag_value != last_flag_value) {
2868 SpinLockHolder h(&sample_period_lock);
2869 int i;
2870 for (i = 0; i < (static_cast<int>(sizeof(primes_list)/sizeof(primes_list[0])) - 1); i++) {
2871 if (primes_list[i] >= flag_value) {
2872 break;
2873 }
2874 }
2875 sample_period = primes_list[i];
2876 last_flag_value = flag_value;
2877 }
2878
2879 bytes_until_sample_ += rnd_ % sample_period;
2880
2881 if (k > (static_cast<size_t>(-1) >> 2)) {
2882 // If the user has asked for a huge allocation then it is possible
2883 // for the code below to loop infinitely. Just return (note that
2884 // this throws off the sampling accuracy somewhat, but a user who
2885 // is allocating more than 1G of memory at a time can live with a
2886 // minor inaccuracy in profiling of small allocations, and also
2887 // would rather not wait for the loop below to terminate).
2888 return;
2889 }
2890
2891 while (bytes_until_sample_ < k) {
2892 // Increase bytes_until_sample_ by enough average sampling periods
2893 // (sample_period >> 1) to allow us to sample past the current
2894 // allocation.
2895 bytes_until_sample_ += (sample_period >> 1);
2896 }
2897
2898 bytes_until_sample_ -= k;
2899}
2900
2901void TCMalloc_ThreadCache::InitModule() {
2902 // There is a slight potential race here because of double-checked
2903 // locking idiom. However, as long as the program does a small
2904 // allocation before switching to multi-threaded mode, we will be
2905 // fine. We increase the chances of doing such a small allocation
2906 // by doing one in the constructor of the module_enter_exit_hook
2907 // object declared below.
2908 SpinLockHolder h(&pageheap_lock);
2909 if (!phinited) {
2910#ifdef WTF_CHANGES
2911 InitTSD();
2912#endif
2913 InitSizeClasses();
2914 threadheap_allocator.Init();
2915 span_allocator.Init();
2916 span_allocator.New(); // Reduce cache conflicts
2917 span_allocator.New(); // Reduce cache conflicts
2918 stacktrace_allocator.Init();
2919 DLL_Init(&sampled_objects);
2920 for (size_t i = 0; i < kNumClasses; ++i) {
2921 central_cache[i].Init(i);
2922 }
2923 pageheap->init();
2924 phinited = 1;
2925#if defined(WTF_CHANGES) && OS(DARWIN)
2926 FastMallocZone::init();
2927#endif
2928 }
2929}
2930
2931inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::NewHeap(ThreadIdentifier tid) {
2932 // Create the heap and add it to the linked list
2933 TCMalloc_ThreadCache *heap = threadheap_allocator.New();
2934 heap->Init(tid);
2935 heap->next_ = thread_heaps;
2936 heap->prev_ = NULL;
2937 if (thread_heaps != NULL) thread_heaps->prev_ = heap;
2938 thread_heaps = heap;
2939 thread_heap_count++;
2940 RecomputeThreadCacheSize();
2941 return heap;
2942}
2943
2944inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetThreadHeap() {
2945#ifdef HAVE_TLS
2946 // __thread is faster, but only when the kernel supports it
2947 if (KernelSupportsTLS())
2948 return threadlocal_heap;
2949#elif COMPILER(MSVC)
2950 return static_cast<TCMalloc_ThreadCache*>(TlsGetValue(tlsIndex));
2951#else
2952 return static_cast<TCMalloc_ThreadCache*>(pthread_getspecific(heap_key));
2953#endif
2954}
2955
2956inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCache() {
2957 TCMalloc_ThreadCache* ptr = NULL;
2958 if (!tsd_inited) {
2959 InitModule();
2960 } else {
2961 ptr = GetThreadHeap();
2962 }
2963 if (ptr == NULL) ptr = CreateCacheIfNecessary();
2964 return ptr;
2965}
2966
2967// In deletion paths, we do not try to create a thread-cache. This is
2968// because we may be in the thread destruction code and may have
2969// already cleaned up the cache for this thread.
2970inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCacheIfPresent() {
2971 if (!tsd_inited) return NULL;
2972 void* const p = GetThreadHeap();
2973 return reinterpret_cast<TCMalloc_ThreadCache*>(p);
2974}
2975
2976void TCMalloc_ThreadCache::InitTSD() {
2977 ASSERT(!tsd_inited);
2978 pthread_key_create(&heap_key, DestroyThreadCache);
2979#if COMPILER(MSVC)
2980 tlsIndex = TlsAlloc();
2981#endif
2982 tsd_inited = true;
2983
2984#if !COMPILER(MSVC)
2985 // We may have used a fake pthread_t for the main thread. Fix it.
2986 pthread_t zero;
2987 memset(&zero, 0, sizeof(zero));
2988#endif
2989#ifndef WTF_CHANGES
2990 SpinLockHolder h(&pageheap_lock);
2991#else
2992 ASSERT(pageheap_lock.IsHeld());
2993#endif
2994 for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
2995#if COMPILER(MSVC)
2996 if (h->tid_ == 0) {
2997 h->tid_ = GetCurrentThreadId();
2998 }
2999#else
3000 if (pthread_equal(h->tid_, zero)) {
3001 h->tid_ = pthread_self();
3002 }
3003#endif
3004 }
3005}
3006
3007TCMalloc_ThreadCache* TCMalloc_ThreadCache::CreateCacheIfNecessary() {
3008 // Initialize per-thread data if necessary
3009 TCMalloc_ThreadCache* heap = NULL;
3010 {
3011 SpinLockHolder h(&pageheap_lock);
3012
3013#if COMPILER(MSVC)
3014 DWORD me;
3015 if (!tsd_inited) {
3016 me = 0;
3017 } else {
3018 me = GetCurrentThreadId();
3019 }
3020#else
3021 // Early on in glibc's life, we cannot even call pthread_self()
3022 pthread_t me;
3023 if (!tsd_inited) {
3024 memset(&me, 0, sizeof(me));
3025 } else {
3026 me = pthread_self();
3027 }
3028#endif
3029
3030 // This may be a recursive malloc call from pthread_setspecific()
3031 // In that case, the heap for this thread has already been created
3032 // and added to the linked list. So we search for that first.
3033 for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
3034#if COMPILER(MSVC)
3035 if (h->tid_ == me) {
3036#else
3037 if (pthread_equal(h->tid_, me)) {
3038#endif
3039 heap = h;
3040 break;
3041 }
3042 }
3043
3044 if (heap == NULL) heap = NewHeap(me);
3045 }
3046
3047 // We call pthread_setspecific() outside the lock because it may
3048 // call malloc() recursively. The recursive call will never get
3049 // here again because it will find the already allocated heap in the
3050 // linked list of heaps.
3051 if (!heap->in_setspecific_ && tsd_inited) {
3052 heap->in_setspecific_ = true;
3053 setThreadHeap(heap);
3054 }
3055 return heap;
3056}
3057
3058void TCMalloc_ThreadCache::BecomeIdle() {
3059 if (!tsd_inited) return; // No caches yet
3060 TCMalloc_ThreadCache* heap = GetThreadHeap();
3061 if (heap == NULL) return; // No thread cache to remove
3062 if (heap->in_setspecific_) return; // Do not disturb the active caller
3063
3064 heap->in_setspecific_ = true;
3065 setThreadHeap(NULL);
3066#ifdef HAVE_TLS
3067 // Also update the copy in __thread
3068 threadlocal_heap = NULL;
3069#endif
3070 heap->in_setspecific_ = false;
3071 if (GetThreadHeap() == heap) {
3072 // Somehow heap got reinstated by a recursive call to malloc
3073 // from pthread_setspecific. We give up in this case.
3074 return;
3075 }
3076
3077 // We can now get rid of the heap
3078 DeleteCache(heap);
3079}
3080
3081void TCMalloc_ThreadCache::DestroyThreadCache(void* ptr) {
3082 // Note that "ptr" cannot be NULL since pthread promises not
3083 // to invoke the destructor on NULL values, but for safety,
3084 // we check anyway.
3085 if (ptr == NULL) return;
3086#ifdef HAVE_TLS
3087 // Prevent fast path of GetThreadHeap() from returning heap.
3088 threadlocal_heap = NULL;
3089#endif
3090 DeleteCache(reinterpret_cast<TCMalloc_ThreadCache*>(ptr));
3091}
3092
3093void TCMalloc_ThreadCache::DeleteCache(TCMalloc_ThreadCache* heap) {
3094 // Remove all memory from heap
3095 heap->Cleanup();
3096
3097 // Remove from linked list
3098 SpinLockHolder h(&pageheap_lock);
3099 if (heap->next_ != NULL) heap->next_->prev_ = heap->prev_;
3100 if (heap->prev_ != NULL) heap->prev_->next_ = heap->next_;
3101 if (thread_heaps == heap) thread_heaps = heap->next_;
3102 thread_heap_count--;
3103 RecomputeThreadCacheSize();
3104
3105 threadheap_allocator.Delete(heap);
3106}
3107
3108void TCMalloc_ThreadCache::RecomputeThreadCacheSize() {
3109 // Divide available space across threads
3110 int n = thread_heap_count > 0 ? thread_heap_count : 1;
3111 size_t space = overall_thread_cache_size / n;
3112
3113 // Limit to allowed range
3114 if (space < kMinThreadCacheSize) space = kMinThreadCacheSize;
3115 if (space > kMaxThreadCacheSize) space = kMaxThreadCacheSize;
3116
3117 per_thread_cache_size = space;
3118}
3119
3120void TCMalloc_ThreadCache::Print() const {
3121 for (size_t cl = 0; cl < kNumClasses; ++cl) {
3122 MESSAGE(" %5" PRIuS " : %4d len; %4d lo\n",
3123 ByteSizeForClass(cl),
3124 list_[cl].length(),
3125 list_[cl].lowwatermark());
3126 }
3127}
3128
3129// Extract interesting stats
3130struct TCMallocStats {
3131 uint64_t system_bytes; // Bytes alloced from system
3132 uint64_t thread_bytes; // Bytes in thread caches
3133 uint64_t central_bytes; // Bytes in central cache
3134 uint64_t transfer_bytes; // Bytes in central transfer cache
3135 uint64_t pageheap_bytes; // Bytes in page heap
3136 uint64_t metadata_bytes; // Bytes alloced for metadata
3137};
3138
3139#ifndef WTF_CHANGES
3140// Get stats into "r". Also get per-size-class counts if class_count != NULL
3141static void ExtractStats(TCMallocStats* r, uint64_t* class_count) {
3142 r->central_bytes = 0;
3143 r->transfer_bytes = 0;
3144 for (int cl = 0; cl < kNumClasses; ++cl) {
3145 const int length = central_cache[cl].length();
3146 const int tc_length = central_cache[cl].tc_length();
3147 r->central_bytes += static_cast<uint64_t>(ByteSizeForClass(cl)) * length;
3148 r->transfer_bytes +=
3149 static_cast<uint64_t>(ByteSizeForClass(cl)) * tc_length;
3150 if (class_count) class_count[cl] = length + tc_length;
3151 }
3152
3153 // Add stats from per-thread heaps
3154 r->thread_bytes = 0;
3155 { // scope
3156 SpinLockHolder h(&pageheap_lock);
3157 for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
3158 r->thread_bytes += h->Size();
3159 if (class_count) {
3160 for (size_t cl = 0; cl < kNumClasses; ++cl) {
3161 class_count[cl] += h->freelist_length(cl);
3162 }
3163 }
3164 }
3165 }
3166
3167 { //scope
3168 SpinLockHolder h(&pageheap_lock);
3169 r->system_bytes = pageheap->SystemBytes();
3170 r->metadata_bytes = metadata_system_bytes;
3171 r->pageheap_bytes = pageheap->FreeBytes();
3172 }
3173}
3174#endif
3175
3176#ifndef WTF_CHANGES
3177// WRITE stats to "out"
3178static void DumpStats(TCMalloc_Printer* out, int level) {
3179 TCMallocStats stats;
3180 uint64_t class_count[kNumClasses];
3181 ExtractStats(&stats, (level >= 2 ? class_count : NULL));
3182
3183 if (level >= 2) {
3184 out->printf("------------------------------------------------\n");
3185 uint64_t cumulative = 0;
3186 for (int cl = 0; cl < kNumClasses; ++cl) {
3187 if (class_count[cl] > 0) {
3188 uint64_t class_bytes = class_count[cl] * ByteSizeForClass(cl);
3189 cumulative += class_bytes;
3190 out->printf("class %3d [ %8" PRIuS " bytes ] : "
3191 "%8" PRIu64 " objs; %5.1f MB; %5.1f cum MB\n",
3192 cl, ByteSizeForClass(cl),
3193 class_count[cl],
3194 class_bytes / 1048576.0,
3195 cumulative / 1048576.0);
3196 }
3197 }
3198
3199 SpinLockHolder h(&pageheap_lock);
3200 pageheap->Dump(out);
3201 }
3202
3203 const uint64_t bytes_in_use = stats.system_bytes
3204 - stats.pageheap_bytes
3205 - stats.central_bytes
3206 - stats.transfer_bytes
3207 - stats.thread_bytes;
3208
3209 out->printf("------------------------------------------------\n"
3210 "MALLOC: %12" PRIu64 " Heap size\n"
3211 "MALLOC: %12" PRIu64 " Bytes in use by application\n"
3212 "MALLOC: %12" PRIu64 " Bytes free in page heap\n"
3213 "MALLOC: %12" PRIu64 " Bytes free in central cache\n"
3214 "MALLOC: %12" PRIu64 " Bytes free in transfer cache\n"
3215 "MALLOC: %12" PRIu64 " Bytes free in thread caches\n"
3216 "MALLOC: %12" PRIu64 " Spans in use\n"
3217 "MALLOC: %12" PRIu64 " Thread heaps in use\n"
3218 "MALLOC: %12" PRIu64 " Metadata allocated\n"
3219 "------------------------------------------------\n",
3220 stats.system_bytes,
3221 bytes_in_use,
3222 stats.pageheap_bytes,
3223 stats.central_bytes,
3224 stats.transfer_bytes,
3225 stats.thread_bytes,
3226 uint64_t(span_allocator.inuse()),
3227 uint64_t(threadheap_allocator.inuse()),
3228 stats.metadata_bytes);
3229}
3230
3231static void PrintStats(int level) {
3232 const int kBufferSize = 16 << 10;
3233 char* buffer = new char[kBufferSize];
3234 TCMalloc_Printer printer(buffer, kBufferSize);
3235 DumpStats(&printer, level);
3236 write(STDERR_FILENO, buffer, strlen(buffer));
3237 delete[] buffer;
3238}
3239
3240static void** DumpStackTraces() {
3241 // Count how much space we need
3242 int needed_slots = 0;
3243 {
3244 SpinLockHolder h(&pageheap_lock);
3245 for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
3246 StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
3247 needed_slots += 3 + stack->depth;
3248 }
3249 needed_slots += 100; // Slop in case sample grows
3250 needed_slots += needed_slots/8; // An extra 12.5% slop
3251 }
3252
3253 void** result = new void*[needed_slots];
3254 if (result == NULL) {
3255 MESSAGE("tcmalloc: could not allocate %d slots for stack traces\n",
3256 needed_slots);
3257 return NULL;
3258 }
3259
3260 SpinLockHolder h(&pageheap_lock);
3261 int used_slots = 0;
3262 for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
3263 ASSERT(used_slots < needed_slots); // Need to leave room for terminator
3264 StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
3265 if (used_slots + 3 + stack->depth >= needed_slots) {
3266 // No more room
3267 break;
3268 }
3269
3270 result[used_slots+0] = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
3271 result[used_slots+1] = reinterpret_cast<void*>(stack->size);
3272 result[used_slots+2] = reinterpret_cast<void*>(stack->depth);
3273 for (int d = 0; d < stack->depth; d++) {
3274 result[used_slots+3+d] = stack->stack[d];
3275 }
3276 used_slots += 3 + stack->depth;
3277 }
3278 result[used_slots] = reinterpret_cast<void*>(static_cast<uintptr_t>(0));
3279 return result;
3280}
3281#endif
3282
3283#ifndef WTF_CHANGES
3284
3285// TCMalloc's support for extra malloc interfaces
3286class TCMallocImplementation : public MallocExtension {
3287 public:
3288 virtual void GetStats(char* buffer, int buffer_length) {
3289 ASSERT(buffer_length > 0);
3290 TCMalloc_Printer printer(buffer, buffer_length);
3291
3292 // Print level one stats unless lots of space is available
3293 if (buffer_length < 10000) {
3294 DumpStats(&printer, 1);
3295 } else {
3296 DumpStats(&printer, 2);
3297 }
3298 }
3299
3300 virtual void** ReadStackTraces() {
3301 return DumpStackTraces();
3302 }
3303
3304 virtual bool GetNumericProperty(const char* name, size_t* value) {
3305 ASSERT(name != NULL);
3306
3307 if (strcmp(name, "generic.current_allocated_bytes") == 0) {
3308 TCMallocStats stats;
3309 ExtractStats(&stats, NULL);
3310 *value = stats.system_bytes
3311 - stats.thread_bytes
3312 - stats.central_bytes
3313 - stats.pageheap_bytes;
3314 return true;
3315 }
3316
3317 if (strcmp(name, "generic.heap_size") == 0) {
3318 TCMallocStats stats;
3319 ExtractStats(&stats, NULL);
3320 *value = stats.system_bytes;
3321 return true;
3322 }
3323
3324 if (strcmp(name, "tcmalloc.slack_bytes") == 0) {
3325 // We assume that bytes in the page heap are not fragmented too
3326 // badly, and are therefore available for allocation.
3327 SpinLockHolder l(&pageheap_lock);
3328 *value = pageheap->FreeBytes();
3329 return true;
3330 }
3331
3332 if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
3333 SpinLockHolder l(&pageheap_lock);
3334 *value = overall_thread_cache_size;
3335 return true;
3336 }
3337
3338 if (strcmp(name, "tcmalloc.current_total_thread_cache_bytes") == 0) {
3339 TCMallocStats stats;
3340 ExtractStats(&stats, NULL);
3341 *value = stats.thread_bytes;
3342 return true;
3343 }
3344
3345 return false;
3346 }
3347
3348 virtual bool SetNumericProperty(const char* name, size_t value) {
3349 ASSERT(name != NULL);
3350
3351 if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
3352 // Clip the value to a reasonable range
3353 if (value < kMinThreadCacheSize) value = kMinThreadCacheSize;
3354 if (value > (1<<30)) value = (1<<30); // Limit to 1GB
3355
3356 SpinLockHolder l(&pageheap_lock);
3357 overall_thread_cache_size = static_cast<size_t>(value);
3358 TCMalloc_ThreadCache::RecomputeThreadCacheSize();
3359 return true;
3360 }
3361
3362 return false;
3363 }
3364
3365 virtual void MarkThreadIdle() {
3366 TCMalloc_ThreadCache::BecomeIdle();
3367 }
3368
3369 virtual void ReleaseFreeMemory() {
3370 SpinLockHolder h(&pageheap_lock);
3371 pageheap->ReleaseFreePages();
3372 }
3373};
3374#endif
3375
3376// The constructor allocates an object to ensure that initialization
3377// runs before main(), and therefore we do not have a chance to become
3378// multi-threaded before initialization. We also create the TSD key
3379// here. Presumably by the time this constructor runs, glibc is in
3380// good enough shape to handle pthread_key_create().
3381//
3382// The constructor also takes the opportunity to tell STL to use
3383// tcmalloc. We want to do this early, before construct time, so
3384// all user STL allocations go through tcmalloc (which works really
3385// well for STL).
3386//
3387// The destructor prints stats when the program exits.
3388class TCMallocGuard {
3389 public:
3390
3391 TCMallocGuard() {
3392#ifdef HAVE_TLS // this is true if the cc/ld/libc combo support TLS
3393 // Check whether the kernel also supports TLS (needs to happen at runtime)
3394 CheckIfKernelSupportsTLS();
3395#endif
3396#ifndef WTF_CHANGES
3397#ifdef WIN32 // patch the windows VirtualAlloc, etc.
3398 PatchWindowsFunctions(); // defined in windows/patch_functions.cc
3399#endif
3400#endif
3401 free(malloc(1));
3402 TCMalloc_ThreadCache::InitTSD();
3403 free(malloc(1));
3404#ifndef WTF_CHANGES
3405 MallocExtension::Register(new TCMallocImplementation);
3406#endif
3407 }
3408
3409#ifndef WTF_CHANGES
3410 ~TCMallocGuard() {
3411 const char* env = getenv("MALLOCSTATS");
3412 if (env != NULL) {
3413 int level = atoi(env);
3414 if (level < 1) level = 1;
3415 PrintStats(level);
3416 }
3417#ifdef WIN32
3418 UnpatchWindowsFunctions();
3419#endif
3420 }
3421#endif
3422};
3423
3424#ifndef WTF_CHANGES
3425static TCMallocGuard module_enter_exit_hook;
3426#endif
3427
3428
3429//-------------------------------------------------------------------
3430// Helpers for the exported routines below
3431//-------------------------------------------------------------------
3432
3433#ifndef WTF_CHANGES
3434
3435static Span* DoSampledAllocation(size_t size) {
3436
3437 // Grab the stack trace outside the heap lock
3438 StackTrace tmp;
3439 tmp.depth = GetStackTrace(tmp.stack, kMaxStackDepth, 1);
3440 tmp.size = size;
3441
3442 SpinLockHolder h(&pageheap_lock);
3443 // Allocate span
3444 Span *span = pageheap->New(pages(size == 0 ? 1 : size));
3445 if (span == NULL) {
3446 return NULL;
3447 }
3448
3449 // Allocate stack trace
3450 StackTrace *stack = stacktrace_allocator.New();
3451 if (stack == NULL) {
3452 // Sampling failed because of lack of memory
3453 return span;
3454 }
3455
3456 *stack = tmp;
3457 span->sample = 1;
3458 span->objects = stack;
3459 DLL_Prepend(&sampled_objects, span);
3460
3461 return span;
3462}
3463#endif
3464
3465static inline bool CheckCachedSizeClass(void *ptr) {
3466 PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
3467 size_t cached_value = pageheap->GetSizeClassIfCached(p);
3468 return cached_value == 0 ||
3469 cached_value == pageheap->GetDescriptor(p)->sizeclass;
3470}
3471
3472static inline void* CheckedMallocResult(void *result)
3473{
3474 ASSERT(result == 0 || CheckCachedSizeClass(result));
3475 return result;
3476}
3477
3478static inline void* SpanToMallocResult(Span *span) {
3479 ASSERT_SPAN_COMMITTED(span);
3480 pageheap->CacheSizeClass(span->start, 0);
3481 return
3482 CheckedMallocResult(reinterpret_cast<void*>(span->start << kPageShift));
3483}
3484
3485#ifdef WTF_CHANGES
3486template <bool crashOnFailure>
3487#endif
3488static ALWAYS_INLINE void* do_malloc(size_t size) {
3489 void* ret = NULL;
3490
3491#ifdef WTF_CHANGES
3492 ASSERT(!isForbidden());
3493#endif
3494
3495 // The following call forces module initialization
3496 TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
3497#ifndef WTF_CHANGES
3498 if ((FLAGS_tcmalloc_sample_parameter > 0) && heap->SampleAllocation(size)) {
3499 Span* span = DoSampledAllocation(size);
3500 if (span != NULL) {
3501 ret = SpanToMallocResult(span);
3502 }
3503 } else
3504#endif
3505 if (size > kMaxSize) {
3506 // Use page-level allocator
3507 SpinLockHolder h(&pageheap_lock);
3508 Span* span = pageheap->New(pages(size));
3509 if (span != NULL) {
3510 ret = SpanToMallocResult(span);
3511 }
3512 } else {
3513 // The common case, and also the simplest. This just pops the
3514 // size-appropriate freelist, afer replenishing it if it's empty.
3515 ret = CheckedMallocResult(heap->Allocate(size));
3516 }
3517 if (!ret) {
3518#ifdef WTF_CHANGES
3519 if (crashOnFailure) // This branch should be optimized out by the compiler.
3520 CRASH();
3521#else
3522 errno = ENOMEM;
3523#endif
3524 }
3525 return ret;
3526}
3527
3528static ALWAYS_INLINE void do_free(void* ptr) {
3529 if (ptr == NULL) return;
3530 ASSERT(pageheap != NULL); // Should not call free() before malloc()
3531 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
3532 Span* span = NULL;
3533 size_t cl = pageheap->GetSizeClassIfCached(p);
3534
3535 if (cl == 0) {
3536 span = pageheap->GetDescriptor(p);
3537 cl = span->sizeclass;
3538 pageheap->CacheSizeClass(p, cl);
3539 }
3540 if (cl != 0) {
3541#ifndef NO_TCMALLOC_SAMPLES
3542 ASSERT(!pageheap->GetDescriptor(p)->sample);
3543#endif
3544 TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCacheIfPresent();
3545 if (heap != NULL) {
3546 heap->Deallocate(ptr, cl);
3547 } else {
3548 // Delete directly into central cache
3549 SLL_SetNext(ptr, NULL);
3550 central_cache[cl].InsertRange(ptr, ptr, 1);
3551 }
3552 } else {
3553 SpinLockHolder h(&pageheap_lock);
3554 ASSERT(reinterpret_cast<uintptr_t>(ptr) % kPageSize == 0);
3555 ASSERT(span != NULL && span->start == p);
3556#ifndef NO_TCMALLOC_SAMPLES
3557 if (span->sample) {
3558 DLL_Remove(span);
3559 stacktrace_allocator.Delete(reinterpret_cast<StackTrace*>(span->objects));
3560 span->objects = NULL;
3561 }
3562#endif
3563 pageheap->Delete(span);
3564 }
3565}
3566
3567#ifndef WTF_CHANGES
3568// For use by exported routines below that want specific alignments
3569//
3570// Note: this code can be slow, and can significantly fragment memory.
3571// The expectation is that memalign/posix_memalign/valloc/pvalloc will
3572// not be invoked very often. This requirement simplifies our
3573// implementation and allows us to tune for expected allocation
3574// patterns.
3575static void* do_memalign(size_t align, size_t size) {
3576 ASSERT((align & (align - 1)) == 0);
3577 ASSERT(align > 0);
3578 if (pageheap == NULL) TCMalloc_ThreadCache::InitModule();
3579
3580 // Allocate at least one byte to avoid boundary conditions below
3581 if (size == 0) size = 1;
3582
3583 if (size <= kMaxSize && align < kPageSize) {
3584 // Search through acceptable size classes looking for one with
3585 // enough alignment. This depends on the fact that
3586 // InitSizeClasses() currently produces several size classes that
3587 // are aligned at powers of two. We will waste time and space if
3588 // we miss in the size class array, but that is deemed acceptable
3589 // since memalign() should be used rarely.
3590 size_t cl = SizeClass(size);
3591 while (cl < kNumClasses && ((class_to_size[cl] & (align - 1)) != 0)) {
3592 cl++;
3593 }
3594 if (cl < kNumClasses) {
3595 TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
3596 return CheckedMallocResult(heap->Allocate(class_to_size[cl]));
3597 }
3598 }
3599
3600 // We will allocate directly from the page heap
3601 SpinLockHolder h(&pageheap_lock);
3602
3603 if (align <= kPageSize) {
3604 // Any page-level allocation will be fine
3605 // TODO: We could put the rest of this page in the appropriate
3606 // TODO: cache but it does not seem worth it.
3607 Span* span = pageheap->New(pages(size));
3608 return span == NULL ? NULL : SpanToMallocResult(span);
3609 }
3610
3611 // Allocate extra pages and carve off an aligned portion
3612 const Length alloc = pages(size + align);
3613 Span* span = pageheap->New(alloc);
3614 if (span == NULL) return NULL;
3615
3616 // Skip starting portion so that we end up aligned
3617 Length skip = 0;
3618 while ((((span->start+skip) << kPageShift) & (align - 1)) != 0) {
3619 skip++;
3620 }
3621 ASSERT(skip < alloc);
3622 if (skip > 0) {
3623 Span* rest = pageheap->Split(span, skip);
3624 pageheap->Delete(span);
3625 span = rest;
3626 }
3627
3628 // Skip trailing portion that we do not need to return
3629 const Length needed = pages(size);
3630 ASSERT(span->length >= needed);
3631 if (span->length > needed) {
3632 Span* trailer = pageheap->Split(span, needed);
3633 pageheap->Delete(trailer);
3634 }
3635 return SpanToMallocResult(span);
3636}
3637#endif
3638
3639// Helpers for use by exported routines below:
3640
3641#ifndef WTF_CHANGES
3642static inline void do_malloc_stats() {
3643 PrintStats(1);
3644}
3645#endif
3646
3647static inline int do_mallopt(int, int) {
3648 return 1; // Indicates error
3649}
3650
3651#ifdef HAVE_STRUCT_MALLINFO // mallinfo isn't defined on freebsd, for instance
3652static inline struct mallinfo do_mallinfo() {
3653 TCMallocStats stats;
3654 ExtractStats(&stats, NULL);
3655
3656 // Just some of the fields are filled in.
3657 struct mallinfo info;
3658 memset(&info, 0, sizeof(info));
3659
3660 // Unfortunately, the struct contains "int" field, so some of the
3661 // size values will be truncated.
3662 info.arena = static_cast<int>(stats.system_bytes);
3663 info.fsmblks = static_cast<int>(stats.thread_bytes
3664 + stats.central_bytes
3665 + stats.transfer_bytes);
3666 info.fordblks = static_cast<int>(stats.pageheap_bytes);
3667 info.uordblks = static_cast<int>(stats.system_bytes
3668 - stats.thread_bytes
3669 - stats.central_bytes
3670 - stats.transfer_bytes
3671 - stats.pageheap_bytes);
3672
3673 return info;
3674}
3675#endif
3676
3677//-------------------------------------------------------------------
3678// Exported routines
3679//-------------------------------------------------------------------
3680
3681// CAVEAT: The code structure below ensures that MallocHook methods are always
3682// called from the stack frame of the invoked allocation function.
3683// heap-checker.cc depends on this to start a stack trace from
3684// the call to the (de)allocation function.
3685
3686#ifndef WTF_CHANGES
3687extern "C"
3688#else
3689#define do_malloc do_malloc<crashOnFailure>
3690
3691template <bool crashOnFailure>
3692void* malloc(size_t);
3693
3694void* fastMalloc(size_t size)
3695{
3696 return malloc<true>(size);
3697}
3698
3699TryMallocReturnValue tryFastMalloc(size_t size)
3700{
3701 return malloc<false>(size);
3702}
3703
3704template <bool crashOnFailure>
3705ALWAYS_INLINE
3706#endif
3707void* malloc(size_t size) {
3708#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3709 if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= size) // If overflow would occur...
3710 return 0;
3711 size += sizeof(AllocAlignmentInteger);
3712 void* result = do_malloc(size);
3713 if (!result)
3714 return 0;
3715
3716 *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
3717 result = static_cast<AllocAlignmentInteger*>(result) + 1;
3718#else
3719 void* result = do_malloc(size);
3720#endif
3721
3722#ifndef WTF_CHANGES
3723 MallocHook::InvokeNewHook(result, size);
3724#endif
3725 return result;
3726}
3727
3728#ifndef WTF_CHANGES
3729extern "C"
3730#endif
3731void free(void* ptr) {
3732#ifndef WTF_CHANGES
3733 MallocHook::InvokeDeleteHook(ptr);
3734#endif
3735
3736#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3737 if (!ptr)
3738 return;
3739
3740 AllocAlignmentInteger* header = Internal::fastMallocMatchValidationValue(ptr);
3741 if (*header != Internal::AllocTypeMalloc)
3742 Internal::fastMallocMatchFailed(ptr);
3743 do_free(header);
3744#else
3745 do_free(ptr);
3746#endif
3747}
3748
3749#ifndef WTF_CHANGES
3750extern "C"
3751#else
3752template <bool crashOnFailure>
3753void* calloc(size_t, size_t);
3754
3755void* fastCalloc(size_t n, size_t elem_size)
3756{
3757 return calloc<true>(n, elem_size);
3758}
3759
3760TryMallocReturnValue tryFastCalloc(size_t n, size_t elem_size)
3761{
3762 return calloc<false>(n, elem_size);
3763}
3764
3765template <bool crashOnFailure>
3766ALWAYS_INLINE
3767#endif
3768void* calloc(size_t n, size_t elem_size) {
3769 size_t totalBytes = n * elem_size;
3770
3771 // Protect against overflow
3772 if (n > 1 && elem_size && (totalBytes / elem_size) != n)
3773 return 0;
3774
3775#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3776 if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= totalBytes) // If overflow would occur...
3777 return 0;
3778
3779 totalBytes += sizeof(AllocAlignmentInteger);
3780 void* result = do_malloc(totalBytes);
3781 if (!result)
3782 return 0;
3783
3784 memset(result, 0, totalBytes);
3785 *static_cast<AllocAlignmentInteger*>(result) = Internal::AllocTypeMalloc;
3786 result = static_cast<AllocAlignmentInteger*>(result) + 1;
3787#else
3788 void* result = do_malloc(totalBytes);
3789 if (result != NULL) {
3790 memset(result, 0, totalBytes);
3791 }
3792#endif
3793
3794#ifndef WTF_CHANGES
3795 MallocHook::InvokeNewHook(result, totalBytes);
3796#endif
3797 return result;
3798}
3799
3800// Since cfree isn't used anywhere, we don't compile it in.
3801#ifndef WTF_CHANGES
3802#ifndef WTF_CHANGES
3803extern "C"
3804#endif
3805void cfree(void* ptr) {
3806#ifndef WTF_CHANGES
3807 MallocHook::InvokeDeleteHook(ptr);
3808#endif
3809 do_free(ptr);
3810}
3811#endif
3812
3813#ifndef WTF_CHANGES
3814extern "C"
3815#else
3816template <bool crashOnFailure>
3817void* realloc(void*, size_t);
3818
3819void* fastRealloc(void* old_ptr, size_t new_size)
3820{
3821 return realloc<true>(old_ptr, new_size);
3822}
3823
3824TryMallocReturnValue tryFastRealloc(void* old_ptr, size_t new_size)
3825{
3826 return realloc<false>(old_ptr, new_size);
3827}
3828
3829template <bool crashOnFailure>
3830ALWAYS_INLINE
3831#endif
3832void* realloc(void* old_ptr, size_t new_size) {
3833 if (old_ptr == NULL) {
3834#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3835 void* result = malloc(new_size);
3836#else
3837 void* result = do_malloc(new_size);
3838#ifndef WTF_CHANGES
3839 MallocHook::InvokeNewHook(result, new_size);
3840#endif
3841#endif
3842 return result;
3843 }
3844 if (new_size == 0) {
3845#ifndef WTF_CHANGES
3846 MallocHook::InvokeDeleteHook(old_ptr);
3847#endif
3848 free(old_ptr);
3849 return NULL;
3850 }
3851
3852#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3853 if (std::numeric_limits<size_t>::max() - sizeof(AllocAlignmentInteger) <= new_size) // If overflow would occur...
3854 return 0;
3855 new_size += sizeof(AllocAlignmentInteger);
3856 AllocAlignmentInteger* header = Internal::fastMallocMatchValidationValue(old_ptr);
3857 if (*header != Internal::AllocTypeMalloc)
3858 Internal::fastMallocMatchFailed(old_ptr);
3859 old_ptr = header;
3860#endif
3861
3862 // Get the size of the old entry
3863 const PageID p = reinterpret_cast<uintptr_t>(old_ptr) >> kPageShift;
3864 size_t cl = pageheap->GetSizeClassIfCached(p);
3865 Span *span = NULL;
3866 size_t old_size;
3867 if (cl == 0) {
3868 span = pageheap->GetDescriptor(p);
3869 cl = span->sizeclass;
3870 pageheap->CacheSizeClass(p, cl);
3871 }
3872 if (cl != 0) {
3873 old_size = ByteSizeForClass(cl);
3874 } else {
3875 ASSERT(span != NULL);
3876 old_size = span->length << kPageShift;
3877 }
3878
3879 // Reallocate if the new size is larger than the old size,
3880 // or if the new size is significantly smaller than the old size.
3881 if ((new_size > old_size) || (AllocationSize(new_size) < old_size)) {
3882 // Need to reallocate
3883 void* new_ptr = do_malloc(new_size);
3884 if (new_ptr == NULL) {
3885 return NULL;
3886 }
3887#ifndef WTF_CHANGES
3888 MallocHook::InvokeNewHook(new_ptr, new_size);
3889#endif
3890 memcpy(new_ptr, old_ptr, ((old_size < new_size) ? old_size : new_size));
3891#ifndef WTF_CHANGES
3892 MallocHook::InvokeDeleteHook(old_ptr);
3893#endif
3894 // We could use a variant of do_free() that leverages the fact
3895 // that we already know the sizeclass of old_ptr. The benefit
3896 // would be small, so don't bother.
3897 do_free(old_ptr);
3898#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3899 new_ptr = static_cast<AllocAlignmentInteger*>(new_ptr) + 1;
3900#endif
3901 return new_ptr;
3902 } else {
3903#if ENABLE(FAST_MALLOC_MATCH_VALIDATION)
3904 old_ptr = static_cast<AllocAlignmentInteger*>(old_ptr) + 1; // Set old_ptr back to the user pointer.
3905#endif
3906 return old_ptr;
3907 }
3908}
3909
3910#ifdef WTF_CHANGES
3911#undef do_malloc
3912#else
3913
3914static SpinLock set_new_handler_lock = SPINLOCK_INITIALIZER;
3915
3916static inline void* cpp_alloc(size_t size, bool nothrow) {
3917 for (;;) {
3918 void* p = do_malloc(size);
3919#ifdef PREANSINEW
3920 return p;
3921#else
3922 if (p == NULL) { // allocation failed
3923 // Get the current new handler. NB: this function is not
3924 // thread-safe. We make a feeble stab at making it so here, but
3925 // this lock only protects against tcmalloc interfering with
3926 // itself, not with other libraries calling set_new_handler.
3927 std::new_handler nh;
3928 {
3929 SpinLockHolder h(&set_new_handler_lock);
3930 nh = std::set_new_handler(0);
3931 (void) std::set_new_handler(nh);
3932 }
3933 // If no new_handler is established, the allocation failed.
3934 if (!nh) {
3935 if (nothrow) return 0;
3936 throw std::bad_alloc();
3937 }
3938 // Otherwise, try the new_handler. If it returns, retry the
3939 // allocation. If it throws std::bad_alloc, fail the allocation.
3940 // if it throws something else, don't interfere.
3941 try {
3942 (*nh)();
3943 } catch (const std::bad_alloc&) {
3944 if (!nothrow) throw;
3945 return p;
3946 }
3947 } else { // allocation success
3948 return p;
3949 }
3950#endif
3951 }
3952}
3953
3954#if ENABLE(GLOBAL_FASTMALLOC_NEW)
3955
3956void* operator new(size_t size) {
3957 void* p = cpp_alloc(size, false);
3958 // We keep this next instruction out of cpp_alloc for a reason: when
3959 // it's in, and new just calls cpp_alloc, the optimizer may fold the
3960 // new call into cpp_alloc, which messes up our whole section-based
3961 // stacktracing (see ATTRIBUTE_SECTION, above). This ensures cpp_alloc
3962 // isn't the last thing this fn calls, and prevents the folding.
3963 MallocHook::InvokeNewHook(p, size);
3964 return p;
3965}
3966
3967void* operator new(size_t size, const std::nothrow_t&) __THROW {
3968 void* p = cpp_alloc(size, true);
3969 MallocHook::InvokeNewHook(p, size);
3970 return p;
3971}
3972
3973void operator delete(void* p) __THROW {
3974 MallocHook::InvokeDeleteHook(p);
3975 do_free(p);
3976}
3977
3978void operator delete(void* p, const std::nothrow_t&) __THROW {
3979 MallocHook::InvokeDeleteHook(p);
3980 do_free(p);
3981}
3982
3983void* operator new[](size_t size) {
3984 void* p = cpp_alloc(size, false);
3985 // We keep this next instruction out of cpp_alloc for a reason: when
3986 // it's in, and new just calls cpp_alloc, the optimizer may fold the
3987 // new call into cpp_alloc, which messes up our whole section-based
3988 // stacktracing (see ATTRIBUTE_SECTION, above). This ensures cpp_alloc
3989 // isn't the last thing this fn calls, and prevents the folding.
3990 MallocHook::InvokeNewHook(p, size);
3991 return p;
3992}
3993
3994void* operator new[](size_t size, const std::nothrow_t&) __THROW {
3995 void* p = cpp_alloc(size, true);
3996 MallocHook::InvokeNewHook(p, size);
3997 return p;
3998}
3999
4000void operator delete[](void* p) __THROW {
4001 MallocHook::InvokeDeleteHook(p);
4002 do_free(p);
4003}
4004
4005void operator delete[](void* p, const std::nothrow_t&) __THROW {
4006 MallocHook::InvokeDeleteHook(p);
4007 do_free(p);
4008}
4009
4010#endif
4011
4012extern "C" void* memalign(size_t align, size_t size) __THROW {
4013 void* result = do_memalign(align, size);
4014 MallocHook::InvokeNewHook(result, size);
4015 return result;
4016}
4017
4018extern "C" int posix_memalign(void** result_ptr, size_t align, size_t size)
4019 __THROW {
4020 if (((align % sizeof(void*)) != 0) ||
4021 ((align & (align - 1)) != 0) ||
4022 (align == 0)) {
4023 return EINVAL;
4024 }
4025
4026 void* result = do_memalign(align, size);
4027 MallocHook::InvokeNewHook(result, size);
4028 if (result == NULL) {
4029 return ENOMEM;
4030 } else {
4031 *result_ptr = result;
4032 return 0;
4033 }
4034}
4035
4036static size_t pagesize = 0;
4037
4038extern "C" void* valloc(size_t size) __THROW {
4039 // Allocate page-aligned object of length >= size bytes
4040 if (pagesize == 0) pagesize = getpagesize();
4041 void* result = do_memalign(pagesize, size);
4042 MallocHook::InvokeNewHook(result, size);
4043 return result;
4044}
4045
4046extern "C" void* pvalloc(size_t size) __THROW {
4047 // Round up size to a multiple of pagesize
4048 if (pagesize == 0) pagesize = getpagesize();
4049 size = (size + pagesize - 1) & ~(pagesize - 1);
4050 void* result = do_memalign(pagesize, size);
4051 MallocHook::InvokeNewHook(result, size);
4052 return result;
4053}
4054
4055extern "C" void malloc_stats(void) {
4056 do_malloc_stats();
4057}
4058
4059extern "C" int mallopt(int cmd, int value) {
4060 return do_mallopt(cmd, value);
4061}
4062
4063#ifdef HAVE_STRUCT_MALLINFO
4064extern "C" struct mallinfo mallinfo(void) {
4065 return do_mallinfo();
4066}
4067#endif
4068
4069//-------------------------------------------------------------------
4070// Some library routines on RedHat 9 allocate memory using malloc()
4071// and free it using __libc_free() (or vice-versa). Since we provide
4072// our own implementations of malloc/free, we need to make sure that
4073// the __libc_XXX variants (defined as part of glibc) also point to
4074// the same implementations.
4075//-------------------------------------------------------------------
4076
4077#if defined(__GLIBC__)
4078extern "C" {
4079#if COMPILER(GCC) && !defined(__MACH__) && defined(HAVE___ATTRIBUTE__)
4080 // Potentially faster variants that use the gcc alias extension.
4081 // Mach-O (Darwin) does not support weak aliases, hence the __MACH__ check.
4082# define ALIAS(x) __attribute__ ((weak, alias (x)))
4083 void* __libc_malloc(size_t size) ALIAS("malloc");
4084 void __libc_free(void* ptr) ALIAS("free");
4085 void* __libc_realloc(void* ptr, size_t size) ALIAS("realloc");
4086 void* __libc_calloc(size_t n, size_t size) ALIAS("calloc");
4087 void __libc_cfree(void* ptr) ALIAS("cfree");
4088 void* __libc_memalign(size_t align, size_t s) ALIAS("memalign");
4089 void* __libc_valloc(size_t size) ALIAS("valloc");
4090 void* __libc_pvalloc(size_t size) ALIAS("pvalloc");
4091 int __posix_memalign(void** r, size_t a, size_t s) ALIAS("posix_memalign");
4092# undef ALIAS
4093# else /* not __GNUC__ */
4094 // Portable wrappers
4095 void* __libc_malloc(size_t size) { return malloc(size); }
4096 void __libc_free(void* ptr) { free(ptr); }
4097 void* __libc_realloc(void* ptr, size_t size) { return realloc(ptr, size); }
4098 void* __libc_calloc(size_t n, size_t size) { return calloc(n, size); }
4099 void __libc_cfree(void* ptr) { cfree(ptr); }
4100 void* __libc_memalign(size_t align, size_t s) { return memalign(align, s); }
4101 void* __libc_valloc(size_t size) { return valloc(size); }
4102 void* __libc_pvalloc(size_t size) { return pvalloc(size); }
4103 int __posix_memalign(void** r, size_t a, size_t s) {
4104 return posix_memalign(r, a, s);
4105 }
4106# endif /* __GNUC__ */
4107}
4108#endif /* __GLIBC__ */
4109
4110// Override __libc_memalign in libc on linux boxes specially.
4111// They have a bug in libc that causes them to (very rarely) allocate
4112// with __libc_memalign() yet deallocate with free() and the
4113// definitions above don't catch it.
4114// This function is an exception to the rule of calling MallocHook method
4115// from the stack frame of the allocation function;
4116// heap-checker handles this special case explicitly.
4117static void *MemalignOverride(size_t align, size_t size, const void *caller)
4118 __THROW {
4119 void* result = do_memalign(align, size);
4120 MallocHook::InvokeNewHook(result, size);
4121 return result;
4122}
4123void *(*__memalign_hook)(size_t, size_t, const void *) = MemalignOverride;
4124
4125#endif
4126
4127#ifdef WTF_CHANGES
4128void releaseFastMallocFreeMemory()
4129{
4130 // Flush free pages in the current thread cache back to the page heap.
4131 // Low watermark mechanism in Scavenge() prevents full return on the first pass.
4132 // The second pass flushes everything.
4133 if (TCMalloc_ThreadCache* threadCache = TCMalloc_ThreadCache::GetCacheIfPresent()) {
4134 threadCache->Scavenge();
4135 threadCache->Scavenge();
4136 }
4137
4138 SpinLockHolder h(&pageheap_lock);
4139 pageheap->ReleaseFreePages();
4140}
4141
4142FastMallocStatistics fastMallocStatistics()
4143{
4144 FastMallocStatistics statistics;
4145
4146 SpinLockHolder lockHolder(&pageheap_lock);
4147 statistics.reservedVMBytes = static_cast<size_t>(pageheap->SystemBytes());
4148 statistics.committedVMBytes = statistics.reservedVMBytes - pageheap->ReturnedBytes();
4149
4150 statistics.freeListBytes = 0;
4151 for (unsigned cl = 0; cl < kNumClasses; ++cl) {
4152 const int length = central_cache[cl].length();
4153 const int tc_length = central_cache[cl].tc_length();
4154
4155 statistics.freeListBytes += ByteSizeForClass(cl) * (length + tc_length);
4156 }
4157 for (TCMalloc_ThreadCache* threadCache = thread_heaps; threadCache ; threadCache = threadCache->next_)
4158 statistics.freeListBytes += threadCache->Size();
4159
4160 return statistics;
4161}
4162
4163size_t fastMallocSize(const void* ptr)
4164{
4165 const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
4166 Span* span = pageheap->GetDescriptorEnsureSafe(p);
4167
4168 if (!span || span->free)
4169 return 0;
4170
4171 for (void* free = span->objects; free != NULL; free = *((void**) free)) {
4172 if (ptr == free)
4173 return 0;
4174 }
4175
4176 if (size_t cl = span->sizeclass)
4177 return ByteSizeForClass(cl);
4178
4179 return span->length << kPageShift;
4180}
4181
4182#if OS(DARWIN)
4183
4184class FreeObjectFinder {
4185 const RemoteMemoryReader& m_reader;
4186 HashSet<void*> m_freeObjects;
4187
4188public:
4189 FreeObjectFinder(const RemoteMemoryReader& reader) : m_reader(reader) { }
4190
4191 void visit(void* ptr) { m_freeObjects.add(ptr); }
4192 bool isFreeObject(void* ptr) const { return m_freeObjects.contains(ptr); }
4193 bool isFreeObject(vm_address_t ptr) const { return isFreeObject(reinterpret_cast<void*>(ptr)); }
4194 size_t freeObjectCount() const { return m_freeObjects.size(); }
4195
4196 void findFreeObjects(TCMalloc_ThreadCache* threadCache)
4197 {
4198 for (; threadCache; threadCache = (threadCache->next_ ? m_reader(threadCache->next_) : 0))
4199 threadCache->enumerateFreeObjects(*this, m_reader);
4200 }
4201
4202 void findFreeObjects(TCMalloc_Central_FreeListPadded* centralFreeList, size_t numSizes, TCMalloc_Central_FreeListPadded* remoteCentralFreeList)
4203 {
4204 for (unsigned i = 0; i < numSizes; i++)
4205 centralFreeList[i].enumerateFreeObjects(*this, m_reader, remoteCentralFreeList + i);
4206 }
4207};
4208
4209class PageMapFreeObjectFinder {
4210 const RemoteMemoryReader& m_reader;
4211 FreeObjectFinder& m_freeObjectFinder;
4212
4213public:
4214 PageMapFreeObjectFinder(const RemoteMemoryReader& reader, FreeObjectFinder& freeObjectFinder)
4215 : m_reader(reader)
4216 , m_freeObjectFinder(freeObjectFinder)
4217 { }
4218
4219 int visit(void* ptr) const
4220 {
4221 if (!ptr)
4222 return 1;
4223
4224 Span* span = m_reader(reinterpret_cast<Span*>(ptr));
4225 if (span->free) {
4226 void* ptr = reinterpret_cast<void*>(span->start << kPageShift);
4227 m_freeObjectFinder.visit(ptr);
4228 } else if (span->sizeclass) {
4229 // Walk the free list of the small-object span, keeping track of each object seen
4230 for (void* nextObject = span->objects; nextObject; nextObject = *m_reader(reinterpret_cast<void**>(nextObject)))
4231 m_freeObjectFinder.visit(nextObject);
4232 }
4233 return span->length;
4234 }
4235};
4236
4237class PageMapMemoryUsageRecorder {
4238 task_t m_task;
4239 void* m_context;
4240 unsigned m_typeMask;
4241 vm_range_recorder_t* m_recorder;
4242 const RemoteMemoryReader& m_reader;
4243 const FreeObjectFinder& m_freeObjectFinder;
4244
4245 HashSet<void*> m_seenPointers;
4246 Vector<Span*> m_coalescedSpans;
4247
4248public:
4249 PageMapMemoryUsageRecorder(task_t task, void* context, unsigned typeMask, vm_range_recorder_t* recorder, const RemoteMemoryReader& reader, const FreeObjectFinder& freeObjectFinder)
4250 : m_task(task)
4251 , m_context(context)
4252 , m_typeMask(typeMask)
4253 , m_recorder(recorder)
4254 , m_reader(reader)
4255 , m_freeObjectFinder(freeObjectFinder)
4256 { }
4257
4258 ~PageMapMemoryUsageRecorder()
4259 {
4260 ASSERT(!m_coalescedSpans.size());
4261 }
4262
4263 void recordPendingRegions()
4264 {
4265 Span* lastSpan = m_coalescedSpans[m_coalescedSpans.size() - 1];
4266 vm_range_t ptrRange = { m_coalescedSpans[0]->start << kPageShift, 0 };
4267 ptrRange.size = (lastSpan->start << kPageShift) - ptrRange.address + (lastSpan->length * kPageSize);
4268
4269 // Mark the memory region the spans represent as a candidate for containing pointers
4270 if (m_typeMask & MALLOC_PTR_REGION_RANGE_TYPE)
4271 (*m_recorder)(m_task, m_context, MALLOC_PTR_REGION_RANGE_TYPE, &ptrRange, 1);
4272
4273 if (!(m_typeMask & MALLOC_PTR_IN_USE_RANGE_TYPE)) {
4274 m_coalescedSpans.clear();
4275 return;
4276 }
4277
4278 Vector<vm_range_t, 1024> allocatedPointers;
4279 for (size_t i = 0; i < m_coalescedSpans.size(); ++i) {
4280 Span *theSpan = m_coalescedSpans[i];
4281 if (theSpan->free)
4282 continue;
4283
4284 vm_address_t spanStartAddress = theSpan->start << kPageShift;
4285 vm_size_t spanSizeInBytes = theSpan->length * kPageSize;
4286
4287 if (!theSpan->sizeclass) {
4288 // If it's an allocated large object span, mark it as in use
4289 if (!m_freeObjectFinder.isFreeObject(spanStartAddress))
4290 allocatedPointers.append((vm_range_t){spanStartAddress, spanSizeInBytes});
4291 } else {
4292 const size_t objectSize = ByteSizeForClass(theSpan->sizeclass);
4293
4294 // Mark each allocated small object within the span as in use
4295 const vm_address_t endOfSpan = spanStartAddress + spanSizeInBytes;
4296 for (vm_address_t object = spanStartAddress; object + objectSize <= endOfSpan; object += objectSize) {
4297 if (!m_freeObjectFinder.isFreeObject(object))
4298 allocatedPointers.append((vm_range_t){object, objectSize});
4299 }
4300 }
4301 }
4302
4303 (*m_recorder)(m_task, m_context, MALLOC_PTR_IN_USE_RANGE_TYPE, allocatedPointers.data(), allocatedPointers.size());
4304
4305 m_coalescedSpans.clear();
4306 }
4307
4308 int visit(void* ptr)
4309 {
4310 if (!ptr)
4311 return 1;
4312
4313 Span* span = m_reader(reinterpret_cast<Span*>(ptr));
4314 if (!span->start)
4315 return 1;
4316
4317 if (m_seenPointers.contains(ptr))
4318 return span->length;
4319 m_seenPointers.add(ptr);
4320
4321 if (!m_coalescedSpans.size()) {
4322 m_coalescedSpans.append(span);
4323 return span->length;
4324 }
4325
4326 Span* previousSpan = m_coalescedSpans[m_coalescedSpans.size() - 1];
4327 vm_address_t previousSpanStartAddress = previousSpan->start << kPageShift;
4328 vm_size_t previousSpanSizeInBytes = previousSpan->length * kPageSize;
4329
4330 // If the new span is adjacent to the previous span, do nothing for now.
4331 vm_address_t spanStartAddress = span->start << kPageShift;
4332 if (spanStartAddress == previousSpanStartAddress + previousSpanSizeInBytes) {
4333 m_coalescedSpans.append(span);
4334 return span->length;
4335 }
4336
4337 // New span is not adjacent to previous span, so record the spans coalesced so far.
4338 recordPendingRegions();
4339 m_coalescedSpans.append(span);
4340
4341 return span->length;
4342 }
4343};
4344
4345class AdminRegionRecorder {
4346 task_t m_task;
4347 void* m_context;
4348 unsigned m_typeMask;
4349 vm_range_recorder_t* m_recorder;
4350 const RemoteMemoryReader& m_reader;
4351
4352 Vector<vm_range_t, 1024> m_pendingRegions;
4353
4354public:
4355 AdminRegionRecorder(task_t task, void* context, unsigned typeMask, vm_range_recorder_t* recorder, const RemoteMemoryReader& reader)
4356 : m_task(task)
4357 , m_context(context)
4358 , m_typeMask(typeMask)
4359 , m_recorder(recorder)
4360 , m_reader(reader)
4361 { }
4362
4363 void recordRegion(vm_address_t ptr, size_t size)
4364 {
4365 if (m_typeMask & MALLOC_ADMIN_REGION_RANGE_TYPE)
4366 m_pendingRegions.append((vm_range_t){ ptr, size });
4367 }
4368
4369 void visit(void *ptr, size_t size)
4370 {
4371 recordRegion(reinterpret_cast<vm_address_t>(ptr), size);
4372 }
4373
4374 void recordPendingRegions()
4375 {
4376 if (m_pendingRegions.size()) {
4377 (*m_recorder)(m_task, m_context, MALLOC_ADMIN_REGION_RANGE_TYPE, m_pendingRegions.data(), m_pendingRegions.size());
4378 m_pendingRegions.clear();
4379 }
4380 }
4381
4382 ~AdminRegionRecorder()
4383 {
4384 ASSERT(!m_pendingRegions.size());
4385 }
4386};
4387
4388kern_return_t FastMallocZone::enumerate(task_t task, void* context, unsigned typeMask, vm_address_t zoneAddress, memory_reader_t reader, vm_range_recorder_t recorder)
4389{
4390 RemoteMemoryReader memoryReader(task, reader);
4391
4392 InitSizeClasses();
4393
4394 FastMallocZone* mzone = memoryReader(reinterpret_cast<FastMallocZone*>(zoneAddress));
4395 TCMalloc_PageHeap* pageHeap = memoryReader(mzone->m_pageHeap);
4396 TCMalloc_ThreadCache** threadHeapsPointer = memoryReader(mzone->m_threadHeaps);
4397 TCMalloc_ThreadCache* threadHeaps = memoryReader(*threadHeapsPointer);
4398
4399 TCMalloc_Central_FreeListPadded* centralCaches = memoryReader(mzone->m_centralCaches, sizeof(TCMalloc_Central_FreeListPadded) * kNumClasses);
4400
4401 FreeObjectFinder finder(memoryReader);
4402 finder.findFreeObjects(threadHeaps);
4403 finder.findFreeObjects(centralCaches, kNumClasses, mzone->m_centralCaches);
4404
4405 TCMalloc_PageHeap::PageMap* pageMap = &pageHeap->pagemap_;
4406 PageMapFreeObjectFinder pageMapFinder(memoryReader, finder);
4407 pageMap->visitValues(pageMapFinder, memoryReader);
4408
4409 PageMapMemoryUsageRecorder usageRecorder(task, context, typeMask, recorder, memoryReader, finder);
4410 pageMap->visitValues(usageRecorder, memoryReader);
4411 usageRecorder.recordPendingRegions();
4412
4413 AdminRegionRecorder adminRegionRecorder(task, context, typeMask, recorder, memoryReader);
4414 pageMap->visitAllocations(adminRegionRecorder, memoryReader);
4415
4416 PageHeapAllocator<Span>* spanAllocator = memoryReader(mzone->m_spanAllocator);
4417 PageHeapAllocator<TCMalloc_ThreadCache>* pageHeapAllocator = memoryReader(mzone->m_pageHeapAllocator);
4418
4419 spanAllocator->recordAdministrativeRegions(adminRegionRecorder, memoryReader);
4420 pageHeapAllocator->recordAdministrativeRegions(adminRegionRecorder, memoryReader);
4421
4422 adminRegionRecorder.recordPendingRegions();
4423
4424 return 0;
4425}
4426
4427size_t FastMallocZone::size(malloc_zone_t*, const void*)
4428{
4429 return 0;
4430}
4431
4432void* FastMallocZone::zoneMalloc(malloc_zone_t*, size_t)
4433{
4434 return 0;
4435}
4436
4437void* FastMallocZone::zoneCalloc(malloc_zone_t*, size_t, size_t)
4438{
4439 return 0;
4440}
4441
4442void FastMallocZone::zoneFree(malloc_zone_t*, void* ptr)
4443{
4444 // Due to <rdar://problem/5671357> zoneFree may be called by the system free even if the pointer
4445 // is not in this zone. When this happens, the pointer being freed was not allocated by any
4446 // zone so we need to print a useful error for the application developer.
4447 malloc_printf("*** error for object %p: pointer being freed was not allocated\n", ptr);
4448}
4449
4450void* FastMallocZone::zoneRealloc(malloc_zone_t*, void*, size_t)
4451{
4452 return 0;
4453}
4454
4455
4456#undef malloc
4457#undef free
4458#undef realloc
4459#undef calloc
4460
4461extern "C" {
4462malloc_introspection_t jscore_fastmalloc_introspection = { &FastMallocZone::enumerate, &FastMallocZone::goodSize, &FastMallocZone::check, &FastMallocZone::print,
4463 &FastMallocZone::log, &FastMallocZone::forceLock, &FastMallocZone::forceUnlock, &FastMallocZone::statistics
4464
4465#if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
4466 , 0 // zone_locked will not be called on the zone unless it advertises itself as version five or higher.
4467#endif
4468#if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD)
4469 , 0, 0, 0, 0 // These members will not be used unless the zone advertises itself as version seven or higher.
4470#endif
4471
4472 };
4473}
4474
4475FastMallocZone::FastMallocZone(TCMalloc_PageHeap* pageHeap, TCMalloc_ThreadCache** threadHeaps, TCMalloc_Central_FreeListPadded* centralCaches, PageHeapAllocator<Span>* spanAllocator, PageHeapAllocator<TCMalloc_ThreadCache>* pageHeapAllocator)
4476 : m_pageHeap(pageHeap)
4477 , m_threadHeaps(threadHeaps)
4478 , m_centralCaches(centralCaches)
4479 , m_spanAllocator(spanAllocator)
4480 , m_pageHeapAllocator(pageHeapAllocator)
4481{
4482 memset(&m_zone, 0, sizeof(m_zone));
4483 m_zone.version = 4;
4484 m_zone.zone_name = "JavaScriptCore FastMalloc";
4485 m_zone.size = &FastMallocZone::size;
4486 m_zone.malloc = &FastMallocZone::zoneMalloc;
4487 m_zone.calloc = &FastMallocZone::zoneCalloc;
4488 m_zone.realloc = &FastMallocZone::zoneRealloc;
4489 m_zone.free = &FastMallocZone::zoneFree;
4490 m_zone.valloc = &FastMallocZone::zoneValloc;
4491 m_zone.destroy = &FastMallocZone::zoneDestroy;
4492 m_zone.introspect = &jscore_fastmalloc_introspection;
4493 malloc_zone_register(&m_zone);
4494}
4495
4496
4497void FastMallocZone::init()
4498{
4499 static FastMallocZone zone(pageheap, &thread_heaps, static_cast<TCMalloc_Central_FreeListPadded*>(central_cache), &span_allocator, &threadheap_allocator);
4500}
4501
4502#endif // OS(DARWIN)
4503
4504} // namespace WTF
4505#endif // WTF_CHANGES
4506
4507#endif // FORCE_SYSTEM_MALLOC
Note: See TracBrowser for help on using the repository browser.