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