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