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