PageRenderTime 73ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 1ms

/JavaScriptCore/wtf/FastMalloc.cpp

https://github.com/kvlasov/qtwebkit
C++ | 3701 lines | 2555 code | 482 blank | 664 comment | 452 complexity | 7b96ce74bc292ff118fa06de30a59ff5 MD5 | raw file
Possible License(s): BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-2.1, LGPL-2.0
  1. // Copyright (c) 2005, 2007, Google Inc.
  2. // All rights reserved.
  3. // Copyright (C) 2005, 2006, 2007, 2008 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. // Author: Sanjay Ghemawat <opensource@google.com>
  32. //
  33. // A malloc that uses a per-thread cache to satisfy small malloc requests.
  34. // (The time for malloc/free of a small object drops from 300 ns to 50 ns.)
  35. //
  36. // See doc/tcmalloc.html for a high-level
  37. // description of how this malloc works.
  38. //
  39. // SYNCHRONIZATION
  40. // 1. The thread-specific lists are accessed without acquiring any locks.
  41. // This is safe because each such list is only accessed by one thread.
  42. // 2. We have a lock per central free-list, and hold it while manipulating
  43. // the central free list for a particular size.
  44. // 3. The central page allocator is protected by "pageheap_lock".
  45. // 4. The pagemap (which maps from page-number to descriptor),
  46. // can be read without holding any locks, and written while holding
  47. // the "pageheap_lock".
  48. // 5. To improve performance, a subset of the information one can get
  49. // from the pagemap is cached in a data structure, pagemap_cache_,
  50. // that atomically reads and writes its entries. This cache can be
  51. // read and written without locking.
  52. //
  53. // This multi-threaded access to the pagemap is safe for fairly
  54. // subtle reasons. We basically assume that when an object X is
  55. // allocated by thread A and deallocated by thread B, there must
  56. // have been appropriate synchronization in the handoff of object
  57. // X from thread A to thread B. The same logic applies to pagemap_cache_.
  58. //
  59. // THE PAGEID-TO-SIZECLASS CACHE
  60. // Hot PageID-to-sizeclass mappings are held by pagemap_cache_. If this cache
  61. // returns 0 for a particular PageID then that means "no information," not that
  62. // the sizeclass is 0. The cache may have stale information for pages that do
  63. // not hold the beginning of any free()'able object. Staleness is eliminated
  64. // in Populate() for pages with sizeclass > 0 objects, and in do_malloc() and
  65. // do_memalign() for all other relevant pages.
  66. //
  67. // TODO: Bias reclamation to larger addresses
  68. // TODO: implement mallinfo/mallopt
  69. // TODO: Better testing
  70. //
  71. // 9/28/2003 (new page-level allocator replaces ptmalloc2):
  72. // * malloc/free of small objects goes from ~300 ns to ~50 ns.
  73. // * allocation of a reasonably complicated struct
  74. // goes from about 1100 ns to about 300 ns.
  75. #include "config.h"
  76. #include "FastMalloc.h"
  77. #include "Assertions.h"
  78. #if ENABLE(JSC_MULTIPLE_THREADS)
  79. #include <pthread.h>
  80. #endif
  81. #ifndef NO_TCMALLOC_SAMPLES
  82. #ifdef WTF_CHANGES
  83. #define NO_TCMALLOC_SAMPLES
  84. #endif
  85. #endif
  86. #if !defined(USE_SYSTEM_MALLOC) && defined(NDEBUG)
  87. #define FORCE_SYSTEM_MALLOC 0
  88. #else
  89. #define FORCE_SYSTEM_MALLOC 1
  90. #endif
  91. #define TCMALLOC_TRACK_DECOMMITED_SPANS (HAVE(VIRTUALALLOC))
  92. #ifndef NDEBUG
  93. namespace WTF {
  94. #if ENABLE(JSC_MULTIPLE_THREADS)
  95. static pthread_key_t isForbiddenKey;
  96. static pthread_once_t isForbiddenKeyOnce = PTHREAD_ONCE_INIT;
  97. static void initializeIsForbiddenKey()
  98. {
  99. pthread_key_create(&isForbiddenKey, 0);
  100. }
  101. static bool isForbidden()
  102. {
  103. pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
  104. return !!pthread_getspecific(isForbiddenKey);
  105. }
  106. void fastMallocForbid()
  107. {
  108. pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
  109. pthread_setspecific(isForbiddenKey, &isForbiddenKey);
  110. }
  111. void fastMallocAllow()
  112. {
  113. pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
  114. pthread_setspecific(isForbiddenKey, 0);
  115. }
  116. #else
  117. static bool staticIsForbidden;
  118. static bool isForbidden()
  119. {
  120. return staticIsForbidden;
  121. }
  122. void fastMallocForbid()
  123. {
  124. staticIsForbidden = true;
  125. }
  126. void fastMallocAllow()
  127. {
  128. staticIsForbidden = false;
  129. }
  130. #endif // ENABLE(JSC_MULTIPLE_THREADS)
  131. } // namespace WTF
  132. #endif // NDEBUG
  133. #include <string.h>
  134. namespace WTF {
  135. void *fastZeroedMalloc(size_t n)
  136. {
  137. void *result = fastMalloc(n);
  138. if (!result)
  139. return 0;
  140. memset(result, 0, n);
  141. #ifndef WTF_CHANGES
  142. MallocHook::InvokeNewHook(result, n);
  143. #endif
  144. return result;
  145. }
  146. }
  147. #if FORCE_SYSTEM_MALLOC
  148. #include <stdlib.h>
  149. #if !PLATFORM(WIN_OS)
  150. #include <pthread.h>
  151. #endif
  152. namespace WTF {
  153. void *fastMalloc(size_t n)
  154. {
  155. ASSERT(!isForbidden());
  156. return malloc(n);
  157. }
  158. void *fastCalloc(size_t n_elements, size_t element_size)
  159. {
  160. ASSERT(!isForbidden());
  161. return calloc(n_elements, element_size);
  162. }
  163. void fastFree(void* p)
  164. {
  165. ASSERT(!isForbidden());
  166. free(p);
  167. }
  168. void *fastRealloc(void* p, size_t n)
  169. {
  170. ASSERT(!isForbidden());
  171. return realloc(p, n);
  172. }
  173. void releaseFastMallocFreeMemory() { }
  174. } // namespace WTF
  175. #if PLATFORM(DARWIN)
  176. // This symbol is present in the JavaScriptCore exports file even when FastMalloc is disabled.
  177. // It will never be used in this case, so it's type and value are less interesting than its presence.
  178. extern "C" const int jscore_fastmalloc_introspection = 0;
  179. #endif
  180. #else // FORCE_SYSTEM_MALLOC
  181. #if HAVE(STDINT_H)
  182. #include <stdint.h>
  183. #elif HAVE(INTTYPES_H)
  184. #include <inttypes.h>
  185. #else
  186. #include <sys/types.h>
  187. #endif
  188. #include "AlwaysInline.h"
  189. #include "Assertions.h"
  190. #include "TCPackedCache.h"
  191. #include "TCPageMap.h"
  192. #include "TCSpinLock.h"
  193. #include "TCSystemAlloc.h"
  194. #include <algorithm>
  195. #include <errno.h>
  196. #include <new>
  197. #include <pthread.h>
  198. #include <stdarg.h>
  199. #include <stddef.h>
  200. #include <stdio.h>
  201. #if COMPILER(MSVC)
  202. #ifndef WIN32_LEAN_AND_MEAN
  203. #define WIN32_LEAN_AND_MEAN
  204. #endif
  205. #include <windows.h>
  206. #endif
  207. #if WTF_CHANGES
  208. #if PLATFORM(DARWIN)
  209. #include "MallocZoneSupport.h"
  210. #include <wtf/HashSet.h>
  211. #endif
  212. #ifndef PRIuS
  213. #define PRIuS "zu"
  214. #endif
  215. // Calling pthread_getspecific through a global function pointer is faster than a normal
  216. // call to the function on Mac OS X, and it's used in performance-critical code. So we
  217. // use a function pointer. But that's not necessarily faster on other platforms, and we had
  218. // problems with this technique on Windows, so we'll do this only on Mac OS X.
  219. #if PLATFORM(DARWIN)
  220. static void* (*pthread_getspecific_function_pointer)(pthread_key_t) = pthread_getspecific;
  221. #define pthread_getspecific(key) pthread_getspecific_function_pointer(key)
  222. #endif
  223. #define DEFINE_VARIABLE(type, name, value, meaning) \
  224. namespace FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead { \
  225. type FLAGS_##name(value); \
  226. char FLAGS_no##name; \
  227. } \
  228. using FLAG__namespace_do_not_use_directly_use_DECLARE_##type##_instead::FLAGS_##name
  229. #define DEFINE_int64(name, value, meaning) \
  230. DEFINE_VARIABLE(int64_t, name, value, meaning)
  231. #define DEFINE_double(name, value, meaning) \
  232. DEFINE_VARIABLE(double, name, value, meaning)
  233. namespace WTF {
  234. #define malloc fastMalloc
  235. #define calloc fastCalloc
  236. #define free fastFree
  237. #define realloc fastRealloc
  238. #define MESSAGE LOG_ERROR
  239. #define CHECK_CONDITION ASSERT
  240. #if PLATFORM(DARWIN)
  241. class TCMalloc_PageHeap;
  242. class TCMalloc_ThreadCache;
  243. class TCMalloc_Central_FreeListPadded;
  244. class FastMallocZone {
  245. public:
  246. static void init();
  247. static kern_return_t enumerate(task_t, void*, unsigned typeMmask, vm_address_t zoneAddress, memory_reader_t, vm_range_recorder_t);
  248. static size_t goodSize(malloc_zone_t*, size_t size) { return size; }
  249. static boolean_t check(malloc_zone_t*) { return true; }
  250. static void print(malloc_zone_t*, boolean_t) { }
  251. static void log(malloc_zone_t*, void*) { }
  252. static void forceLock(malloc_zone_t*) { }
  253. static void forceUnlock(malloc_zone_t*) { }
  254. static void statistics(malloc_zone_t*, malloc_statistics_t* stats) { memset(stats, 0, sizeof(malloc_statistics_t)); }
  255. private:
  256. FastMallocZone(TCMalloc_PageHeap*, TCMalloc_ThreadCache**, TCMalloc_Central_FreeListPadded*);
  257. static size_t size(malloc_zone_t*, const void*);
  258. static void* zoneMalloc(malloc_zone_t*, size_t);
  259. static void* zoneCalloc(malloc_zone_t*, size_t numItems, size_t size);
  260. static void zoneFree(malloc_zone_t*, void*);
  261. static void* zoneRealloc(malloc_zone_t*, void*, size_t);
  262. static void* zoneValloc(malloc_zone_t*, size_t) { LOG_ERROR("valloc is not supported"); return 0; }
  263. static void zoneDestroy(malloc_zone_t*) { }
  264. malloc_zone_t m_zone;
  265. TCMalloc_PageHeap* m_pageHeap;
  266. TCMalloc_ThreadCache** m_threadHeaps;
  267. TCMalloc_Central_FreeListPadded* m_centralCaches;
  268. };
  269. #endif
  270. #endif
  271. #ifndef WTF_CHANGES
  272. // This #ifdef should almost never be set. Set NO_TCMALLOC_SAMPLES if
  273. // you're porting to a system where you really can't get a stacktrace.
  274. #ifdef NO_TCMALLOC_SAMPLES
  275. // We use #define so code compiles even if you #include stacktrace.h somehow.
  276. # define GetStackTrace(stack, depth, skip) (0)
  277. #else
  278. # include <google/stacktrace.h>
  279. #endif
  280. #endif
  281. // Even if we have support for thread-local storage in the compiler
  282. // and linker, the OS may not support it. We need to check that at
  283. // runtime. Right now, we have to keep a manual set of "bad" OSes.
  284. #if defined(HAVE_TLS)
  285. static bool kernel_supports_tls = false; // be conservative
  286. static inline bool KernelSupportsTLS() {
  287. return kernel_supports_tls;
  288. }
  289. # if !HAVE_DECL_UNAME // if too old for uname, probably too old for TLS
  290. static void CheckIfKernelSupportsTLS() {
  291. kernel_supports_tls = false;
  292. }
  293. # else
  294. # include <sys/utsname.h> // DECL_UNAME checked for <sys/utsname.h> too
  295. static void CheckIfKernelSupportsTLS() {
  296. struct utsname buf;
  297. if (uname(&buf) != 0) { // should be impossible
  298. MESSAGE("uname failed assuming no TLS support (errno=%d)\n", errno);
  299. kernel_supports_tls = false;
  300. } else if (strcasecmp(buf.sysname, "linux") == 0) {
  301. // The linux case: the first kernel to support TLS was 2.6.0
  302. if (buf.release[0] < '2' && buf.release[1] == '.') // 0.x or 1.x
  303. kernel_supports_tls = false;
  304. else if (buf.release[0] == '2' && buf.release[1] == '.' &&
  305. buf.release[2] >= '0' && buf.release[2] < '6' &&
  306. buf.release[3] == '.') // 2.0 - 2.5
  307. kernel_supports_tls = false;
  308. else
  309. kernel_supports_tls = true;
  310. } else { // some other kernel, we'll be optimisitic
  311. kernel_supports_tls = true;
  312. }
  313. // TODO(csilvers): VLOG(1) the tls status once we support RAW_VLOG
  314. }
  315. # endif // HAVE_DECL_UNAME
  316. #endif // HAVE_TLS
  317. // __THROW is defined in glibc systems. It means, counter-intuitively,
  318. // "This function will never throw an exception." It's an optional
  319. // optimization tool, but we may need to use it to match glibc prototypes.
  320. #ifndef __THROW // I guess we're not on a glibc system
  321. # define __THROW // __THROW is just an optimization, so ok to make it ""
  322. #endif
  323. //-------------------------------------------------------------------
  324. // Configuration
  325. //-------------------------------------------------------------------
  326. // Not all possible combinations of the following parameters make
  327. // sense. In particular, if kMaxSize increases, you may have to
  328. // increase kNumClasses as well.
  329. static const size_t kPageShift = 12;
  330. static const size_t kPageSize = 1 << kPageShift;
  331. static const size_t kMaxSize = 8u * kPageSize;
  332. static const size_t kAlignShift = 3;
  333. static const size_t kAlignment = 1 << kAlignShift;
  334. static const size_t kNumClasses = 68;
  335. // Allocates a big block of memory for the pagemap once we reach more than
  336. // 128MB
  337. static const size_t kPageMapBigAllocationThreshold = 128 << 20;
  338. // Minimum number of pages to fetch from system at a time. Must be
  339. // significantly bigger than kBlockSize to amortize system-call
  340. // overhead, and also to reduce external fragementation. Also, we
  341. // should keep this value big because various incarnations of Linux
  342. // have small limits on the number of mmap() regions per
  343. // address-space.
  344. static const size_t kMinSystemAlloc = 1 << (20 - kPageShift);
  345. // Number of objects to move between a per-thread list and a central
  346. // list in one shot. We want this to be not too small so we can
  347. // amortize the lock overhead for accessing the central list. Making
  348. // it too big may temporarily cause unnecessary memory wastage in the
  349. // per-thread free list until the scavenger cleans up the list.
  350. static int num_objects_to_move[kNumClasses];
  351. // Maximum length we allow a per-thread free-list to have before we
  352. // move objects from it into the corresponding central free-list. We
  353. // want this big to avoid locking the central free-list too often. It
  354. // should not hurt to make this list somewhat big because the
  355. // scavenging code will shrink it down when its contents are not in use.
  356. static const int kMaxFreeListLength = 256;
  357. // Lower and upper bounds on the per-thread cache sizes
  358. static const size_t kMinThreadCacheSize = kMaxSize * 2;
  359. static const size_t kMaxThreadCacheSize = 2 << 20;
  360. // Default bound on the total amount of thread caches
  361. static const size_t kDefaultOverallThreadCacheSize = 16 << 20;
  362. // For all span-lengths < kMaxPages we keep an exact-size list.
  363. // REQUIRED: kMaxPages >= kMinSystemAlloc;
  364. static const size_t kMaxPages = kMinSystemAlloc;
  365. /* The smallest prime > 2^n */
  366. static int primes_list[] = {
  367. // Small values might cause high rates of sampling
  368. // and hence commented out.
  369. // 2, 5, 11, 17, 37, 67, 131, 257,
  370. // 521, 1031, 2053, 4099, 8209, 16411,
  371. 32771, 65537, 131101, 262147, 524309, 1048583,
  372. 2097169, 4194319, 8388617, 16777259, 33554467 };
  373. // Twice the approximate gap between sampling actions.
  374. // I.e., we take one sample approximately once every
  375. // tcmalloc_sample_parameter/2
  376. // bytes of allocation, i.e., ~ once every 128KB.
  377. // Must be a prime number.
  378. #ifdef NO_TCMALLOC_SAMPLES
  379. DEFINE_int64(tcmalloc_sample_parameter, 0,
  380. "Unused: code is compiled with NO_TCMALLOC_SAMPLES");
  381. static size_t sample_period = 0;
  382. #else
  383. DEFINE_int64(tcmalloc_sample_parameter, 262147,
  384. "Twice the approximate gap between sampling actions."
  385. " Must be a prime number. Otherwise will be rounded up to a "
  386. " larger prime number");
  387. static size_t sample_period = 262147;
  388. #endif
  389. // Protects sample_period above
  390. static SpinLock sample_period_lock = SPINLOCK_INITIALIZER;
  391. // Parameters for controlling how fast memory is returned to the OS.
  392. DEFINE_double(tcmalloc_release_rate, 1,
  393. "Rate at which we release unused memory to the system. "
  394. "Zero means we never release memory back to the system. "
  395. "Increase this flag to return memory faster; decrease it "
  396. "to return memory slower. Reasonable rates are in the "
  397. "range [0,10]");
  398. //-------------------------------------------------------------------
  399. // Mapping from size to size_class and vice versa
  400. //-------------------------------------------------------------------
  401. // Sizes <= 1024 have an alignment >= 8. So for such sizes we have an
  402. // array indexed by ceil(size/8). Sizes > 1024 have an alignment >= 128.
  403. // So for these larger sizes we have an array indexed by ceil(size/128).
  404. //
  405. // We flatten both logical arrays into one physical array and use
  406. // arithmetic to compute an appropriate index. The constants used by
  407. // ClassIndex() were selected to make the flattening work.
  408. //
  409. // Examples:
  410. // Size Expression Index
  411. // -------------------------------------------------------
  412. // 0 (0 + 7) / 8 0
  413. // 1 (1 + 7) / 8 1
  414. // ...
  415. // 1024 (1024 + 7) / 8 128
  416. // 1025 (1025 + 127 + (120<<7)) / 128 129
  417. // ...
  418. // 32768 (32768 + 127 + (120<<7)) / 128 376
  419. static const size_t kMaxSmallSize = 1024;
  420. static const int shift_amount[2] = { 3, 7 }; // For divides by 8 or 128
  421. static const int add_amount[2] = { 7, 127 + (120 << 7) };
  422. static unsigned char class_array[377];
  423. // Compute index of the class_array[] entry for a given size
  424. static inline int ClassIndex(size_t s) {
  425. const int i = (s > kMaxSmallSize);
  426. return static_cast<int>((s + add_amount[i]) >> shift_amount[i]);
  427. }
  428. // Mapping from size class to max size storable in that class
  429. static size_t class_to_size[kNumClasses];
  430. // Mapping from size class to number of pages to allocate at a time
  431. static size_t class_to_pages[kNumClasses];
  432. // TransferCache is used to cache transfers of num_objects_to_move[size_class]
  433. // back and forth between thread caches and the central cache for a given size
  434. // class.
  435. struct TCEntry {
  436. void *head; // Head of chain of objects.
  437. void *tail; // Tail of chain of objects.
  438. };
  439. // A central cache freelist can have anywhere from 0 to kNumTransferEntries
  440. // slots to put link list chains into. To keep memory usage bounded the total
  441. // number of TCEntries across size classes is fixed. Currently each size
  442. // class is initially given one TCEntry which also means that the maximum any
  443. // one class can have is kNumClasses.
  444. static const int kNumTransferEntries = kNumClasses;
  445. // Note: the following only works for "n"s that fit in 32-bits, but
  446. // that is fine since we only use it for small sizes.
  447. static inline int LgFloor(size_t n) {
  448. int log = 0;
  449. for (int i = 4; i >= 0; --i) {
  450. int shift = (1 << i);
  451. size_t x = n >> shift;
  452. if (x != 0) {
  453. n = x;
  454. log += shift;
  455. }
  456. }
  457. ASSERT(n == 1);
  458. return log;
  459. }
  460. // Some very basic linked list functions for dealing with using void * as
  461. // storage.
  462. static inline void *SLL_Next(void *t) {
  463. return *(reinterpret_cast<void**>(t));
  464. }
  465. static inline void SLL_SetNext(void *t, void *n) {
  466. *(reinterpret_cast<void**>(t)) = n;
  467. }
  468. static inline void SLL_Push(void **list, void *element) {
  469. SLL_SetNext(element, *list);
  470. *list = element;
  471. }
  472. static inline void *SLL_Pop(void **list) {
  473. void *result = *list;
  474. *list = SLL_Next(*list);
  475. return result;
  476. }
  477. // Remove N elements from a linked list to which head points. head will be
  478. // modified to point to the new head. start and end will point to the first
  479. // and last nodes of the range. Note that end will point to NULL after this
  480. // function is called.
  481. static inline void SLL_PopRange(void **head, int N, void **start, void **end) {
  482. if (N == 0) {
  483. *start = NULL;
  484. *end = NULL;
  485. return;
  486. }
  487. void *tmp = *head;
  488. for (int i = 1; i < N; ++i) {
  489. tmp = SLL_Next(tmp);
  490. }
  491. *start = *head;
  492. *end = tmp;
  493. *head = SLL_Next(tmp);
  494. // Unlink range from list.
  495. SLL_SetNext(tmp, NULL);
  496. }
  497. static inline void SLL_PushRange(void **head, void *start, void *end) {
  498. if (!start) return;
  499. SLL_SetNext(end, *head);
  500. *head = start;
  501. }
  502. static inline size_t SLL_Size(void *head) {
  503. int count = 0;
  504. while (head) {
  505. count++;
  506. head = SLL_Next(head);
  507. }
  508. return count;
  509. }
  510. // Setup helper functions.
  511. static ALWAYS_INLINE size_t SizeClass(size_t size) {
  512. return class_array[ClassIndex(size)];
  513. }
  514. // Get the byte-size for a specified class
  515. static ALWAYS_INLINE size_t ByteSizeForClass(size_t cl) {
  516. return class_to_size[cl];
  517. }
  518. static int NumMoveSize(size_t size) {
  519. if (size == 0) return 0;
  520. // Use approx 64k transfers between thread and central caches.
  521. int num = static_cast<int>(64.0 * 1024.0 / size);
  522. if (num < 2) num = 2;
  523. // Clamp well below kMaxFreeListLength to avoid ping pong between central
  524. // and thread caches.
  525. if (num > static_cast<int>(0.8 * kMaxFreeListLength))
  526. num = static_cast<int>(0.8 * kMaxFreeListLength);
  527. // Also, avoid bringing in too many objects into small object free
  528. // lists. There are lots of such lists, and if we allow each one to
  529. // fetch too many at a time, we end up having to scavenge too often
  530. // (especially when there are lots of threads and each thread gets a
  531. // small allowance for its thread cache).
  532. //
  533. // TODO: Make thread cache free list sizes dynamic so that we do not
  534. // have to equally divide a fixed resource amongst lots of threads.
  535. if (num > 32) num = 32;
  536. return num;
  537. }
  538. // Initialize the mapping arrays
  539. static void InitSizeClasses() {
  540. // Do some sanity checking on add_amount[]/shift_amount[]/class_array[]
  541. if (ClassIndex(0) < 0) {
  542. MESSAGE("Invalid class index %d for size 0\n", ClassIndex(0));
  543. abort();
  544. }
  545. if (static_cast<size_t>(ClassIndex(kMaxSize)) >= sizeof(class_array)) {
  546. MESSAGE("Invalid class index %d for kMaxSize\n", ClassIndex(kMaxSize));
  547. abort();
  548. }
  549. // Compute the size classes we want to use
  550. size_t sc = 1; // Next size class to assign
  551. unsigned char alignshift = kAlignShift;
  552. int last_lg = -1;
  553. for (size_t size = kAlignment; size <= kMaxSize; size += (1 << alignshift)) {
  554. int lg = LgFloor(size);
  555. if (lg > last_lg) {
  556. // Increase alignment every so often.
  557. //
  558. // Since we double the alignment every time size doubles and
  559. // size >= 128, this means that space wasted due to alignment is
  560. // at most 16/128 i.e., 12.5%. Plus we cap the alignment at 256
  561. // bytes, so the space wasted as a percentage starts falling for
  562. // sizes > 2K.
  563. if ((lg >= 7) && (alignshift < 8)) {
  564. alignshift++;
  565. }
  566. last_lg = lg;
  567. }
  568. // Allocate enough pages so leftover is less than 1/8 of total.
  569. // This bounds wasted space to at most 12.5%.
  570. size_t psize = kPageSize;
  571. while ((psize % size) > (psize >> 3)) {
  572. psize += kPageSize;
  573. }
  574. const size_t my_pages = psize >> kPageShift;
  575. if (sc > 1 && my_pages == class_to_pages[sc-1]) {
  576. // See if we can merge this into the previous class without
  577. // increasing the fragmentation of the previous class.
  578. const size_t my_objects = (my_pages << kPageShift) / size;
  579. const size_t prev_objects = (class_to_pages[sc-1] << kPageShift)
  580. / class_to_size[sc-1];
  581. if (my_objects == prev_objects) {
  582. // Adjust last class to include this size
  583. class_to_size[sc-1] = size;
  584. continue;
  585. }
  586. }
  587. // Add new class
  588. class_to_pages[sc] = my_pages;
  589. class_to_size[sc] = size;
  590. sc++;
  591. }
  592. if (sc != kNumClasses) {
  593. MESSAGE("wrong number of size classes: found %" PRIuS " instead of %d\n",
  594. sc, int(kNumClasses));
  595. abort();
  596. }
  597. // Initialize the mapping arrays
  598. int next_size = 0;
  599. for (unsigned char c = 1; c < kNumClasses; c++) {
  600. const size_t max_size_in_class = class_to_size[c];
  601. for (size_t s = next_size; s <= max_size_in_class; s += kAlignment) {
  602. class_array[ClassIndex(s)] = c;
  603. }
  604. next_size = static_cast<int>(max_size_in_class + kAlignment);
  605. }
  606. // Double-check sizes just to be safe
  607. for (size_t size = 0; size <= kMaxSize; size++) {
  608. const size_t sc = SizeClass(size);
  609. if (sc == 0) {
  610. MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
  611. abort();
  612. }
  613. if (sc > 1 && size <= class_to_size[sc-1]) {
  614. MESSAGE("Allocating unnecessarily large class %" PRIuS " for %" PRIuS
  615. "\n", sc, size);
  616. abort();
  617. }
  618. if (sc >= kNumClasses) {
  619. MESSAGE("Bad size class %" PRIuS " for %" PRIuS "\n", sc, size);
  620. abort();
  621. }
  622. const size_t s = class_to_size[sc];
  623. if (size > s) {
  624. MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
  625. abort();
  626. }
  627. if (s == 0) {
  628. MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %" PRIuS ")\n", s, size, sc);
  629. abort();
  630. }
  631. }
  632. // Initialize the num_objects_to_move array.
  633. for (size_t cl = 1; cl < kNumClasses; ++cl) {
  634. num_objects_to_move[cl] = NumMoveSize(ByteSizeForClass(cl));
  635. }
  636. #ifndef WTF_CHANGES
  637. if (false) {
  638. // Dump class sizes and maximum external wastage per size class
  639. for (size_t cl = 1; cl < kNumClasses; ++cl) {
  640. const int alloc_size = class_to_pages[cl] << kPageShift;
  641. const int alloc_objs = alloc_size / class_to_size[cl];
  642. const int min_used = (class_to_size[cl-1] + 1) * alloc_objs;
  643. const int max_waste = alloc_size - min_used;
  644. MESSAGE("SC %3d [ %8d .. %8d ] from %8d ; %2.0f%% maxwaste\n",
  645. int(cl),
  646. int(class_to_size[cl-1] + 1),
  647. int(class_to_size[cl]),
  648. int(class_to_pages[cl] << kPageShift),
  649. max_waste * 100.0 / alloc_size
  650. );
  651. }
  652. }
  653. #endif
  654. }
  655. // -------------------------------------------------------------------------
  656. // Simple allocator for objects of a specified type. External locking
  657. // is required before accessing one of these objects.
  658. // -------------------------------------------------------------------------
  659. // Metadata allocator -- keeps stats about how many bytes allocated
  660. static uint64_t metadata_system_bytes = 0;
  661. static void* MetaDataAlloc(size_t bytes) {
  662. void* result = TCMalloc_SystemAlloc(bytes, 0);
  663. if (result != NULL) {
  664. metadata_system_bytes += bytes;
  665. }
  666. return result;
  667. }
  668. template <class T>
  669. class PageHeapAllocator {
  670. private:
  671. // How much to allocate from system at a time
  672. static const size_t kAllocIncrement = 32 << 10;
  673. // Aligned size of T
  674. static const size_t kAlignedSize
  675. = (((sizeof(T) + kAlignment - 1) / kAlignment) * kAlignment);
  676. // Free area from which to carve new objects
  677. char* free_area_;
  678. size_t free_avail_;
  679. // Free list of already carved objects
  680. void* free_list_;
  681. // Number of allocated but unfreed objects
  682. int inuse_;
  683. public:
  684. void Init() {
  685. ASSERT(kAlignedSize <= kAllocIncrement);
  686. inuse_ = 0;
  687. free_area_ = NULL;
  688. free_avail_ = 0;
  689. free_list_ = NULL;
  690. }
  691. T* New() {
  692. // Consult free list
  693. void* result;
  694. if (free_list_ != NULL) {
  695. result = free_list_;
  696. free_list_ = *(reinterpret_cast<void**>(result));
  697. } else {
  698. if (free_avail_ < kAlignedSize) {
  699. // Need more room
  700. free_area_ = reinterpret_cast<char*>(MetaDataAlloc(kAllocIncrement));
  701. if (free_area_ == NULL) abort();
  702. free_avail_ = kAllocIncrement;
  703. }
  704. result = free_area_;
  705. free_area_ += kAlignedSize;
  706. free_avail_ -= kAlignedSize;
  707. }
  708. inuse_++;
  709. return reinterpret_cast<T*>(result);
  710. }
  711. void Delete(T* p) {
  712. *(reinterpret_cast<void**>(p)) = free_list_;
  713. free_list_ = p;
  714. inuse_--;
  715. }
  716. int inuse() const { return inuse_; }
  717. };
  718. // -------------------------------------------------------------------------
  719. // Span - a contiguous run of pages
  720. // -------------------------------------------------------------------------
  721. // Type that can hold a page number
  722. typedef uintptr_t PageID;
  723. // Type that can hold the length of a run of pages
  724. typedef uintptr_t Length;
  725. static const Length kMaxValidPages = (~static_cast<Length>(0)) >> kPageShift;
  726. // Convert byte size into pages. This won't overflow, but may return
  727. // an unreasonably large value if bytes is huge enough.
  728. static inline Length pages(size_t bytes) {
  729. return (bytes >> kPageShift) +
  730. ((bytes & (kPageSize - 1)) > 0 ? 1 : 0);
  731. }
  732. // Convert a user size into the number of bytes that will actually be
  733. // allocated
  734. static size_t AllocationSize(size_t bytes) {
  735. if (bytes > kMaxSize) {
  736. // Large object: we allocate an integral number of pages
  737. ASSERT(bytes <= (kMaxValidPages << kPageShift));
  738. return pages(bytes) << kPageShift;
  739. } else {
  740. // Small object: find the size class to which it belongs
  741. return ByteSizeForClass(SizeClass(bytes));
  742. }
  743. }
  744. // Information kept for a span (a contiguous run of pages).
  745. struct Span {
  746. PageID start; // Starting page number
  747. Length length; // Number of pages in span
  748. Span* next; // Used when in link list
  749. Span* prev; // Used when in link list
  750. void* objects; // Linked list of free objects
  751. unsigned int free : 1; // Is the span free
  752. #ifndef NO_TCMALLOC_SAMPLES
  753. unsigned int sample : 1; // Sampled object?
  754. #endif
  755. unsigned int sizeclass : 8; // Size-class for small objects (or 0)
  756. unsigned int refcount : 11; // Number of non-free objects
  757. bool decommitted : 1;
  758. #undef SPAN_HISTORY
  759. #ifdef SPAN_HISTORY
  760. // For debugging, we can keep a log events per span
  761. int nexthistory;
  762. char history[64];
  763. int value[64];
  764. #endif
  765. };
  766. #if TCMALLOC_TRACK_DECOMMITED_SPANS
  767. #define ASSERT_SPAN_COMMITTED(span) ASSERT(!span->decommitted)
  768. #else
  769. #define ASSERT_SPAN_COMMITTED(span)
  770. #endif
  771. #ifdef SPAN_HISTORY
  772. void Event(Span* span, char op, int v = 0) {
  773. span->history[span->nexthistory] = op;
  774. span->value[span->nexthistory] = v;
  775. span->nexthistory++;
  776. if (span->nexthistory == sizeof(span->history)) span->nexthistory = 0;
  777. }
  778. #else
  779. #define Event(s,o,v) ((void) 0)
  780. #endif
  781. // Allocator/deallocator for spans
  782. static PageHeapAllocator<Span> span_allocator;
  783. static Span* NewSpan(PageID p, Length len) {
  784. Span* result = span_allocator.New();
  785. memset(result, 0, sizeof(*result));
  786. result->start = p;
  787. result->length = len;
  788. #ifdef SPAN_HISTORY
  789. result->nexthistory = 0;
  790. #endif
  791. return result;
  792. }
  793. static inline void DeleteSpan(Span* span) {
  794. #ifndef NDEBUG
  795. // In debug mode, trash the contents of deleted Spans
  796. memset(span, 0x3f, sizeof(*span));
  797. #endif
  798. span_allocator.Delete(span);
  799. }
  800. // -------------------------------------------------------------------------
  801. // Doubly linked list of spans.
  802. // -------------------------------------------------------------------------
  803. static inline void DLL_Init(Span* list) {
  804. list->next = list;
  805. list->prev = list;
  806. }
  807. static inline void DLL_Remove(Span* span) {
  808. span->prev->next = span->next;
  809. span->next->prev = span->prev;
  810. span->prev = NULL;
  811. span->next = NULL;
  812. }
  813. static ALWAYS_INLINE bool DLL_IsEmpty(const Span* list) {
  814. return list->next == list;
  815. }
  816. #ifndef WTF_CHANGES
  817. static int DLL_Length(const Span* list) {
  818. int result = 0;
  819. for (Span* s = list->next; s != list; s = s->next) {
  820. result++;
  821. }
  822. return result;
  823. }
  824. #endif
  825. #if 0 /* Not needed at the moment -- causes compiler warnings if not used */
  826. static void DLL_Print(const char* label, const Span* list) {
  827. MESSAGE("%-10s %p:", label, list);
  828. for (const Span* s = list->next; s != list; s = s->next) {
  829. MESSAGE(" <%p,%u,%u>", s, s->start, s->length);
  830. }
  831. MESSAGE("\n");
  832. }
  833. #endif
  834. static inline void DLL_Prepend(Span* list, Span* span) {
  835. ASSERT(span->next == NULL);
  836. ASSERT(span->prev == NULL);
  837. span->next = list->next;
  838. span->prev = list;
  839. list->next->prev = span;
  840. list->next = span;
  841. }
  842. // -------------------------------------------------------------------------
  843. // Stack traces kept for sampled allocations
  844. // The following state is protected by pageheap_lock_.
  845. // -------------------------------------------------------------------------
  846. // size/depth are made the same size as a pointer so that some generic
  847. // code below can conveniently cast them back and forth to void*.
  848. static const int kMaxStackDepth = 31;
  849. struct StackTrace {
  850. uintptr_t size; // Size of object
  851. uintptr_t depth; // Number of PC values stored in array below
  852. void* stack[kMaxStackDepth];
  853. };
  854. static PageHeapAllocator<StackTrace> stacktrace_allocator;
  855. static Span sampled_objects;
  856. // -------------------------------------------------------------------------
  857. // Map from page-id to per-page data
  858. // -------------------------------------------------------------------------
  859. // We use PageMap2<> for 32-bit and PageMap3<> for 64-bit machines.
  860. // We also use a simple one-level cache for hot PageID-to-sizeclass mappings,
  861. // because sometimes the sizeclass is all the information we need.
  862. // Selector class -- general selector uses 3-level map
  863. template <int BITS> class MapSelector {
  864. public:
  865. typedef TCMalloc_PageMap3<BITS-kPageShift> Type;
  866. typedef PackedCache<BITS, uint64_t> CacheType;
  867. };
  868. // A two-level map for 32-bit machines
  869. template <> class MapSelector<32> {
  870. public:
  871. typedef TCMalloc_PageMap2<32-kPageShift> Type;
  872. typedef PackedCache<32-kPageShift, uint16_t> CacheType;
  873. };
  874. // -------------------------------------------------------------------------
  875. // Page-level allocator
  876. // * Eager coalescing
  877. //
  878. // Heap for page-level allocation. We allow allocating and freeing a
  879. // contiguous runs of pages (called a "span").
  880. // -------------------------------------------------------------------------
  881. class TCMalloc_PageHeap {
  882. public:
  883. void init();
  884. // Allocate a run of "n" pages. Returns zero if out of memory.
  885. Span* New(Length n);
  886. // Delete the span "[p, p+n-1]".
  887. // REQUIRES: span was returned by earlier call to New() and
  888. // has not yet been deleted.
  889. void Delete(Span* span);
  890. // Mark an allocated span as being used for small objects of the
  891. // specified size-class.
  892. // REQUIRES: span was returned by an earlier call to New()
  893. // and has not yet been deleted.
  894. void RegisterSizeClass(Span* span, size_t sc);
  895. // Split an allocated span into two spans: one of length "n" pages
  896. // followed by another span of length "span->length - n" pages.
  897. // Modifies "*span" to point to the first span of length "n" pages.
  898. // Returns a pointer to the second span.
  899. //
  900. // REQUIRES: "0 < n < span->length"
  901. // REQUIRES: !span->free
  902. // REQUIRES: span->sizeclass == 0
  903. Span* Split(Span* span, Length n);
  904. // Return the descriptor for the specified page.
  905. inline Span* GetDescriptor(PageID p) const {
  906. return reinterpret_cast<Span*>(pagemap_.get(p));
  907. }
  908. #ifdef WTF_CHANGES
  909. inline Span* GetDescriptorEnsureSafe(PageID p)
  910. {
  911. pagemap_.Ensure(p, 1);
  912. return GetDescriptor(p);
  913. }
  914. #endif
  915. // Dump state to stderr
  916. #ifndef WTF_CHANGES
  917. void Dump(TCMalloc_Printer* out);
  918. #endif
  919. // Return number of bytes allocated from system
  920. inline uint64_t SystemBytes() const { return system_bytes_; }
  921. // Return number of free bytes in heap
  922. uint64_t FreeBytes() const {
  923. return (static_cast<uint64_t>(free_pages_) << kPageShift);
  924. }
  925. bool Check();
  926. bool CheckList(Span* list, Length min_pages, Length max_pages);
  927. // Release all pages on the free list for reuse by the OS:
  928. void ReleaseFreePages();
  929. // Return 0 if we have no information, or else the correct sizeclass for p.
  930. // Reads and writes to pagemap_cache_ do not require locking.
  931. // The entries are 64 bits on 64-bit hardware and 16 bits on
  932. // 32-bit hardware, and we don't mind raciness as long as each read of
  933. // an entry yields a valid entry, not a partially updated entry.
  934. size_t GetSizeClassIfCached(PageID p) const {
  935. return pagemap_cache_.GetOrDefault(p, 0);
  936. }
  937. void CacheSizeClass(PageID p, size_t cl) const { pagemap_cache_.Put(p, cl); }
  938. private:
  939. // Pick the appropriate map and cache types based on pointer size
  940. typedef MapSelector<8*sizeof(uintptr_t)>::Type PageMap;
  941. typedef MapSelector<8*sizeof(uintptr_t)>::CacheType PageMapCache;
  942. PageMap pagemap_;
  943. mutable PageMapCache pagemap_cache_;
  944. // We segregate spans of a given size into two circular linked
  945. // lists: one for normal spans, and one for spans whose memory
  946. // has been returned to the system.
  947. struct SpanList {
  948. Span normal;
  949. Span returned;
  950. };
  951. // List of free spans of length >= kMaxPages
  952. SpanList large_;
  953. // Array mapping from span length to a doubly linked list of free spans
  954. SpanList free_[kMaxPages];
  955. // Number of pages kept in free lists
  956. uintptr_t free_pages_;
  957. // Bytes allocated from system
  958. uint64_t system_bytes_;
  959. bool GrowHeap(Length n);
  960. // REQUIRES span->length >= n
  961. // Remove span from its free list, and move any leftover part of
  962. // span into appropriate free lists. Also update "span" to have
  963. // length exactly "n" and mark it as non-free so it can be returned
  964. // to the client.
  965. //
  966. // "released" is true iff "span" was found on a "returned" list.
  967. void Carve(Span* span, Length n, bool released);
  968. void RecordSpan(Span* span) {
  969. pagemap_.set(span->start, span);
  970. if (span->length > 1) {
  971. pagemap_.set(span->start + span->length - 1, span);
  972. }
  973. }
  974. // Allocate a large span of length == n. If successful, returns a
  975. // span of exactly the specified length. Else, returns NULL.
  976. Span* AllocLarge(Length n);
  977. // Incrementally release some memory to the system.
  978. // IncrementalScavenge(n) is called whenever n pages are freed.
  979. void IncrementalScavenge(Length n);
  980. // Number of pages to deallocate before doing more scavenging
  981. int64_t scavenge_counter_;
  982. // Index of last free list we scavenged
  983. size_t scavenge_index_;
  984. #if defined(WTF_CHANGES) && PLATFORM(DARWIN)
  985. friend class FastMallocZone;
  986. #endif
  987. };
  988. void TCMalloc_PageHeap::init()
  989. {
  990. pagemap_.init(MetaDataAlloc);
  991. pagemap_cache_ = PageMapCache(0);
  992. free_pages_ = 0;
  993. system_bytes_ = 0;
  994. scavenge_counter_ = 0;
  995. // Start scavenging at kMaxPages list
  996. scavenge_index_ = kMaxPages-1;
  997. COMPILE_ASSERT(kNumClasses <= (1 << PageMapCache::kValuebits), valuebits);
  998. DLL_Init(&large_.normal);
  999. DLL_Init(&large_.returned);
  1000. for (size_t i = 0; i < kMaxPages; i++) {
  1001. DLL_Init(&free_[i].normal);
  1002. DLL_Init(&free_[i].returned);
  1003. }
  1004. }
  1005. inline Span* TCMalloc_PageHeap::New(Length n) {
  1006. ASSERT(Check());
  1007. ASSERT(n > 0);
  1008. // Find first size >= n that has a non-empty list
  1009. for (Length s = n; s < kMaxPages; s++) {
  1010. Span* ll = NULL;
  1011. bool released = false;
  1012. if (!DLL_IsEmpty(&free_[s].normal)) {
  1013. // Found normal span
  1014. ll = &free_[s].normal;
  1015. } else if (!DLL_IsEmpty(&free_[s].returned)) {
  1016. // Found returned span; reallocate it
  1017. ll = &free_[s].returned;
  1018. released = true;
  1019. } else {
  1020. // Keep looking in larger classes
  1021. continue;
  1022. }
  1023. Span* result = ll->next;
  1024. Carve(result, n, released);
  1025. #if TCMALLOC_TRACK_DECOMMITED_SPANS
  1026. if (result->decommitted) {
  1027. TCMalloc_SystemCommit(reinterpret_cast<void*>(result->start << kPageShift), static_cast<size_t>(n << kPageShift));
  1028. result->decommitted = false;
  1029. }
  1030. #endif
  1031. ASSERT(Check());
  1032. free_pages_ -= n;
  1033. return result;
  1034. }
  1035. Span* result = AllocLarge(n);
  1036. if (result != NULL) {
  1037. ASSERT_SPAN_COMMITTED(result);
  1038. return result;
  1039. }
  1040. // Grow the heap and try again
  1041. if (!GrowHeap(n)) {
  1042. ASSERT(Check());
  1043. return NULL;
  1044. }
  1045. return AllocLarge(n);
  1046. }
  1047. Span* TCMalloc_PageHeap::AllocLarge(Length n) {
  1048. // find the best span (closest to n in size).
  1049. // The following loops implements address-ordered best-fit.
  1050. bool from_released = false;
  1051. Span *best = NULL;
  1052. // Search through normal list
  1053. for (Span* span = large_.normal.next;
  1054. span != &large_.normal;
  1055. span = span->next) {
  1056. if (span->length >= n) {
  1057. if ((best == NULL)
  1058. || (span->length < best->length)
  1059. || ((span->length == best->length) && (span->start < best->start))) {
  1060. best = span;
  1061. from_released = false;
  1062. }
  1063. }
  1064. }
  1065. // Search through released list in case it has a better fit
  1066. for (Span* span = large_.returned.next;
  1067. span != &large_.returned;
  1068. span = span->next) {
  1069. if (span->length >= n) {
  1070. if ((best == NULL)
  1071. || (span->length < best->length)
  1072. || ((span->length == best->length) && (span->start < best->start))) {
  1073. best = span;
  1074. from_released = true;
  1075. }
  1076. }
  1077. }
  1078. if (best != NULL) {
  1079. Carve(best, n, from_released);
  1080. #if TCMALLOC_TRACK_DECOMMITED_SPANS
  1081. if (best->decommitted) {
  1082. TCMalloc_SystemCommit(reinterpret_cast<void*>(best->start << kPageShift), static_cast<size_t>(n << kPageShift));
  1083. best->decommitted = false;
  1084. }
  1085. #endif
  1086. ASSERT(Check());
  1087. free_pages_ -= n;
  1088. return best;
  1089. }
  1090. return NULL;
  1091. }
  1092. Span* TCMalloc_PageHeap::Split(Span* span, Length n) {
  1093. ASSERT(0 < n);
  1094. ASSERT(n < span->length);
  1095. ASSERT(!span->free);
  1096. ASSERT(span->sizeclass == 0);
  1097. Event(span, 'T', n);
  1098. const Length extra = span->length - n;
  1099. Span* leftover = NewSpan(span->start + n, extra);
  1100. Event(leftover, 'U', extra);
  1101. RecordSpan(leftover);
  1102. pagemap_.set(span->start + n - 1, span); // Update map from pageid to span
  1103. span->length = n;
  1104. return leftover;
  1105. }
  1106. #if !TCMALLOC_TRACK_DECOMMITED_SPANS
  1107. static ALWAYS_INLINE void propagateDecommittedState(Span*, Span*) { }
  1108. #else
  1109. static ALWAYS_INLINE void propagateDecommittedState(Span* destination, Span* source)
  1110. {
  1111. destination->decommitted = source->decommitted;
  1112. }
  1113. #endif
  1114. inline void TCMalloc_PageHeap::Carve(Span* span, Length n, bool released) {
  1115. ASSERT(n > 0);
  1116. DLL_Remove(span);
  1117. span->free = 0;
  1118. Event(span, 'A', n);
  1119. const int extra = static_cast<int>(span->length - n);
  1120. ASSERT(extra >= 0);
  1121. if (extra > 0) {
  1122. Span* leftover = NewSpan(span->start + n, extra);
  1123. leftover->free = 1;
  1124. propagateDecommittedState(leftover, span);
  1125. Event(leftover, 'S', extra);
  1126. RecordSpan(leftover);
  1127. // Place leftover span on appropriate free list
  1128. SpanList* listpair = (static_cast<size_t>(extra) < kMaxPages) ? &free_[extra] : &large_;
  1129. Span* dst = released ? &listpair->returned : &listpair->normal;
  1130. DLL_Prepend(dst, leftover);
  1131. span->length = n;
  1132. pagemap_.set(span->start + n - 1, span);
  1133. }
  1134. }
  1135. #if !TCMALLOC_TRACK_DECOMMITED_SPANS
  1136. static ALWAYS_INLINE void mergeDecommittedStates(Span*, Span*) { }
  1137. #else
  1138. static ALWAYS_INLINE void mergeDecommittedStates(Span* destination, Span* other)
  1139. {
  1140. if (other->decommitted)
  1141. destination->decommitted = true;
  1142. }
  1143. #endif
  1144. inline void TCMalloc_PageHeap::Delete(Span* span) {
  1145. ASSERT(Check());
  1146. ASSERT(!span->free);
  1147. ASSERT(span->length > 0);
  1148. ASSERT(GetDescriptor(span->start) == span);
  1149. ASSERT(GetDescriptor(span->start + span->length - 1) == span);
  1150. span->sizeclass = 0;
  1151. #ifndef NO_TCMALLOC_SAMPLES
  1152. span->sample = 0;
  1153. #endif
  1154. // Coalesce -- we guarantee that "p" != 0, so no bounds checking
  1155. // necessary. We do not bother resetting the stale pagemap
  1156. // entries for the pieces we are merging together because we only
  1157. // care about the pagemap entries for the boundaries.
  1158. //
  1159. // Note that the spans we merge into "span" may come out of
  1160. // a "returned" list. For simplicity, we move these into the
  1161. // "normal" list of the appropriate size class.
  1162. const PageID p = span->start;
  1163. const Length n = span->length;
  1164. Span* prev = GetDescriptor(p-1);
  1165. if (prev != NULL && prev->free) {
  1166. // Merge preceding span into this span
  1167. ASSERT(prev->start + prev->length == p);
  1168. const Length len = prev->length;
  1169. mergeDecommittedStates(span, prev);
  1170. DLL_Remove(prev);
  1171. DeleteSpan(prev);
  1172. span->start -= len;
  1173. span->length += len;
  1174. pagemap_.set(span->start, span);
  1175. Event(span, 'L', len);
  1176. }
  1177. Span* next = GetDescriptor(p+n);
  1178. if (next != NULL && next->free) {
  1179. // Merge next span into this span
  1180. ASSERT(next->start == p+n);
  1181. const Length len = next->length;
  1182. mergeDecommittedStates(span, next);
  1183. DLL_Remove(next);
  1184. DeleteSpan(next);
  1185. span->length += len;
  1186. pagemap_.set(span->start + span->length - 1, span);
  1187. Event(span, 'R', len);
  1188. }
  1189. Event(span, 'D', span->length);
  1190. span->free = 1;
  1191. if (span->length < kMaxPages) {
  1192. DLL_Prepend(&free_[span->length].normal, span);
  1193. } else {
  1194. DLL_Prepend(&large_.normal, span);
  1195. }
  1196. free_pages_ += n;
  1197. IncrementalScavenge(n);
  1198. ASSERT(Check());
  1199. }
  1200. void TCMalloc_PageHeap::IncrementalScavenge(Length n) {
  1201. // Fast path; not yet time to release memory
  1202. scavenge_counter_ -= n;
  1203. if (scavenge_counter_ >= 0) return; // Not yet time to scavenge
  1204. // If there is nothing to release, wait for so many pages before
  1205. // scavenging again. With 4K pages, this comes to 16MB of memory.
  1206. static const size_t kDefaultReleaseDelay = 1 << 8;
  1207. // Find index of free list to scavenge
  1208. size_t index = scavenge_index_ + 1;
  1209. for (size_t i = 0; i < kMaxPages+1; i++) {
  1210. if (index > kMaxPages) index = 0;
  1211. SpanList* slist = (index == kMaxPages) ? &large_ : &free_[index];
  1212. if (!DLL_IsEmpty(&slist->normal)) {
  1213. // Release the last span on the normal portion of this list
  1214. Span* s = slist->normal.prev;
  1215. DLL_Remove(s);
  1216. TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
  1217. static_cast<size_t>(s->length << kPageShift));
  1218. #if TCMALLOC_TRACK_DECOMMITED_SPANS
  1219. s->decommitted = true;
  1220. #endif
  1221. DLL_Prepend(&slist->returned, s);
  1222. scavenge_counter_ = std::max<size_t>(64UL, std::min<size_t>(kDefaultReleaseDelay, kDefaultReleaseDelay - (free_pages_ / kDefaultReleaseDelay)));
  1223. if (index == kMaxPages && !DLL_IsEmpty(&slist->normal))
  1224. scavenge_index_ = index - 1;
  1225. else
  1226. scavenge_index_ = index;
  1227. return;
  1228. }
  1229. index++;
  1230. }
  1231. // Nothing to scavenge, delay for a while
  1232. scavenge_counter_ = kDefaultReleaseDelay;
  1233. }
  1234. void TCMalloc_PageHeap::RegisterSizeClass(Span* span, size_t sc) {
  1235. // Associate span object with all interior pages as well
  1236. ASSERT(!span->free);
  1237. ASSERT(GetDescriptor(span->start) == span);
  1238. ASSERT(GetDescriptor(span->start+span->length-1) == span);
  1239. Event(span, 'C', sc);
  1240. span->sizeclass = static_cast<unsigned int>(sc);
  1241. for (Length i = 1; i < span->length-1; i++) {
  1242. pagemap_.set(span->start+i, span);
  1243. }
  1244. }
  1245. #ifndef WTF_CHANGES
  1246. static double PagesToMB(uint64_t pages) {
  1247. return (pages << kPageShift) / 1048576.0;
  1248. }
  1249. void TCMalloc_PageHeap::Dump(TCMalloc_Printer* out) {
  1250. int nonempty_sizes = 0;
  1251. for (int s = 0; s < kMaxPages; s++) {
  1252. if (!DLL_IsEmpty(&free_[s].normal) || !DLL_IsEmpty(&free_[s].returned)) {
  1253. nonempty_sizes++;
  1254. }
  1255. }
  1256. out->printf("------------------------------------------------\n");
  1257. out->printf("PageHeap: %d sizes; %6.1f MB free\n",
  1258. nonempty_sizes, PagesToMB(free_pages_));
  1259. out->printf("------------------------------------------------\n");
  1260. uint64_t total_normal = 0;
  1261. uint64_t total_returned = 0;
  1262. for (int s = 0; s < kMaxPages; s++) {
  1263. const int n_length = DLL_Length(&free_[s].normal);
  1264. const int r_length = DLL_Length(&free_[s].returned);
  1265. if (n_length + r_length > 0) {
  1266. uint64_t n_pages = s * n_length;
  1267. uint64_t r_pages = s * r_length;
  1268. total_normal += n_pages;
  1269. total_returned += r_pages;
  1270. out->printf("%6u pages * %6u spans ~ %6.1f MB; %6.1f MB cum"
  1271. "; unmapped: %6.1f MB; %6.1f MB cum\n",
  1272. s,
  1273. (n_length + r_length),
  1274. PagesToMB(n_pages + r_pages),
  1275. PagesToMB(total_normal + total_returned),
  1276. PagesToMB(r_pages),
  1277. PagesToMB(total_returned));
  1278. }
  1279. }
  1280. uint64_t n_pages = 0;
  1281. uint64_t r_pages = 0;
  1282. int n_spans = 0;
  1283. int r_spans = 0;
  1284. out->printf("Normal large spans:\n");
  1285. for (Span* s = large_.normal.next; s != &large_.normal; s = s->next) {
  1286. out->printf(" [ %6" PRIuS " pages ] %6.1f MB\n",
  1287. s->length, PagesToMB(s->length));
  1288. n_pages += s->length;
  1289. n_spans++;
  1290. }
  1291. out->printf("Unmapped large spans:\n");
  1292. for (Span* s = large_.returned.next; s != &large_.returned; s = s->next) {
  1293. out->printf(" [ %6" PRIuS " pages ] %6.1f MB\n",
  1294. s->length, PagesToMB(s->length));
  1295. r_pages += s->length;
  1296. r_spans++;
  1297. }
  1298. total_normal += n_pages;
  1299. total_returned += r_pages;
  1300. out->printf(">255 large * %6u spans ~ %6.1f MB; %6.1f MB cum"
  1301. "; unmapped: %6.1f MB; %6.1f MB cum\n",
  1302. (n_spans + r_spans),
  1303. PagesToMB(n_pages + r_pages),
  1304. PagesToMB(total_normal + total_returned),
  1305. PagesToMB(r_pages),
  1306. PagesToMB(total_returned));
  1307. }
  1308. #endif
  1309. bool TCMalloc_PageHeap::GrowHeap(Length n) {
  1310. ASSERT(kMaxPages >= kMinSystemAlloc);
  1311. if (n > kMaxValidPages) return false;
  1312. Length ask = (n>kMinSystemAlloc) ? n : static_cast<Length>(kMinSystemAlloc);
  1313. size_t actual_size;
  1314. void* ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize);
  1315. if (ptr == NULL) {
  1316. if (n < ask) {
  1317. // Try growing just "n" pages
  1318. ask = n;
  1319. ptr = TCMalloc_SystemAlloc(ask << kPageShift, &actual_size, kPageSize);;
  1320. }
  1321. if (ptr == NULL) return false;
  1322. }
  1323. ask = actual_size >> kPageShift;
  1324. uint64_t old_system_bytes = system_bytes_;
  1325. system_bytes_ += (ask << kPageShift);
  1326. const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
  1327. ASSERT(p > 0);
  1328. // If we have already a lot of pages allocated, just pre allocate a bunch of
  1329. // memory for the page map. This prevents fragmentation by pagemap metadata
  1330. // when a program keeps allocating and freeing large blocks.
  1331. if (old_system_bytes < kPageMapBigAllocationThreshold
  1332. && system_bytes_ >= kPageMapBigAllocationThreshold) {
  1333. pagemap_.PreallocateMoreMemory();
  1334. }
  1335. // Make sure pagemap_ has entries for all of the new pages.
  1336. // Plus ensure one before and one after so coalescing code
  1337. // does not need bounds-checking.
  1338. if (pagemap_.Ensure(p-1, ask+2)) {
  1339. // Pretend the new area is allocated and then Delete() it to
  1340. // cause any necessary coalescing to occur.
  1341. //
  1342. // We do not adjust free_pages_ here since Delete() will do it for us.
  1343. Span* span = NewSpan(p, ask);
  1344. RecordSpan(span);
  1345. Delete(span);
  1346. ASSERT(Check());
  1347. return true;
  1348. } else {
  1349. // We could not allocate memory within "pagemap_"
  1350. // TODO: Once we can return memory to the system, return the new span
  1351. return false;
  1352. }
  1353. }
  1354. bool TCMalloc_PageHeap::Check() {
  1355. ASSERT(free_[0].normal.next == &free_[0].normal);
  1356. ASSERT(free_[0].returned.next == &free_[0].returned);
  1357. CheckList(&large_.normal, kMaxPages, 1000000000);
  1358. CheckList(&large_.returned, kMaxPages, 1000000000);
  1359. for (Length s = 1; s < kMaxPages; s++) {
  1360. CheckList(&free_[s].normal, s, s);
  1361. CheckList(&free_[s].returned, s, s);
  1362. }
  1363. return true;
  1364. }
  1365. #if ASSERT_DISABLED
  1366. bool TCMalloc_PageHeap::CheckList(Span*, Length, Length) {
  1367. return true;
  1368. }
  1369. #else
  1370. bool TCMalloc_PageHeap::CheckList(Span* list, Length min_pages, Length max_pages) {
  1371. for (Span* s = list->next; s != list; s = s->next) {
  1372. CHECK_CONDITION(s->free);
  1373. CHECK_CONDITION(s->length >= min_pages);
  1374. CHECK_CONDITION(s->length <= max_pages);
  1375. CHECK_CONDITION(GetDescriptor(s->start) == s);
  1376. CHECK_CONDITION(GetDescriptor(s->start+s->length-1) == s);
  1377. }
  1378. return true;
  1379. }
  1380. #endif
  1381. static void ReleaseFreeList(Span* list, Span* returned) {
  1382. // Walk backwards through list so that when we push these
  1383. // spans on the "returned" list, we preserve the order.
  1384. while (!DLL_IsEmpty(list)) {
  1385. Span* s = list->prev;
  1386. DLL_Remove(s);
  1387. DLL_Prepend(returned, s);
  1388. TCMalloc_SystemRelease(reinterpret_cast<void*>(s->start << kPageShift),
  1389. static_cast<size_t>(s->length << kPageShift));
  1390. }
  1391. }
  1392. void TCMalloc_PageHeap::ReleaseFreePages() {
  1393. for (Length s = 0; s < kMaxPages; s++) {
  1394. ReleaseFreeList(&free_[s].normal, &free_[s].returned);
  1395. }
  1396. ReleaseFreeList(&large_.normal, &large_.returned);
  1397. ASSERT(Check());
  1398. }
  1399. //-------------------------------------------------------------------
  1400. // Free list
  1401. //-------------------------------------------------------------------
  1402. class TCMalloc_ThreadCache_FreeList {
  1403. private:
  1404. void* list_; // Linked list of nodes
  1405. uint16_t length_; // Current length
  1406. uint16_t lowater_; // Low water mark for list length
  1407. public:
  1408. void Init() {
  1409. list_ = NULL;
  1410. length_ = 0;
  1411. lowater_ = 0;
  1412. }
  1413. // Return current length of list
  1414. int length() const {
  1415. return length_;
  1416. }
  1417. // Is list empty?
  1418. bool empty() const {
  1419. return list_ == NULL;
  1420. }
  1421. // Low-water mark management
  1422. int lowwatermark() const { return lowater_; }
  1423. void clear_lowwatermark() { lowater_ = length_; }
  1424. ALWAYS_INLINE void Push(void* ptr) {
  1425. SLL_Push(&list_, ptr);
  1426. length_++;
  1427. }
  1428. void PushRange(int N, void *start, void *end) {
  1429. SLL_PushRange(&list_, start, end);
  1430. length_ = length_ + static_cast<uint16_t>(N);
  1431. }
  1432. void PopRange(int N, void **start, void **end) {
  1433. SLL_PopRange(&list_, N, start, end);
  1434. ASSERT(length_ >= N);
  1435. length_ = length_ - static_cast<uint16_t>(N);
  1436. if (length_ < lowater_) lowater_ = length_;
  1437. }
  1438. ALWAYS_INLINE void* Pop() {
  1439. ASSERT(list_ != NULL);
  1440. length_--;
  1441. if (length_ < lowater_) lowater_ = length_;
  1442. return SLL_Pop(&list_);
  1443. }
  1444. #ifdef WTF_CHANGES
  1445. template <class Finder, class Reader>
  1446. void enumerateFreeObjects(Finder& finder, const Reader& reader)
  1447. {
  1448. for (void* nextObject = list_; nextObject; nextObject = *reader(reinterpret_cast<void**>(nextObject)))
  1449. finder.visit(nextObject);
  1450. }
  1451. #endif
  1452. };
  1453. //-------------------------------------------------------------------
  1454. // Data kept per thread
  1455. //-------------------------------------------------------------------
  1456. class TCMalloc_ThreadCache {
  1457. private:
  1458. typedef TCMalloc_ThreadCache_FreeList FreeList;
  1459. #if COMPILER(MSVC)
  1460. typedef DWORD ThreadIdentifier;
  1461. #else
  1462. typedef pthread_t ThreadIdentifier;
  1463. #endif
  1464. size_t size_; // Combined size of data
  1465. ThreadIdentifier tid_; // Which thread owns it
  1466. bool in_setspecific_; // Called pthread_setspecific?
  1467. FreeList list_[kNumClasses]; // Array indexed by size-class
  1468. // We sample allocations, biased by the size of the allocation
  1469. uint32_t rnd_; // Cheap random number generator
  1470. size_t bytes_until_sample_; // Bytes until we sample next
  1471. // Allocate a new heap. REQUIRES: pageheap_lock is held.
  1472. static inline TCMalloc_ThreadCache* NewHeap(ThreadIdentifier tid);
  1473. // Use only as pthread thread-specific destructor function.
  1474. static void DestroyThreadCache(void* ptr);
  1475. public:
  1476. // All ThreadCache objects are kept in a linked list (for stats collection)
  1477. TCMalloc_ThreadCache* next_;
  1478. TCMalloc_ThreadCache* prev_;
  1479. void Init(ThreadIdentifier tid);
  1480. void Cleanup();
  1481. // Accessors (mostly just for printing stats)
  1482. int freelist_length(size_t cl) const { return list_[cl].length(); }
  1483. // Total byte size in cache
  1484. size_t Size() const { return size_; }
  1485. void* Allocate(size_t size);
  1486. void Deallocate(void* ptr, size_t size_class);
  1487. void FetchFromCentralCache(size_t cl, size_t allocationSize);
  1488. void ReleaseToCentralCache(size_t cl, int N);
  1489. void Scavenge();
  1490. void Print() const;
  1491. // Record allocation of "k" bytes. Return true iff allocation
  1492. // should be sampled
  1493. bool SampleAllocation(size_t k);
  1494. // Pick next sampling point
  1495. void PickNextSample(size_t k);
  1496. static void InitModule();
  1497. static void InitTSD();
  1498. static TCMalloc_ThreadCache* GetThreadHeap();
  1499. static TCMalloc_ThreadCache* GetCache();
  1500. static TCMalloc_ThreadCache* GetCacheIfPresent();
  1501. static TCMalloc_ThreadCache* CreateCacheIfNecessary();
  1502. static void DeleteCache(TCMalloc_ThreadCache* heap);
  1503. static void BecomeIdle();
  1504. static void RecomputeThreadCacheSize();
  1505. #ifdef WTF_CHANGES
  1506. template <class Finder, class Reader>
  1507. void enumerateFreeObjects(Finder& finder, const Reader& reader)
  1508. {
  1509. for (unsigned sizeClass = 0; sizeClass < kNumClasses; sizeClass++)
  1510. list_[sizeClass].enumerateFreeObjects(finder, reader);
  1511. }
  1512. #endif
  1513. };
  1514. //-------------------------------------------------------------------
  1515. // Data kept per size-class in central cache
  1516. //-------------------------------------------------------------------
  1517. class TCMalloc_Central_FreeList {
  1518. public:
  1519. void Init(size_t cl);
  1520. // These methods all do internal locking.
  1521. // Insert the specified range into the central freelist. N is the number of
  1522. // elements in the range.
  1523. void InsertRange(void *start, void *end, int N);
  1524. // Returns the actual number of fetched elements into N.
  1525. void RemoveRange(void **start, void **end, int *N);
  1526. // Returns the number of free objects in cache.
  1527. size_t length() {
  1528. SpinLockHolder h(&lock_);
  1529. return counter_;
  1530. }
  1531. // Returns the number of free objects in the transfer cache.
  1532. int tc_length() {
  1533. SpinLockHolder h(&lock_);
  1534. return used_slots_ * num_objects_to_move[size_class_];
  1535. }
  1536. #ifdef WTF_CHANGES
  1537. template <class Finder, class Reader>
  1538. void enumerateFreeObjects(Finder& finder, const Reader& reader)
  1539. {
  1540. for (Span* span = &empty_; span && span != &empty_; span = (span->next ? reader(span->next) : 0))
  1541. ASSERT(!span->objects);
  1542. ASSERT(!nonempty_.objects);
  1543. for (Span* span = reader(nonempty_.next); span && span != &nonempty_; span = (span->next ? reader(span->next) : 0)) {
  1544. for (void* nextObject = span->objects; nextObject; nextObject = *reader(reinterpret_cast<void**>(nextObject)))
  1545. finder.visit(nextObject);
  1546. }
  1547. }
  1548. #endif
  1549. private:
  1550. // REQUIRES: lock_ is held
  1551. // Remove object from cache and return.
  1552. // Return NULL if no free entries in cache.
  1553. void* FetchFromSpans();
  1554. // REQUIRES: lock_ is held
  1555. // Remove object from cache and return. Fetches
  1556. // from pageheap if cache is empty. Only returns
  1557. // NULL on allocation failure.
  1558. void* FetchFromSpansSafe();
  1559. // REQUIRES: lock_ is held
  1560. // Release a linked list of objects to spans.
  1561. // May temporarily release lock_.
  1562. void ReleaseListToSpans(void *start);
  1563. // REQUIRES: lock_ is held
  1564. // Release an object to spans.
  1565. // May temporarily release lock_.
  1566. void ReleaseToSpans(void* object);
  1567. // REQUIRES: lock_ is held
  1568. // Populate cache by fetching from the page heap.
  1569. // May temporarily release lock_.
  1570. void Populate();
  1571. // REQUIRES: lock is held.
  1572. // Tries to make room for a TCEntry. If the cache is full it will try to
  1573. // expand it at the cost of some other cache size. Return false if there is
  1574. // no space.
  1575. bool MakeCacheSpace();
  1576. // REQUIRES: lock_ for locked_size_class is held.
  1577. // Picks a "random" size class to steal TCEntry slot from. In reality it
  1578. // just iterates over the sizeclasses but does so without taking a lock.
  1579. // Returns true on success.
  1580. // May temporarily lock a "random" size class.
  1581. static bool EvictRandomSizeClass(size_t locked_size_class, bool force);
  1582. // REQUIRES: lock_ is *not* held.
  1583. // Tries to shrink the Cache. If force is true it will relase objects to
  1584. // spans if it allows it to shrink the cache. Return false if it failed to
  1585. // shrink the cache. Decrements cache_size_ on succeess.
  1586. // May temporarily take lock_. If it takes lock_, the locked_size_class
  1587. // lock is released to the thread from holding two size class locks
  1588. // concurrently which could lead to a deadlock.
  1589. bool ShrinkCache(int locked_size_class, bool force);
  1590. // This lock protects all the data members. cached_entries and cache_size_
  1591. // may be looked at without holding the lock.
  1592. SpinLock lock_;
  1593. // We keep linked lists of empty and non-empty spans.
  1594. size_t size_class_; // My size class
  1595. Span empty_; // Dummy header for list of empty spans
  1596. Span nonempty_; // Dummy header for list of non-empty spans
  1597. size_t counter_; // Number of free objects in cache entry
  1598. // Here we reserve space for TCEntry cache slots. Since one size class can
  1599. // end up getting all the TCEntries quota in the system we just preallocate
  1600. // sufficient number of entries here.
  1601. TCEntry tc_slots_[kNumTransferEntries];
  1602. // Number of currently used cached entries in tc_slots_. This variable is
  1603. // updated under a lock but can be read without one.
  1604. int32_t used_slots_;
  1605. // The current number of slots for this size class. This is an
  1606. // adaptive value that is increased if there is lots of traffic
  1607. // on a given size class.
  1608. int32_t cache_size_;
  1609. };
  1610. // Pad each CentralCache object to multiple of 64 bytes
  1611. class TCMalloc_Central_FreeListPadded : public TCMalloc_Central_FreeList {
  1612. private:
  1613. char pad_[(64 - (sizeof(TCMalloc_Central_FreeList) % 64)) % 64];
  1614. };
  1615. //-------------------------------------------------------------------
  1616. // Global variables
  1617. //-------------------------------------------------------------------
  1618. // Central cache -- a collection of free-lists, one per size-class.
  1619. // We have a separate lock per free-list to reduce contention.
  1620. static TCMalloc_Central_FreeListPadded central_cache[kNumClasses];
  1621. // Page-level allocator
  1622. static SpinLock pageheap_lock = SPINLOCK_INITIALIZER;
  1623. static void* pageheap_memory[(sizeof(TCMalloc_PageHeap) + sizeof(void*) - 1) / sizeof(void*)];
  1624. static bool phinited = false;
  1625. // Avoid extra level of indirection by making "pageheap" be just an alias
  1626. // of pageheap_memory.
  1627. typedef union {
  1628. void* m_memory;
  1629. TCMalloc_PageHeap* m_pageHeap;
  1630. } PageHeapUnion;
  1631. static inline TCMalloc_PageHeap* getPageHeap()
  1632. {
  1633. PageHeapUnion u = { &pageheap_memory[0] };
  1634. return u.m_pageHeap;
  1635. }
  1636. #define pageheap getPageHeap()
  1637. // If TLS is available, we also store a copy
  1638. // of the per-thread object in a __thread variable
  1639. // since __thread variables are faster to read
  1640. // than pthread_getspecific(). We still need
  1641. // pthread_setspecific() because __thread
  1642. // variables provide no way to run cleanup
  1643. // code when a thread is destroyed.
  1644. #ifdef HAVE_TLS
  1645. static __thread TCMalloc_ThreadCache *threadlocal_heap;
  1646. #endif
  1647. // Thread-specific key. Initialization here is somewhat tricky
  1648. // because some Linux startup code invokes malloc() before it
  1649. // is in a good enough state to handle pthread_keycreate().
  1650. // Therefore, we use TSD keys only after tsd_inited is set to true.
  1651. // Until then, we use a slow path to get the heap object.
  1652. static bool tsd_inited = false;
  1653. static pthread_key_t heap_key;
  1654. #if COMPILER(MSVC)
  1655. DWORD tlsIndex = TLS_OUT_OF_INDEXES;
  1656. #endif
  1657. static ALWAYS_INLINE void setThreadHeap(TCMalloc_ThreadCache* heap)
  1658. {
  1659. // still do pthread_setspecific when using MSVC fast TLS to
  1660. // benefit from the delete callback.
  1661. pthread_setspecific(heap_key, heap);
  1662. #if COMPILER(MSVC)
  1663. TlsSetValue(tlsIndex, heap);
  1664. #endif
  1665. }
  1666. // Allocator for thread heaps
  1667. static PageHeapAllocator<TCMalloc_ThreadCache> threadheap_allocator;
  1668. // Linked list of heap objects. Protected by pageheap_lock.
  1669. static TCMalloc_ThreadCache* thread_heaps = NULL;
  1670. static int thread_heap_count = 0;
  1671. // Overall thread cache size. Protected by pageheap_lock.
  1672. static size_t overall_thread_cache_size = kDefaultOverallThreadCacheSize;
  1673. // Global per-thread cache size. Writes are protected by
  1674. // pageheap_lock. Reads are done without any locking, which should be
  1675. // fine as long as size_t can be written atomically and we don't place
  1676. // invariants between this variable and other pieces of state.
  1677. static volatile size_t per_thread_cache_size = kMaxThreadCacheSize;
  1678. //-------------------------------------------------------------------
  1679. // Central cache implementation
  1680. //-------------------------------------------------------------------
  1681. void TCMalloc_Central_FreeList::Init(size_t cl) {
  1682. lock_.Init();
  1683. size_class_ = cl;
  1684. DLL_Init(&empty_);
  1685. DLL_Init(&nonempty_);
  1686. counter_ = 0;
  1687. cache_size_ = 1;
  1688. used_slots_ = 0;
  1689. ASSERT(cache_size_ <= kNumTransferEntries);
  1690. }
  1691. void TCMalloc_Central_FreeList::ReleaseListToSpans(void* start) {
  1692. while (start) {
  1693. void *next = SLL_Next(start);
  1694. ReleaseToSpans(start);
  1695. start = next;
  1696. }
  1697. }
  1698. ALWAYS_INLINE void TCMalloc_Central_FreeList::ReleaseToSpans(void* object) {
  1699. const PageID p = reinterpret_cast<uintptr_t>(object) >> kPageShift;
  1700. Span* span = pageheap->GetDescriptor(p);
  1701. ASSERT(span != NULL);
  1702. ASSERT(span->refcount > 0);
  1703. // If span is empty, move it to non-empty list
  1704. if (span->objects == NULL) {
  1705. DLL_Remove(span);
  1706. DLL_Prepend(&nonempty_, span);
  1707. Event(span, 'N', 0);
  1708. }
  1709. // The following check is expensive, so it is disabled by default
  1710. if (false) {
  1711. // Check that object does not occur in list
  1712. int got = 0;
  1713. for (void* p = span->objects; p != NULL; p = *((void**) p)) {
  1714. ASSERT(p != object);
  1715. got++;
  1716. }
  1717. ASSERT(got + span->refcount ==
  1718. (span->length<<kPageShift)/ByteSizeForClass(span->sizeclass));
  1719. }
  1720. counter_++;
  1721. span->refcount--;
  1722. if (span->refcount == 0) {
  1723. Event(span, '#', 0);
  1724. counter_ -= (span->length<<kPageShift) / ByteSizeForClass(span->sizeclass);
  1725. DLL_Remove(span);
  1726. // Release central list lock while operating on pageheap
  1727. lock_.Unlock();
  1728. {
  1729. SpinLockHolder h(&pageheap_lock);
  1730. pageheap->Delete(span);
  1731. }
  1732. lock_.Lock();
  1733. } else {
  1734. *(reinterpret_cast<void**>(object)) = span->objects;
  1735. span->objects = object;
  1736. }
  1737. }
  1738. ALWAYS_INLINE bool TCMalloc_Central_FreeList::EvictRandomSizeClass(
  1739. size_t locked_size_class, bool force) {
  1740. static int race_counter = 0;
  1741. int t = race_counter++; // Updated without a lock, but who cares.
  1742. if (t >= static_cast<int>(kNumClasses)) {
  1743. while (t >= static_cast<int>(kNumClasses)) {
  1744. t -= kNumClasses;
  1745. }
  1746. race_counter = t;
  1747. }
  1748. ASSERT(t >= 0);
  1749. ASSERT(t < static_cast<int>(kNumClasses));
  1750. if (t == static_cast<int>(locked_size_class)) return false;
  1751. return central_cache[t].ShrinkCache(static_cast<int>(locked_size_class), force);
  1752. }
  1753. bool TCMalloc_Central_FreeList::MakeCacheSpace() {
  1754. // Is there room in the cache?
  1755. if (used_slots_ < cache_size_) return true;
  1756. // Check if we can expand this cache?
  1757. if (cache_size_ == kNumTransferEntries) return false;
  1758. // Ok, we'll try to grab an entry from some other size class.
  1759. if (EvictRandomSizeClass(size_class_, false) ||
  1760. EvictRandomSizeClass(size_class_, true)) {
  1761. // Succeeded in evicting, we're going to make our cache larger.
  1762. cache_size_++;
  1763. return true;
  1764. }
  1765. return false;
  1766. }
  1767. namespace {
  1768. class LockInverter {
  1769. private:
  1770. SpinLock *held_, *temp_;
  1771. public:
  1772. inline explicit LockInverter(SpinLock* held, SpinLock *temp)
  1773. : held_(held), temp_(temp) { held_->Unlock(); temp_->Lock(); }
  1774. inline ~LockInverter() { temp_->Unlock(); held_->Lock(); }
  1775. };
  1776. }
  1777. bool TCMalloc_Central_FreeList::ShrinkCache(int locked_size_class, bool force) {
  1778. // Start with a quick check without taking a lock.
  1779. if (cache_size_ == 0) return false;
  1780. // We don't evict from a full cache unless we are 'forcing'.
  1781. if (force == false && used_slots_ == cache_size_) return false;
  1782. // Grab lock, but first release the other lock held by this thread. We use
  1783. // the lock inverter to ensure that we never hold two size class locks
  1784. // concurrently. That can create a deadlock because there is no well
  1785. // defined nesting order.
  1786. LockInverter li(&central_cache[locked_size_class].lock_, &lock_);
  1787. ASSERT(used_slots_ <= cache_size_);
  1788. ASSERT(0 <= cache_size_);
  1789. if (cache_size_ == 0) return false;
  1790. if (used_slots_ == cache_size_) {
  1791. if (force == false) return false;
  1792. // ReleaseListToSpans releases the lock, so we have to make all the
  1793. // updates to the central list before calling it.
  1794. cache_size_--;
  1795. used_slots_--;
  1796. ReleaseListToSpans(tc_slots_[used_slots_].head);
  1797. return true;
  1798. }
  1799. cache_size_--;
  1800. return true;
  1801. }
  1802. void TCMalloc_Central_FreeList::InsertRange(void *start, void *end, int N) {
  1803. SpinLockHolder h(&lock_);
  1804. if (N == num_objects_to_move[size_class_] &&
  1805. MakeCacheSpace()) {
  1806. int slot = used_slots_++;
  1807. ASSERT(slot >=0);
  1808. ASSERT(slot < kNumTransferEntries);
  1809. TCEntry *entry = &tc_slots_[slot];
  1810. entry->head = start;
  1811. entry->tail = end;
  1812. return;
  1813. }
  1814. ReleaseListToSpans(start);
  1815. }
  1816. void TCMalloc_Central_FreeList::RemoveRange(void **start, void **end, int *N) {
  1817. int num = *N;
  1818. ASSERT(num > 0);
  1819. SpinLockHolder h(&lock_);
  1820. if (num == num_objects_to_move[size_class_] && used_slots_ > 0) {
  1821. int slot = --used_slots_;
  1822. ASSERT(slot >= 0);
  1823. TCEntry *entry = &tc_slots_[slot];
  1824. *start = entry->head;
  1825. *end = entry->tail;
  1826. return;
  1827. }
  1828. // TODO: Prefetch multiple TCEntries?
  1829. void *tail = FetchFromSpansSafe();
  1830. if (!tail) {
  1831. // We are completely out of memory.
  1832. *start = *end = NULL;
  1833. *N = 0;
  1834. return;
  1835. }
  1836. SLL_SetNext(tail, NULL);
  1837. void *head = tail;
  1838. int count = 1;
  1839. while (count < num) {
  1840. void *t = FetchFromSpans();
  1841. if (!t) break;
  1842. SLL_Push(&head, t);
  1843. count++;
  1844. }
  1845. *start = head;
  1846. *end = tail;
  1847. *N = count;
  1848. }
  1849. void* TCMalloc_Central_FreeList::FetchFromSpansSafe() {
  1850. void *t = FetchFromSpans();
  1851. if (!t) {
  1852. Populate();
  1853. t = FetchFromSpans();
  1854. }
  1855. return t;
  1856. }
  1857. void* TCMalloc_Central_FreeList::FetchFromSpans() {
  1858. if (DLL_IsEmpty(&nonempty_)) return NULL;
  1859. Span* span = nonempty_.next;
  1860. ASSERT(span->objects != NULL);
  1861. ASSERT_SPAN_COMMITTED(span);
  1862. span->refcount++;
  1863. void* result = span->objects;
  1864. span->objects = *(reinterpret_cast<void**>(result));
  1865. if (span->objects == NULL) {
  1866. // Move to empty list
  1867. DLL_Remove(span);
  1868. DLL_Prepend(&empty_, span);
  1869. Event(span, 'E', 0);
  1870. }
  1871. counter_--;
  1872. return result;
  1873. }
  1874. // Fetch memory from the system and add to the central cache freelist.
  1875. ALWAYS_INLINE void TCMalloc_Central_FreeList::Populate() {
  1876. // Release central list lock while operating on pageheap
  1877. lock_.Unlock();
  1878. const size_t npages = class_to_pages[size_class_];
  1879. Span* span;
  1880. {
  1881. SpinLockHolder h(&pageheap_lock);
  1882. span = pageheap->New(npages);
  1883. if (span) pageheap->RegisterSizeClass(span, size_class_);
  1884. }
  1885. if (span == NULL) {
  1886. MESSAGE("allocation failed: %d\n", errno);
  1887. lock_.Lock();
  1888. return;
  1889. }
  1890. ASSERT_SPAN_COMMITTED(span);
  1891. ASSERT(span->length == npages);
  1892. // Cache sizeclass info eagerly. Locking is not necessary.
  1893. // (Instead of being eager, we could just replace any stale info
  1894. // about this span, but that seems to be no better in practice.)
  1895. for (size_t i = 0; i < npages; i++) {
  1896. pageheap->CacheSizeClass(span->start + i, size_class_);
  1897. }
  1898. // Split the block into pieces and add to the free-list
  1899. // TODO: coloring of objects to avoid cache conflicts?
  1900. void** tail = &span->objects;
  1901. char* ptr = reinterpret_cast<char*>(span->start << kPageShift);
  1902. char* limit = ptr + (npages << kPageShift);
  1903. const size_t size = ByteSizeForClass(size_class_);
  1904. int num = 0;
  1905. char* nptr;
  1906. while ((nptr = ptr + size) <= limit) {
  1907. *tail = ptr;
  1908. tail = reinterpret_cast<void**>(ptr);
  1909. ptr = nptr;
  1910. num++;
  1911. }
  1912. ASSERT(ptr <= limit);
  1913. *tail = NULL;
  1914. span->refcount = 0; // No sub-object in use yet
  1915. // Add span to list of non-empty spans
  1916. lock_.Lock();
  1917. DLL_Prepend(&nonempty_, span);
  1918. counter_ += num;
  1919. }
  1920. //-------------------------------------------------------------------
  1921. // TCMalloc_ThreadCache implementation
  1922. //-------------------------------------------------------------------
  1923. inline bool TCMalloc_ThreadCache::SampleAllocation(size_t k) {
  1924. if (bytes_until_sample_ < k) {
  1925. PickNextSample(k);
  1926. return true;
  1927. } else {
  1928. bytes_until_sample_ -= k;
  1929. return false;
  1930. }
  1931. }
  1932. void TCMalloc_ThreadCache::Init(ThreadIdentifier tid) {
  1933. size_ = 0;
  1934. next_ = NULL;
  1935. prev_ = NULL;
  1936. tid_ = tid;
  1937. in_setspecific_ = false;
  1938. for (size_t cl = 0; cl < kNumClasses; ++cl) {
  1939. list_[cl].Init();
  1940. }
  1941. // Initialize RNG -- run it for a bit to get to good values
  1942. bytes_until_sample_ = 0;
  1943. rnd_ = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(this));
  1944. for (int i = 0; i < 100; i++) {
  1945. PickNextSample(static_cast<size_t>(FLAGS_tcmalloc_sample_parameter * 2));
  1946. }
  1947. }
  1948. void TCMalloc_ThreadCache::Cleanup() {
  1949. // Put unused memory back into central cache
  1950. for (size_t cl = 0; cl < kNumClasses; ++cl) {
  1951. if (list_[cl].length() > 0) {
  1952. ReleaseToCentralCache(cl, list_[cl].length());
  1953. }
  1954. }
  1955. }
  1956. ALWAYS_INLINE void* TCMalloc_ThreadCache::Allocate(size_t size) {
  1957. ASSERT(size <= kMaxSize);
  1958. const size_t cl = SizeClass(size);
  1959. FreeList* list = &list_[cl];
  1960. size_t allocationSize = ByteSizeForClass(cl);
  1961. if (list->empty()) {
  1962. FetchFromCentralCache(cl, allocationSize);
  1963. if (list->empty()) return NULL;
  1964. }
  1965. size_ -= allocationSize;
  1966. return list->Pop();
  1967. }
  1968. inline void TCMalloc_ThreadCache::Deallocate(void* ptr, size_t cl) {
  1969. size_ += ByteSizeForClass(cl);
  1970. FreeList* list = &list_[cl];
  1971. list->Push(ptr);
  1972. // If enough data is free, put back into central cache
  1973. if (list->length() > kMaxFreeListLength) {
  1974. ReleaseToCentralCache(cl, num_objects_to_move[cl]);
  1975. }
  1976. if (size_ >= per_thread_cache_size) Scavenge();
  1977. }
  1978. // Remove some objects of class "cl" from central cache and add to thread heap
  1979. ALWAYS_INLINE void TCMalloc_ThreadCache::FetchFromCentralCache(size_t cl, size_t allocationSize) {
  1980. int fetch_count = num_objects_to_move[cl];
  1981. void *start, *end;
  1982. central_cache[cl].RemoveRange(&start, &end, &fetch_count);
  1983. list_[cl].PushRange(fetch_count, start, end);
  1984. size_ += allocationSize * fetch_count;
  1985. }
  1986. // Remove some objects of class "cl" from thread heap and add to central cache
  1987. inline void TCMalloc_ThreadCache::ReleaseToCentralCache(size_t cl, int N) {
  1988. ASSERT(N > 0);
  1989. FreeList* src = &list_[cl];
  1990. if (N > src->length()) N = src->length();
  1991. size_ -= N*ByteSizeForClass(cl);
  1992. // We return prepackaged chains of the correct size to the central cache.
  1993. // TODO: Use the same format internally in the thread caches?
  1994. int batch_size = num_objects_to_move[cl];
  1995. while (N > batch_size) {
  1996. void *tail, *head;
  1997. src->PopRange(batch_size, &head, &tail);
  1998. central_cache[cl].InsertRange(head, tail, batch_size);
  1999. N -= batch_size;
  2000. }
  2001. void *tail, *head;
  2002. src->PopRange(N, &head, &tail);
  2003. central_cache[cl].InsertRange(head, tail, N);
  2004. }
  2005. // Release idle memory to the central cache
  2006. inline void TCMalloc_ThreadCache::Scavenge() {
  2007. // If the low-water mark for the free list is L, it means we would
  2008. // not have had to allocate anything from the central cache even if
  2009. // we had reduced the free list size by L. We aim to get closer to
  2010. // that situation by dropping L/2 nodes from the free list. This
  2011. // may not release much memory, but if so we will call scavenge again
  2012. // pretty soon and the low-water marks will be high on that call.
  2013. //int64 start = CycleClock::Now();
  2014. for (size_t cl = 0; cl < kNumClasses; cl++) {
  2015. FreeList* list = &list_[cl];
  2016. const int lowmark = list->lowwatermark();
  2017. if (lowmark > 0) {
  2018. const int drop = (lowmark > 1) ? lowmark/2 : 1;
  2019. ReleaseToCentralCache(cl, drop);
  2020. }
  2021. list->clear_lowwatermark();
  2022. }
  2023. //int64 finish = CycleClock::Now();
  2024. //CycleTimer ct;
  2025. //MESSAGE("GC: %.0f ns\n", ct.CyclesToUsec(finish-start)*1000.0);
  2026. }
  2027. void TCMalloc_ThreadCache::PickNextSample(size_t k) {
  2028. // Make next "random" number
  2029. // x^32+x^22+x^2+x^1+1 is a primitive polynomial for random numbers
  2030. static const uint32_t kPoly = (1 << 22) | (1 << 2) | (1 << 1) | (1 << 0);
  2031. uint32_t r = rnd_;
  2032. rnd_ = (r << 1) ^ ((static_cast<int32_t>(r) >> 31) & kPoly);
  2033. // Next point is "rnd_ % (sample_period)". I.e., average
  2034. // increment is "sample_period/2".
  2035. const int flag_value = static_cast<int>(FLAGS_tcmalloc_sample_parameter);
  2036. static int last_flag_value = -1;
  2037. if (flag_value != last_flag_value) {
  2038. SpinLockHolder h(&sample_period_lock);
  2039. int i;
  2040. for (i = 0; i < (static_cast<int>(sizeof(primes_list)/sizeof(primes_list[0])) - 1); i++) {
  2041. if (primes_list[i] >= flag_value) {
  2042. break;
  2043. }
  2044. }
  2045. sample_period = primes_list[i];
  2046. last_flag_value = flag_value;
  2047. }
  2048. bytes_until_sample_ += rnd_ % sample_period;
  2049. if (k > (static_cast<size_t>(-1) >> 2)) {
  2050. // If the user has asked for a huge allocation then it is possible
  2051. // for the code below to loop infinitely. Just return (note that
  2052. // this throws off the sampling accuracy somewhat, but a user who
  2053. // is allocating more than 1G of memory at a time can live with a
  2054. // minor inaccuracy in profiling of small allocations, and also
  2055. // would rather not wait for the loop below to terminate).
  2056. return;
  2057. }
  2058. while (bytes_until_sample_ < k) {
  2059. // Increase bytes_until_sample_ by enough average sampling periods
  2060. // (sample_period >> 1) to allow us to sample past the current
  2061. // allocation.
  2062. bytes_until_sample_ += (sample_period >> 1);
  2063. }
  2064. bytes_until_sample_ -= k;
  2065. }
  2066. void TCMalloc_ThreadCache::InitModule() {
  2067. // There is a slight potential race here because of double-checked
  2068. // locking idiom. However, as long as the program does a small
  2069. // allocation before switching to multi-threaded mode, we will be
  2070. // fine. We increase the chances of doing such a small allocation
  2071. // by doing one in the constructor of the module_enter_exit_hook
  2072. // object declared below.
  2073. SpinLockHolder h(&pageheap_lock);
  2074. if (!phinited) {
  2075. #ifdef WTF_CHANGES
  2076. InitTSD();
  2077. #endif
  2078. InitSizeClasses();
  2079. threadheap_allocator.Init();
  2080. span_allocator.Init();
  2081. span_allocator.New(); // Reduce cache conflicts
  2082. span_allocator.New(); // Reduce cache conflicts
  2083. stacktrace_allocator.Init();
  2084. DLL_Init(&sampled_objects);
  2085. for (size_t i = 0; i < kNumClasses; ++i) {
  2086. central_cache[i].Init(i);
  2087. }
  2088. pageheap->init();
  2089. phinited = 1;
  2090. #if defined(WTF_CHANGES) && PLATFORM(DARWIN)
  2091. FastMallocZone::init();
  2092. #endif
  2093. }
  2094. }
  2095. inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::NewHeap(ThreadIdentifier tid) {
  2096. // Create the heap and add it to the linked list
  2097. TCMalloc_ThreadCache *heap = threadheap_allocator.New();
  2098. heap->Init(tid);
  2099. heap->next_ = thread_heaps;
  2100. heap->prev_ = NULL;
  2101. if (thread_heaps != NULL) thread_heaps->prev_ = heap;
  2102. thread_heaps = heap;
  2103. thread_heap_count++;
  2104. RecomputeThreadCacheSize();
  2105. return heap;
  2106. }
  2107. inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetThreadHeap() {
  2108. #ifdef HAVE_TLS
  2109. // __thread is faster, but only when the kernel supports it
  2110. if (KernelSupportsTLS())
  2111. return threadlocal_heap;
  2112. #elif COMPILER(MSVC)
  2113. return static_cast<TCMalloc_ThreadCache*>(TlsGetValue(tlsIndex));
  2114. #else
  2115. return static_cast<TCMalloc_ThreadCache*>(pthread_getspecific(heap_key));
  2116. #endif
  2117. }
  2118. inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCache() {
  2119. TCMalloc_ThreadCache* ptr = NULL;
  2120. if (!tsd_inited) {
  2121. InitModule();
  2122. } else {
  2123. ptr = GetThreadHeap();
  2124. }
  2125. if (ptr == NULL) ptr = CreateCacheIfNecessary();
  2126. return ptr;
  2127. }
  2128. // In deletion paths, we do not try to create a thread-cache. This is
  2129. // because we may be in the thread destruction code and may have
  2130. // already cleaned up the cache for this thread.
  2131. inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCacheIfPresent() {
  2132. if (!tsd_inited) return NULL;
  2133. void* const p = GetThreadHeap();
  2134. return reinterpret_cast<TCMalloc_ThreadCache*>(p);
  2135. }
  2136. void TCMalloc_ThreadCache::InitTSD() {
  2137. ASSERT(!tsd_inited);
  2138. pthread_key_create(&heap_key, DestroyThreadCache);
  2139. #if COMPILER(MSVC)
  2140. tlsIndex = TlsAlloc();
  2141. #endif
  2142. tsd_inited = true;
  2143. #if !COMPILER(MSVC)
  2144. // We may have used a fake pthread_t for the main thread. Fix it.
  2145. pthread_t zero;
  2146. memset(&zero, 0, sizeof(zero));
  2147. #endif
  2148. #ifndef WTF_CHANGES
  2149. SpinLockHolder h(&pageheap_lock);
  2150. #else
  2151. ASSERT(pageheap_lock.IsHeld());
  2152. #endif
  2153. for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
  2154. #if COMPILER(MSVC)
  2155. if (h->tid_ == 0) {
  2156. h->tid_ = GetCurrentThreadId();
  2157. }
  2158. #else
  2159. if (pthread_equal(h->tid_, zero)) {
  2160. h->tid_ = pthread_self();
  2161. }
  2162. #endif
  2163. }
  2164. }
  2165. TCMalloc_ThreadCache* TCMalloc_ThreadCache::CreateCacheIfNecessary() {
  2166. // Initialize per-thread data if necessary
  2167. TCMalloc_ThreadCache* heap = NULL;
  2168. {
  2169. SpinLockHolder h(&pageheap_lock);
  2170. #if COMPILER(MSVC)
  2171. DWORD me;
  2172. if (!tsd_inited) {
  2173. me = 0;
  2174. } else {
  2175. me = GetCurrentThreadId();
  2176. }
  2177. #else
  2178. // Early on in glibc's life, we cannot even call pthread_self()
  2179. pthread_t me;
  2180. if (!tsd_inited) {
  2181. memset(&me, 0, sizeof(me));
  2182. } else {
  2183. me = pthread_self();
  2184. }
  2185. #endif
  2186. // This may be a recursive malloc call from pthread_setspecific()
  2187. // In that case, the heap for this thread has already been created
  2188. // and added to the linked list. So we search for that first.
  2189. for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
  2190. #if COMPILER(MSVC)
  2191. if (h->tid_ == me) {
  2192. #else
  2193. if (pthread_equal(h->tid_, me)) {
  2194. #endif
  2195. heap = h;
  2196. break;
  2197. }
  2198. }
  2199. if (heap == NULL) heap = NewHeap(me);
  2200. }
  2201. // We call pthread_setspecific() outside the lock because it may
  2202. // call malloc() recursively. The recursive call will never get
  2203. // here again because it will find the already allocated heap in the
  2204. // linked list of heaps.
  2205. if (!heap->in_setspecific_ && tsd_inited) {
  2206. heap->in_setspecific_ = true;
  2207. setThreadHeap(heap);
  2208. }
  2209. return heap;
  2210. }
  2211. void TCMalloc_ThreadCache::BecomeIdle() {
  2212. if (!tsd_inited) return; // No caches yet
  2213. TCMalloc_ThreadCache* heap = GetThreadHeap();
  2214. if (heap == NULL) return; // No thread cache to remove
  2215. if (heap->in_setspecific_) return; // Do not disturb the active caller
  2216. heap->in_setspecific_ = true;
  2217. pthread_setspecific(heap_key, NULL);
  2218. #ifdef HAVE_TLS
  2219. // Also update the copy in __thread
  2220. threadlocal_heap = NULL;
  2221. #endif
  2222. heap->in_setspecific_ = false;
  2223. if (GetThreadHeap() == heap) {
  2224. // Somehow heap got reinstated by a recursive call to malloc
  2225. // from pthread_setspecific. We give up in this case.
  2226. return;
  2227. }
  2228. // We can now get rid of the heap
  2229. DeleteCache(heap);
  2230. }
  2231. void TCMalloc_ThreadCache::DestroyThreadCache(void* ptr) {
  2232. // Note that "ptr" cannot be NULL since pthread promises not
  2233. // to invoke the destructor on NULL values, but for safety,
  2234. // we check anyway.
  2235. if (ptr == NULL) return;
  2236. #ifdef HAVE_TLS
  2237. // Prevent fast path of GetThreadHeap() from returning heap.
  2238. threadlocal_heap = NULL;
  2239. #endif
  2240. DeleteCache(reinterpret_cast<TCMalloc_ThreadCache*>(ptr));
  2241. }
  2242. void TCMalloc_ThreadCache::DeleteCache(TCMalloc_ThreadCache* heap) {
  2243. // Remove all memory from heap
  2244. heap->Cleanup();
  2245. // Remove from linked list
  2246. SpinLockHolder h(&pageheap_lock);
  2247. if (heap->next_ != NULL) heap->next_->prev_ = heap->prev_;
  2248. if (heap->prev_ != NULL) heap->prev_->next_ = heap->next_;
  2249. if (thread_heaps == heap) thread_heaps = heap->next_;
  2250. thread_heap_count--;
  2251. RecomputeThreadCacheSize();
  2252. threadheap_allocator.Delete(heap);
  2253. }
  2254. void TCMalloc_ThreadCache::RecomputeThreadCacheSize() {
  2255. // Divide available space across threads
  2256. int n = thread_heap_count > 0 ? thread_heap_count : 1;
  2257. size_t space = overall_thread_cache_size / n;
  2258. // Limit to allowed range
  2259. if (space < kMinThreadCacheSize) space = kMinThreadCacheSize;
  2260. if (space > kMaxThreadCacheSize) space = kMaxThreadCacheSize;
  2261. per_thread_cache_size = space;
  2262. }
  2263. void TCMalloc_ThreadCache::Print() const {
  2264. for (size_t cl = 0; cl < kNumClasses; ++cl) {
  2265. MESSAGE(" %5" PRIuS " : %4d len; %4d lo\n",
  2266. ByteSizeForClass(cl),
  2267. list_[cl].length(),
  2268. list_[cl].lowwatermark());
  2269. }
  2270. }
  2271. // Extract interesting stats
  2272. struct TCMallocStats {
  2273. uint64_t system_bytes; // Bytes alloced from system
  2274. uint64_t thread_bytes; // Bytes in thread caches
  2275. uint64_t central_bytes; // Bytes in central cache
  2276. uint64_t transfer_bytes; // Bytes in central transfer cache
  2277. uint64_t pageheap_bytes; // Bytes in page heap
  2278. uint64_t metadata_bytes; // Bytes alloced for metadata
  2279. };
  2280. #ifndef WTF_CHANGES
  2281. // Get stats into "r". Also get per-size-class counts if class_count != NULL
  2282. static void ExtractStats(TCMallocStats* r, uint64_t* class_count) {
  2283. r->central_bytes = 0;
  2284. r->transfer_bytes = 0;
  2285. for (int cl = 0; cl < kNumClasses; ++cl) {
  2286. const int length = central_cache[cl].length();
  2287. const int tc_length = central_cache[cl].tc_length();
  2288. r->central_bytes += static_cast<uint64_t>(ByteSizeForClass(cl)) * length;
  2289. r->transfer_bytes +=
  2290. static_cast<uint64_t>(ByteSizeForClass(cl)) * tc_length;
  2291. if (class_count) class_count[cl] = length + tc_length;
  2292. }
  2293. // Add stats from per-thread heaps
  2294. r->thread_bytes = 0;
  2295. { // scope
  2296. SpinLockHolder h(&pageheap_lock);
  2297. for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
  2298. r->thread_bytes += h->Size();
  2299. if (class_count) {
  2300. for (size_t cl = 0; cl < kNumClasses; ++cl) {
  2301. class_count[cl] += h->freelist_length(cl);
  2302. }
  2303. }
  2304. }
  2305. }
  2306. { //scope
  2307. SpinLockHolder h(&pageheap_lock);
  2308. r->system_bytes = pageheap->SystemBytes();
  2309. r->metadata_bytes = metadata_system_bytes;
  2310. r->pageheap_bytes = pageheap->FreeBytes();
  2311. }
  2312. }
  2313. #endif
  2314. #ifndef WTF_CHANGES
  2315. // WRITE stats to "out"
  2316. static void DumpStats(TCMalloc_Printer* out, int level) {
  2317. TCMallocStats stats;
  2318. uint64_t class_count[kNumClasses];
  2319. ExtractStats(&stats, (level >= 2 ? class_count : NULL));
  2320. if (level >= 2) {
  2321. out->printf("------------------------------------------------\n");
  2322. uint64_t cumulative = 0;
  2323. for (int cl = 0; cl < kNumClasses; ++cl) {
  2324. if (class_count[cl] > 0) {
  2325. uint64_t class_bytes = class_count[cl] * ByteSizeForClass(cl);
  2326. cumulative += class_bytes;
  2327. out->printf("class %3d [ %8" PRIuS " bytes ] : "
  2328. "%8" PRIu64 " objs; %5.1f MB; %5.1f cum MB\n",
  2329. cl, ByteSizeForClass(cl),
  2330. class_count[cl],
  2331. class_bytes / 1048576.0,
  2332. cumulative / 1048576.0);
  2333. }
  2334. }
  2335. SpinLockHolder h(&pageheap_lock);
  2336. pageheap->Dump(out);
  2337. }
  2338. const uint64_t bytes_in_use = stats.system_bytes
  2339. - stats.pageheap_bytes
  2340. - stats.central_bytes
  2341. - stats.transfer_bytes
  2342. - stats.thread_bytes;
  2343. out->printf("------------------------------------------------\n"
  2344. "MALLOC: %12" PRIu64 " Heap size\n"
  2345. "MALLOC: %12" PRIu64 " Bytes in use by application\n"
  2346. "MALLOC: %12" PRIu64 " Bytes free in page heap\n"
  2347. "MALLOC: %12" PRIu64 " Bytes free in central cache\n"
  2348. "MALLOC: %12" PRIu64 " Bytes free in transfer cache\n"
  2349. "MALLOC: %12" PRIu64 " Bytes free in thread caches\n"
  2350. "MALLOC: %12" PRIu64 " Spans in use\n"
  2351. "MALLOC: %12" PRIu64 " Thread heaps in use\n"
  2352. "MALLOC: %12" PRIu64 " Metadata allocated\n"
  2353. "------------------------------------------------\n",
  2354. stats.system_bytes,
  2355. bytes_in_use,
  2356. stats.pageheap_bytes,
  2357. stats.central_bytes,
  2358. stats.transfer_bytes,
  2359. stats.thread_bytes,
  2360. uint64_t(span_allocator.inuse()),
  2361. uint64_t(threadheap_allocator.inuse()),
  2362. stats.metadata_bytes);
  2363. }
  2364. static void PrintStats(int level) {
  2365. const int kBufferSize = 16 << 10;
  2366. char* buffer = new char[kBufferSize];
  2367. TCMalloc_Printer printer(buffer, kBufferSize);
  2368. DumpStats(&printer, level);
  2369. write(STDERR_FILENO, buffer, strlen(buffer));
  2370. delete[] buffer;
  2371. }
  2372. static void** DumpStackTraces() {
  2373. // Count how much space we need
  2374. int needed_slots = 0;
  2375. {
  2376. SpinLockHolder h(&pageheap_lock);
  2377. for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
  2378. StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
  2379. needed_slots += 3 + stack->depth;
  2380. }
  2381. needed_slots += 100; // Slop in case sample grows
  2382. needed_slots += needed_slots/8; // An extra 12.5% slop
  2383. }
  2384. void** result = new void*[needed_slots];
  2385. if (result == NULL) {
  2386. MESSAGE("tcmalloc: could not allocate %d slots for stack traces\n",
  2387. needed_slots);
  2388. return NULL;
  2389. }
  2390. SpinLockHolder h(&pageheap_lock);
  2391. int used_slots = 0;
  2392. for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
  2393. ASSERT(used_slots < needed_slots); // Need to leave room for terminator
  2394. StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
  2395. if (used_slots + 3 + stack->depth >= needed_slots) {
  2396. // No more room
  2397. break;
  2398. }
  2399. result[used_slots+0] = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
  2400. result[used_slots+1] = reinterpret_cast<void*>(stack->size);
  2401. result[used_slots+2] = reinterpret_cast<void*>(stack->depth);
  2402. for (int d = 0; d < stack->depth; d++) {
  2403. result[used_slots+3+d] = stack->stack[d];
  2404. }
  2405. used_slots += 3 + stack->depth;
  2406. }
  2407. result[used_slots] = reinterpret_cast<void*>(static_cast<uintptr_t>(0));
  2408. return result;
  2409. }
  2410. #endif
  2411. #ifndef WTF_CHANGES
  2412. // TCMalloc's support for extra malloc interfaces
  2413. class TCMallocImplementation : public MallocExtension {
  2414. public:
  2415. virtual void GetStats(char* buffer, int buffer_length) {
  2416. ASSERT(buffer_length > 0);
  2417. TCMalloc_Printer printer(buffer, buffer_length);
  2418. // Print level one stats unless lots of space is available
  2419. if (buffer_length < 10000) {
  2420. DumpStats(&printer, 1);
  2421. } else {
  2422. DumpStats(&printer, 2);
  2423. }
  2424. }
  2425. virtual void** ReadStackTraces() {
  2426. return DumpStackTraces();
  2427. }
  2428. virtual bool GetNumericProperty(const char* name, size_t* value) {
  2429. ASSERT(name != NULL);
  2430. if (strcmp(name, "generic.current_allocated_bytes") == 0) {
  2431. TCMallocStats stats;
  2432. ExtractStats(&stats, NULL);
  2433. *value = stats.system_bytes
  2434. - stats.thread_bytes
  2435. - stats.central_bytes
  2436. - stats.pageheap_bytes;
  2437. return true;
  2438. }
  2439. if (strcmp(name, "generic.heap_size") == 0) {
  2440. TCMallocStats stats;
  2441. ExtractStats(&stats, NULL);
  2442. *value = stats.system_bytes;
  2443. return true;
  2444. }
  2445. if (strcmp(name, "tcmalloc.slack_bytes") == 0) {
  2446. // We assume that bytes in the page heap are not fragmented too
  2447. // badly, and are therefore available for allocation.
  2448. SpinLockHolder l(&pageheap_lock);
  2449. *value = pageheap->FreeBytes();
  2450. return true;
  2451. }
  2452. if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
  2453. SpinLockHolder l(&pageheap_lock);
  2454. *value = overall_thread_cache_size;
  2455. return true;
  2456. }
  2457. if (strcmp(name, "tcmalloc.current_total_thread_cache_bytes") == 0) {
  2458. TCMallocStats stats;
  2459. ExtractStats(&stats, NULL);
  2460. *value = stats.thread_bytes;
  2461. return true;
  2462. }
  2463. return false;
  2464. }
  2465. virtual bool SetNumericProperty(const char* name, size_t value) {
  2466. ASSERT(name != NULL);
  2467. if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
  2468. // Clip the value to a reasonable range
  2469. if (value < kMinThreadCacheSize) value = kMinThreadCacheSize;
  2470. if (value > (1<<30)) value = (1<<30); // Limit to 1GB
  2471. SpinLockHolder l(&pageheap_lock);
  2472. overall_thread_cache_size = static_cast<size_t>(value);
  2473. TCMalloc_ThreadCache::RecomputeThreadCacheSize();
  2474. return true;
  2475. }
  2476. return false;
  2477. }
  2478. virtual void MarkThreadIdle() {
  2479. TCMalloc_ThreadCache::BecomeIdle();
  2480. }
  2481. virtual void ReleaseFreeMemory() {
  2482. SpinLockHolder h(&pageheap_lock);
  2483. pageheap->ReleaseFreePages();
  2484. }
  2485. };
  2486. #endif
  2487. // The constructor allocates an object to ensure that initialization
  2488. // runs before main(), and therefore we do not have a chance to become
  2489. // multi-threaded before initialization. We also create the TSD key
  2490. // here. Presumably by the time this constructor runs, glibc is in
  2491. // good enough shape to handle pthread_key_create().
  2492. //
  2493. // The constructor also takes the opportunity to tell STL to use
  2494. // tcmalloc. We want to do this early, before construct time, so
  2495. // all user STL allocations go through tcmalloc (which works really
  2496. // well for STL).
  2497. //
  2498. // The destructor prints stats when the program exits.
  2499. class TCMallocGuard {
  2500. public:
  2501. TCMallocGuard() {
  2502. #ifdef HAVE_TLS // this is true if the cc/ld/libc combo support TLS
  2503. // Check whether the kernel also supports TLS (needs to happen at runtime)
  2504. CheckIfKernelSupportsTLS();
  2505. #endif
  2506. #ifndef WTF_CHANGES
  2507. #ifdef WIN32 // patch the windows VirtualAlloc, etc.
  2508. PatchWindowsFunctions(); // defined in windows/patch_functions.cc
  2509. #endif
  2510. #endif
  2511. free(malloc(1));
  2512. TCMalloc_ThreadCache::InitTSD();
  2513. free(malloc(1));
  2514. #ifndef WTF_CHANGES
  2515. MallocExtension::Register(new TCMallocImplementation);
  2516. #endif
  2517. }
  2518. #ifndef WTF_CHANGES
  2519. ~TCMallocGuard() {
  2520. const char* env = getenv("MALLOCSTATS");
  2521. if (env != NULL) {
  2522. int level = atoi(env);
  2523. if (level < 1) level = 1;
  2524. PrintStats(level);
  2525. }
  2526. #ifdef WIN32
  2527. UnpatchWindowsFunctions();
  2528. #endif
  2529. }
  2530. #endif
  2531. };
  2532. #ifndef WTF_CHANGES
  2533. static TCMallocGuard module_enter_exit_hook;
  2534. #endif
  2535. //-------------------------------------------------------------------
  2536. // Helpers for the exported routines below
  2537. //-------------------------------------------------------------------
  2538. #ifndef WTF_CHANGES
  2539. static Span* DoSampledAllocation(size_t size) {
  2540. // Grab the stack trace outside the heap lock
  2541. StackTrace tmp;
  2542. tmp.depth = GetStackTrace(tmp.stack, kMaxStackDepth, 1);
  2543. tmp.size = size;
  2544. SpinLockHolder h(&pageheap_lock);
  2545. // Allocate span
  2546. Span *span = pageheap->New(pages(size == 0 ? 1 : size));
  2547. if (span == NULL) {
  2548. return NULL;
  2549. }
  2550. // Allocate stack trace
  2551. StackTrace *stack = stacktrace_allocator.New();
  2552. if (stack == NULL) {
  2553. // Sampling failed because of lack of memory
  2554. return span;
  2555. }
  2556. *stack = tmp;
  2557. span->sample = 1;
  2558. span->objects = stack;
  2559. DLL_Prepend(&sampled_objects, span);
  2560. return span;
  2561. }
  2562. #endif
  2563. static inline bool CheckCachedSizeClass(void *ptr) {
  2564. PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
  2565. size_t cached_value = pageheap->GetSizeClassIfCached(p);
  2566. return cached_value == 0 ||
  2567. cached_value == pageheap->GetDescriptor(p)->sizeclass;
  2568. }
  2569. static inline void* CheckedMallocResult(void *result)
  2570. {
  2571. ASSERT(result == 0 || CheckCachedSizeClass(result));
  2572. return result;
  2573. }
  2574. static inline void* SpanToMallocResult(Span *span) {
  2575. ASSERT_SPAN_COMMITTED(span);
  2576. pageheap->CacheSizeClass(span->start, 0);
  2577. return
  2578. CheckedMallocResult(reinterpret_cast<void*>(span->start << kPageShift));
  2579. }
  2580. static ALWAYS_INLINE void* do_malloc(size_t size) {
  2581. void* ret = NULL;
  2582. #ifdef WTF_CHANGES
  2583. ASSERT(!isForbidden());
  2584. #endif
  2585. // The following call forces module initialization
  2586. TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
  2587. #ifndef WTF_CHANGES
  2588. if ((FLAGS_tcmalloc_sample_parameter > 0) && heap->SampleAllocation(size)) {
  2589. Span* span = DoSampledAllocation(size);
  2590. if (span != NULL) {
  2591. ret = SpanToMallocResult(span);
  2592. }
  2593. } else
  2594. #endif
  2595. if (size > kMaxSize) {
  2596. // Use page-level allocator
  2597. SpinLockHolder h(&pageheap_lock);
  2598. Span* span = pageheap->New(pages(size));
  2599. if (span != NULL) {
  2600. ret = SpanToMallocResult(span);
  2601. }
  2602. } else {
  2603. // The common case, and also the simplest. This just pops the
  2604. // size-appropriate freelist, afer replenishing it if it's empty.
  2605. ret = CheckedMallocResult(heap->Allocate(size));
  2606. }
  2607. if (ret == NULL) errno = ENOMEM;
  2608. return ret;
  2609. }
  2610. static ALWAYS_INLINE void do_free(void* ptr) {
  2611. if (ptr == NULL) return;
  2612. ASSERT(pageheap != NULL); // Should not call free() before malloc()
  2613. const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
  2614. Span* span = NULL;
  2615. size_t cl = pageheap->GetSizeClassIfCached(p);
  2616. if (cl == 0) {
  2617. span = pageheap->GetDescriptor(p);
  2618. cl = span->sizeclass;
  2619. pageheap->CacheSizeClass(p, cl);
  2620. }
  2621. if (cl != 0) {
  2622. #ifndef NO_TCMALLOC_SAMPLES
  2623. ASSERT(!pageheap->GetDescriptor(p)->sample);
  2624. #endif
  2625. TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCacheIfPresent();
  2626. if (heap != NULL) {
  2627. heap->Deallocate(ptr, cl);
  2628. } else {
  2629. // Delete directly into central cache
  2630. SLL_SetNext(ptr, NULL);
  2631. central_cache[cl].InsertRange(ptr, ptr, 1);
  2632. }
  2633. } else {
  2634. SpinLockHolder h(&pageheap_lock);
  2635. ASSERT(reinterpret_cast<uintptr_t>(ptr) % kPageSize == 0);
  2636. ASSERT(span != NULL && span->start == p);
  2637. #ifndef NO_TCMALLOC_SAMPLES
  2638. if (span->sample) {
  2639. DLL_Remove(span);
  2640. stacktrace_allocator.Delete(reinterpret_cast<StackTrace*>(span->objects));
  2641. span->objects = NULL;
  2642. }
  2643. #endif
  2644. pageheap->Delete(span);
  2645. }
  2646. }
  2647. #ifndef WTF_CHANGES
  2648. // For use by exported routines below that want specific alignments
  2649. //
  2650. // Note: this code can be slow, and can significantly fragment memory.
  2651. // The expectation is that memalign/posix_memalign/valloc/pvalloc will
  2652. // not be invoked very often. This requirement simplifies our
  2653. // implementation and allows us to tune for expected allocation
  2654. // patterns.
  2655. static void* do_memalign(size_t align, size_t size) {
  2656. ASSERT((align & (align - 1)) == 0);
  2657. ASSERT(align > 0);
  2658. if (pageheap == NULL) TCMalloc_ThreadCache::InitModule();
  2659. // Allocate at least one byte to avoid boundary conditions below
  2660. if (size == 0) size = 1;
  2661. if (size <= kMaxSize && align < kPageSize) {
  2662. // Search through acceptable size classes looking for one with
  2663. // enough alignment. This depends on the fact that
  2664. // InitSizeClasses() currently produces several size classes that
  2665. // are aligned at powers of two. We will waste time and space if
  2666. // we miss in the size class array, but that is deemed acceptable
  2667. // since memalign() should be used rarely.
  2668. size_t cl = SizeClass(size);
  2669. while (cl < kNumClasses && ((class_to_size[cl] & (align - 1)) != 0)) {
  2670. cl++;
  2671. }
  2672. if (cl < kNumClasses) {
  2673. TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
  2674. return CheckedMallocResult(heap->Allocate(class_to_size[cl]));
  2675. }
  2676. }
  2677. // We will allocate directly from the page heap
  2678. SpinLockHolder h(&pageheap_lock);
  2679. if (align <= kPageSize) {
  2680. // Any page-level allocation will be fine
  2681. // TODO: We could put the rest of this page in the appropriate
  2682. // TODO: cache but it does not seem worth it.
  2683. Span* span = pageheap->New(pages(size));
  2684. return span == NULL ? NULL : SpanToMallocResult(span);
  2685. }
  2686. // Allocate extra pages and carve off an aligned portion
  2687. const Length alloc = pages(size + align);
  2688. Span* span = pageheap->New(alloc);
  2689. if (span == NULL) return NULL;
  2690. // Skip starting portion so that we end up aligned
  2691. Length skip = 0;
  2692. while ((((span->start+skip) << kPageShift) & (align - 1)) != 0) {
  2693. skip++;
  2694. }
  2695. ASSERT(skip < alloc);
  2696. if (skip > 0) {
  2697. Span* rest = pageheap->Split(span, skip);
  2698. pageheap->Delete(span);
  2699. span = rest;
  2700. }
  2701. // Skip trailing portion that we do not need to return
  2702. const Length needed = pages(size);
  2703. ASSERT(span->length >= needed);
  2704. if (span->length > needed) {
  2705. Span* trailer = pageheap->Split(span, needed);
  2706. pageheap->Delete(trailer);
  2707. }
  2708. return SpanToMallocResult(span);
  2709. }
  2710. #endif
  2711. // Helpers for use by exported routines below:
  2712. #ifndef WTF_CHANGES
  2713. static inline void do_malloc_stats() {
  2714. PrintStats(1);
  2715. }
  2716. #endif
  2717. static inline int do_mallopt(int, int) {
  2718. return 1; // Indicates error
  2719. }
  2720. #ifdef HAVE_STRUCT_MALLINFO // mallinfo isn't defined on freebsd, for instance
  2721. static inline struct mallinfo do_mallinfo() {
  2722. TCMallocStats stats;
  2723. ExtractStats(&stats, NULL);
  2724. // Just some of the fields are filled in.
  2725. struct mallinfo info;
  2726. memset(&info, 0, sizeof(info));
  2727. // Unfortunately, the struct contains "int" field, so some of the
  2728. // size values will be truncated.
  2729. info.arena = static_cast<int>(stats.system_bytes);
  2730. info.fsmblks = static_cast<int>(stats.thread_bytes
  2731. + stats.central_bytes
  2732. + stats.transfer_bytes);
  2733. info.fordblks = static_cast<int>(stats.pageheap_bytes);
  2734. info.uordblks = static_cast<int>(stats.system_bytes
  2735. - stats.thread_bytes
  2736. - stats.central_bytes
  2737. - stats.transfer_bytes
  2738. - stats.pageheap_bytes);
  2739. return info;
  2740. }
  2741. #endif
  2742. //-------------------------------------------------------------------
  2743. // Exported routines
  2744. //-------------------------------------------------------------------
  2745. // CAVEAT: The code structure below ensures that MallocHook methods are always
  2746. // called from the stack frame of the invoked allocation function.
  2747. // heap-checker.cc depends on this to start a stack trace from
  2748. // the call to the (de)allocation function.
  2749. #ifndef WTF_CHANGES
  2750. extern "C"
  2751. #endif
  2752. void* malloc(size_t size) {
  2753. void* result = do_malloc(size);
  2754. #ifndef WTF_CHANGES
  2755. MallocHook::InvokeNewHook(result, size);
  2756. #endif
  2757. return result;
  2758. }
  2759. #ifndef WTF_CHANGES
  2760. extern "C"
  2761. #endif
  2762. void free(void* ptr) {
  2763. #ifndef WTF_CHANGES
  2764. MallocHook::InvokeDeleteHook(ptr);
  2765. #endif
  2766. do_free(ptr);
  2767. }
  2768. #ifndef WTF_CHANGES
  2769. extern "C"
  2770. #endif
  2771. void* calloc(size_t n, size_t elem_size) {
  2772. const size_t totalBytes = n * elem_size;
  2773. // Protect against overflow
  2774. if (n > 1 && elem_size && (totalBytes / elem_size) != n)
  2775. return 0;
  2776. void* result = do_malloc(totalBytes);
  2777. if (result != NULL) {
  2778. memset(result, 0, totalBytes);
  2779. }
  2780. #ifndef WTF_CHANGES
  2781. MallocHook::InvokeNewHook(result, totalBytes);
  2782. #endif
  2783. return result;
  2784. }
  2785. #ifndef WTF_CHANGES
  2786. extern "C"
  2787. #endif
  2788. void cfree(void* ptr) {
  2789. #ifndef WTF_CHANGES
  2790. MallocHook::InvokeDeleteHook(ptr);
  2791. #endif
  2792. do_free(ptr);
  2793. }
  2794. #ifndef WTF_CHANGES
  2795. extern "C"
  2796. #endif
  2797. void* realloc(void* old_ptr, size_t new_size) {
  2798. if (old_ptr == NULL) {
  2799. void* result = do_malloc(new_size);
  2800. #ifndef WTF_CHANGES
  2801. MallocHook::InvokeNewHook(result, new_size);
  2802. #endif
  2803. return result;
  2804. }
  2805. if (new_size == 0) {
  2806. #ifndef WTF_CHANGES
  2807. MallocHook::InvokeDeleteHook(old_ptr);
  2808. #endif
  2809. free(old_ptr);
  2810. return NULL;
  2811. }
  2812. // Get the size of the old entry
  2813. const PageID p = reinterpret_cast<uintptr_t>(old_ptr) >> kPageShift;
  2814. size_t cl = pageheap->GetSizeClassIfCached(p);
  2815. Span *span = NULL;
  2816. size_t old_size;
  2817. if (cl == 0) {
  2818. span = pageheap->GetDescriptor(p);
  2819. cl = span->sizeclass;
  2820. pageheap->CacheSizeClass(p, cl);
  2821. }
  2822. if (cl != 0) {
  2823. old_size = ByteSizeForClass(cl);
  2824. } else {
  2825. ASSERT(span != NULL);
  2826. old_size = span->length << kPageShift;
  2827. }
  2828. // Reallocate if the new size is larger than the old size,
  2829. // or if the new size is significantly smaller than the old size.
  2830. if ((new_size > old_size) || (AllocationSize(new_size) < old_size)) {
  2831. // Need to reallocate
  2832. void* new_ptr = do_malloc(new_size);
  2833. if (new_ptr == NULL) {
  2834. return NULL;
  2835. }
  2836. #ifndef WTF_CHANGES
  2837. MallocHook::InvokeNewHook(new_ptr, new_size);
  2838. #endif
  2839. memcpy(new_ptr, old_ptr, ((old_size < new_size) ? old_size : new_size));
  2840. #ifndef WTF_CHANGES
  2841. MallocHook::InvokeDeleteHook(old_ptr);
  2842. #endif
  2843. // We could use a variant of do_free() that leverages the fact
  2844. // that we already know the sizeclass of old_ptr. The benefit
  2845. // would be small, so don't bother.
  2846. do_free(old_ptr);
  2847. return new_ptr;
  2848. } else {
  2849. return old_ptr;
  2850. }
  2851. }
  2852. #ifndef WTF_CHANGES
  2853. static SpinLock set_new_handler_lock = SPINLOCK_INITIALIZER;
  2854. static inline void* cpp_alloc(size_t size, bool nothrow) {
  2855. for (;;) {
  2856. void* p = do_malloc(size);
  2857. #ifdef PREANSINEW
  2858. return p;
  2859. #else
  2860. if (p == NULL) { // allocation failed
  2861. // Get the current new handler. NB: this function is not
  2862. // thread-safe. We make a feeble stab at making it so here, but
  2863. // this lock only protects against tcmalloc interfering with
  2864. // itself, not with other libraries calling set_new_handler.
  2865. std::new_handler nh;
  2866. {
  2867. SpinLockHolder h(&set_new_handler_lock);
  2868. nh = std::set_new_handler(0);
  2869. (void) std::set_new_handler(nh);
  2870. }
  2871. // If no new_handler is established, the allocation failed.
  2872. if (!nh) {
  2873. if (nothrow) return 0;
  2874. throw std::bad_alloc();
  2875. }
  2876. // Otherwise, try the new_handler. If it returns, retry the
  2877. // allocation. If it throws std::bad_alloc, fail the allocation.
  2878. // if it throws something else, don't interfere.
  2879. try {
  2880. (*nh)();
  2881. } catch (const std::bad_alloc&) {
  2882. if (!nothrow) throw;
  2883. return p;
  2884. }
  2885. } else { // allocation success
  2886. return p;
  2887. }
  2888. #endif
  2889. }
  2890. }
  2891. void* operator new(size_t size) {
  2892. void* p = cpp_alloc(size, false);
  2893. // We keep this next instruction out of cpp_alloc for a reason: when
  2894. // it's in, and new just calls cpp_alloc, the optimizer may fold the
  2895. // new call into cpp_alloc, which messes up our whole section-based
  2896. // stacktracing (see ATTRIBUTE_SECTION, above). This ensures cpp_alloc
  2897. // isn't the last thing this fn calls, and prevents the folding.
  2898. MallocHook::InvokeNewHook(p, size);
  2899. return p;
  2900. }
  2901. void* operator new(size_t size, const std::nothrow_t&) __THROW {
  2902. void* p = cpp_alloc(size, true);
  2903. MallocHook::InvokeNewHook(p, size);
  2904. return p;
  2905. }
  2906. void operator delete(void* p) __THROW {
  2907. MallocHook::InvokeDeleteHook(p);
  2908. do_free(p);
  2909. }
  2910. void operator delete(void* p, const std::nothrow_t&) __THROW {
  2911. MallocHook::InvokeDeleteHook(p);
  2912. do_free(p);
  2913. }
  2914. void* operator new[](size_t size) {
  2915. void* p = cpp_alloc(size, false);
  2916. // We keep this next instruction out of cpp_alloc for a reason: when
  2917. // it's in, and new just calls cpp_alloc, the optimizer may fold the
  2918. // new call into cpp_alloc, which messes up our whole section-based
  2919. // stacktracing (see ATTRIBUTE_SECTION, above). This ensures cpp_alloc
  2920. // isn't the last thing this fn calls, and prevents the folding.
  2921. MallocHook::InvokeNewHook(p, size);
  2922. return p;
  2923. }
  2924. void* operator new[](size_t size, const std::nothrow_t&) __THROW {
  2925. void* p = cpp_alloc(size, true);
  2926. MallocHook::InvokeNewHook(p, size);
  2927. return p;
  2928. }
  2929. void operator delete[](void* p) __THROW {
  2930. MallocHook::InvokeDeleteHook(p);
  2931. do_free(p);
  2932. }
  2933. void operator delete[](void* p, const std::nothrow_t&) __THROW {
  2934. MallocHook::InvokeDeleteHook(p);
  2935. do_free(p);
  2936. }
  2937. extern "C" void* memalign(size_t align, size_t size) __THROW {
  2938. void* result = do_memalign(align, size);
  2939. MallocHook::InvokeNewHook(result, size);
  2940. return result;
  2941. }
  2942. extern "C" int posix_memalign(void** result_ptr, size_t align, size_t size)
  2943. __THROW {
  2944. if (((align % sizeof(void*)) != 0) ||
  2945. ((align & (align - 1)) != 0) ||
  2946. (align == 0)) {
  2947. return EINVAL;
  2948. }
  2949. void* result = do_memalign(align, size);
  2950. MallocHook::InvokeNewHook(result, size);
  2951. if (result == NULL) {
  2952. return ENOMEM;
  2953. } else {
  2954. *result_ptr = result;
  2955. return 0;
  2956. }
  2957. }
  2958. static size_t pagesize = 0;
  2959. extern "C" void* valloc(size_t size) __THROW {
  2960. // Allocate page-aligned object of length >= size bytes
  2961. if (pagesize == 0) pagesize = getpagesize();
  2962. void* result = do_memalign(pagesize, size);
  2963. MallocHook::InvokeNewHook(result, size);
  2964. return result;
  2965. }
  2966. extern "C" void* pvalloc(size_t size) __THROW {
  2967. // Round up size to a multiple of pagesize
  2968. if (pagesize == 0) pagesize = getpagesize();
  2969. size = (size + pagesize - 1) & ~(pagesize - 1);
  2970. void* result = do_memalign(pagesize, size);
  2971. MallocHook::InvokeNewHook(result, size);
  2972. return result;
  2973. }
  2974. extern "C" void malloc_stats(void) {
  2975. do_malloc_stats();
  2976. }
  2977. extern "C" int mallopt(int cmd, int value) {
  2978. return do_mallopt(cmd, value);
  2979. }
  2980. #ifdef HAVE_STRUCT_MALLINFO
  2981. extern "C" struct mallinfo mallinfo(void) {
  2982. return do_mallinfo();
  2983. }
  2984. #endif
  2985. //-------------------------------------------------------------------
  2986. // Some library routines on RedHat 9 allocate memory using malloc()
  2987. // and free it using __libc_free() (or vice-versa). Since we provide
  2988. // our own implementations of malloc/free, we need to make sure that
  2989. // the __libc_XXX variants (defined as part of glibc) also point to
  2990. // the same implementations.
  2991. //-------------------------------------------------------------------
  2992. #if defined(__GLIBC__)
  2993. extern "C" {
  2994. # if defined(__GNUC__) && !defined(__MACH__) && defined(HAVE___ATTRIBUTE__)
  2995. // Potentially faster variants that use the gcc alias extension.
  2996. // Mach-O (Darwin) does not support weak aliases, hence the __MACH__ check.
  2997. # define ALIAS(x) __attribute__ ((weak, alias (x)))
  2998. void* __libc_malloc(size_t size) ALIAS("malloc");
  2999. void __libc_free(void* ptr) ALIAS("free");
  3000. void* __libc_realloc(void* ptr, size_t size) ALIAS("realloc");
  3001. void* __libc_calloc(size_t n, size_t size) ALIAS("calloc");
  3002. void __libc_cfree(void* ptr) ALIAS("cfree");
  3003. void* __libc_memalign(size_t align, size_t s) ALIAS("memalign");
  3004. void* __libc_valloc(size_t size) ALIAS("valloc");
  3005. void* __libc_pvalloc(size_t size) ALIAS("pvalloc");
  3006. int __posix_memalign(void** r, size_t a, size_t s) ALIAS("posix_memalign");
  3007. # undef ALIAS
  3008. # else /* not __GNUC__ */
  3009. // Portable wrappers
  3010. void* __libc_malloc(size_t size) { return malloc(size); }
  3011. void __libc_free(void* ptr) { free(ptr); }
  3012. void* __libc_realloc(void* ptr, size_t size) { return realloc(ptr, size); }
  3013. void* __libc_calloc(size_t n, size_t size) { return calloc(n, size); }
  3014. void __libc_cfree(void* ptr) { cfree(ptr); }
  3015. void* __libc_memalign(size_t align, size_t s) { return memalign(align, s); }
  3016. void* __libc_valloc(size_t size) { return valloc(size); }
  3017. void* __libc_pvalloc(size_t size) { return pvalloc(size); }
  3018. int __posix_memalign(void** r, size_t a, size_t s) {
  3019. return posix_memalign(r, a, s);
  3020. }
  3021. # endif /* __GNUC__ */
  3022. }
  3023. #endif /* __GLIBC__ */
  3024. // Override __libc_memalign in libc on linux boxes specially.
  3025. // They have a bug in libc that causes them to (very rarely) allocate
  3026. // with __libc_memalign() yet deallocate with free() and the
  3027. // definitions above don't catch it.
  3028. // This function is an exception to the rule of calling MallocHook method
  3029. // from the stack frame of the allocation function;
  3030. // heap-checker handles this special case explicitly.
  3031. static void *MemalignOverride(size_t align, size_t size, const void *caller)
  3032. __THROW {
  3033. void* result = do_memalign(align, size);
  3034. MallocHook::InvokeNewHook(result, size);
  3035. return result;
  3036. }
  3037. void *(*__memalign_hook)(size_t, size_t, const void *) = MemalignOverride;
  3038. #endif
  3039. #if defined(WTF_CHANGES) && PLATFORM(DARWIN)
  3040. class FreeObjectFinder {
  3041. const RemoteMemoryReader& m_reader;
  3042. HashSet<void*> m_freeObjects;
  3043. public:
  3044. FreeObjectFinder(const RemoteMemoryReader& reader) : m_reader(reader) { }
  3045. void visit(void* ptr) { m_freeObjects.add(ptr); }
  3046. bool isFreeObject(void* ptr) const { return m_freeObjects.contains(ptr); }
  3047. size_t freeObjectCount() const { return m_freeObjects.size(); }
  3048. void findFreeObjects(TCMalloc_ThreadCache* threadCache)
  3049. {
  3050. for (; threadCache; threadCache = (threadCache->next_ ? m_reader(threadCache->next_) : 0))
  3051. threadCache->enumerateFreeObjects(*this, m_reader);
  3052. }
  3053. void findFreeObjects(TCMalloc_Central_FreeListPadded* centralFreeList, size_t numSizes)
  3054. {
  3055. for (unsigned i = 0; i < numSizes; i++)
  3056. centralFreeList[i].enumerateFreeObjects(*this, m_reader);
  3057. }
  3058. };
  3059. class PageMapFreeObjectFinder {
  3060. const RemoteMemoryReader& m_reader;
  3061. FreeObjectFinder& m_freeObjectFinder;
  3062. public:
  3063. PageMapFreeObjectFinder(const RemoteMemoryReader& reader, FreeObjectFinder& freeObjectFinder)
  3064. : m_reader(reader)
  3065. , m_freeObjectFinder(freeObjectFinder)
  3066. { }
  3067. int visit(void* ptr) const
  3068. {
  3069. if (!ptr)
  3070. return 1;
  3071. Span* span = m_reader(reinterpret_cast<Span*>(ptr));
  3072. if (span->free) {
  3073. void* ptr = reinterpret_cast<void*>(span->start << kPageShift);
  3074. m_freeObjectFinder.visit(ptr);
  3075. } else if (span->sizeclass) {
  3076. // Walk the free list of the small-object span, keeping track of each object seen
  3077. for (void* nextObject = span->objects; nextObject; nextObject = *m_reader(reinterpret_cast<void**>(nextObject)))
  3078. m_freeObjectFinder.visit(nextObject);
  3079. }
  3080. return span->length;
  3081. }
  3082. };
  3083. class PageMapMemoryUsageRecorder {
  3084. task_t m_task;
  3085. void* m_context;
  3086. unsigned m_typeMask;
  3087. vm_range_recorder_t* m_recorder;
  3088. const RemoteMemoryReader& m_reader;
  3089. const FreeObjectFinder& m_freeObjectFinder;
  3090. mutable HashSet<void*> m_seenPointers;
  3091. public:
  3092. PageMapMemoryUsageRecorder(task_t task, void* context, unsigned typeMask, vm_range_recorder_t* recorder, const RemoteMemoryReader& reader, const FreeObjectFinder& freeObjectFinder)
  3093. : m_task(task)
  3094. , m_context(context)
  3095. , m_typeMask(typeMask)
  3096. , m_recorder(recorder)
  3097. , m_reader(reader)
  3098. , m_freeObjectFinder(freeObjectFinder)
  3099. { }
  3100. int visit(void* ptr) const
  3101. {
  3102. if (!ptr)
  3103. return 1;
  3104. Span* span = m_reader(reinterpret_cast<Span*>(ptr));
  3105. if (m_seenPointers.contains(ptr))
  3106. return span->length;
  3107. m_seenPointers.add(ptr);
  3108. // Mark the memory used for the Span itself as an administrative region
  3109. vm_range_t ptrRange = { reinterpret_cast<vm_address_t>(ptr), sizeof(Span) };
  3110. if (m_typeMask & (MALLOC_PTR_REGION_RANGE_TYPE | MALLOC_ADMIN_REGION_RANGE_TYPE))
  3111. (*m_recorder)(m_task, m_context, MALLOC_ADMIN_REGION_RANGE_TYPE, &ptrRange, 1);
  3112. ptrRange.address = span->start << kPageShift;
  3113. ptrRange.size = span->length * kPageSize;
  3114. // Mark the memory region the span represents as candidates for containing pointers
  3115. if (m_typeMask & (MALLOC_PTR_REGION_RANGE_TYPE | MALLOC_ADMIN_REGION_RANGE_TYPE))
  3116. (*m_recorder)(m_task, m_context, MALLOC_PTR_REGION_RANGE_TYPE, &ptrRange, 1);
  3117. if (!span->free && (m_typeMask & MALLOC_PTR_IN_USE_RANGE_TYPE)) {
  3118. // If it's an allocated large object span, mark it as in use
  3119. if (span->sizeclass == 0 && !m_freeObjectFinder.isFreeObject(reinterpret_cast<void*>(ptrRange.address)))
  3120. (*m_recorder)(m_task, m_context, MALLOC_PTR_IN_USE_RANGE_TYPE, &ptrRange, 1);
  3121. else if (span->sizeclass) {
  3122. const size_t byteSize = ByteSizeForClass(span->sizeclass);
  3123. unsigned totalObjects = (span->length << kPageShift) / byteSize;
  3124. ASSERT(span->refcount <= totalObjects);
  3125. char* ptr = reinterpret_cast<char*>(span->start << kPageShift);
  3126. // Mark each allocated small object within the span as in use
  3127. for (unsigned i = 0; i < totalObjects; i++) {
  3128. char* thisObject = ptr + (i * byteSize);
  3129. if (m_freeObjectFinder.isFreeObject(thisObject))
  3130. continue;
  3131. vm_range_t objectRange = { reinterpret_cast<vm_address_t>(thisObject), byteSize };
  3132. (*m_recorder)(m_task, m_context, MALLOC_PTR_IN_USE_RANGE_TYPE, &objectRange, 1);
  3133. }
  3134. }
  3135. }
  3136. return span->length;
  3137. }
  3138. };
  3139. 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)
  3140. {
  3141. RemoteMemoryReader memoryReader(task, reader);
  3142. InitSizeClasses();
  3143. FastMallocZone* mzone = memoryReader(reinterpret_cast<FastMallocZone*>(zoneAddress));
  3144. TCMalloc_PageHeap* pageHeap = memoryReader(mzone->m_pageHeap);
  3145. TCMalloc_ThreadCache** threadHeapsPointer = memoryReader(mzone->m_threadHeaps);
  3146. TCMalloc_ThreadCache* threadHeaps = memoryReader(*threadHeapsPointer);
  3147. TCMalloc_Central_FreeListPadded* centralCaches = memoryReader(mzone->m_centralCaches, sizeof(TCMalloc_Central_FreeListPadded) * kNumClasses);
  3148. FreeObjectFinder finder(memoryReader);
  3149. finder.findFreeObjects(threadHeaps);
  3150. finder.findFreeObjects(centralCaches, kNumClasses);
  3151. TCMalloc_PageHeap::PageMap* pageMap = &pageHeap->pagemap_;
  3152. PageMapFreeObjectFinder pageMapFinder(memoryReader, finder);
  3153. pageMap->visit(pageMapFinder, memoryReader);
  3154. PageMapMemoryUsageRecorder usageRecorder(task, context, typeMask, recorder, memoryReader, finder);
  3155. pageMap->visit(usageRecorder, memoryReader);
  3156. return 0;
  3157. }
  3158. size_t FastMallocZone::size(malloc_zone_t*, const void*)
  3159. {
  3160. return 0;
  3161. }
  3162. void* FastMallocZone::zoneMalloc(malloc_zone_t*, size_t)
  3163. {
  3164. return 0;
  3165. }
  3166. void* FastMallocZone::zoneCalloc(malloc_zone_t*, size_t, size_t)
  3167. {
  3168. return 0;
  3169. }
  3170. void FastMallocZone::zoneFree(malloc_zone_t*, void* ptr)
  3171. {
  3172. // Due to <rdar://problem/5671357> zoneFree may be called by the system free even if the pointer
  3173. // is not in this zone. When this happens, the pointer being freed was not allocated by any
  3174. // zone so we need to print a useful error for the application developer.
  3175. malloc_printf("*** error for object %p: pointer being freed was not allocated\n", ptr);
  3176. }
  3177. void* FastMallocZone::zoneRealloc(malloc_zone_t*, void*, size_t)
  3178. {
  3179. return 0;
  3180. }
  3181. #undef malloc
  3182. #undef free
  3183. #undef realloc
  3184. #undef calloc
  3185. extern "C" {
  3186. malloc_introspection_t jscore_fastmalloc_introspection = { &FastMallocZone::enumerate, &FastMallocZone::goodSize, &FastMallocZone::check, &FastMallocZone::print,
  3187. &FastMallocZone::log, &FastMallocZone::forceLock, &FastMallocZone::forceUnlock, &FastMallocZone::statistics };
  3188. }
  3189. FastMallocZone::FastMallocZone(TCMalloc_PageHeap* pageHeap, TCMalloc_ThreadCache** threadHeaps, TCMalloc_Central_FreeListPadded* centralCaches)
  3190. : m_pageHeap(pageHeap)
  3191. , m_threadHeaps(threadHeaps)
  3192. , m_centralCaches(centralCaches)
  3193. {
  3194. memset(&m_zone, 0, sizeof(m_zone));
  3195. m_zone.zone_name = "JavaScriptCore FastMalloc";
  3196. m_zone.size = &FastMallocZone::size;
  3197. m_zone.malloc = &FastMallocZone::zoneMalloc;
  3198. m_zone.calloc = &FastMallocZone::zoneCalloc;
  3199. m_zone.realloc = &FastMallocZone::zoneRealloc;
  3200. m_zone.free = &FastMallocZone::zoneFree;
  3201. m_zone.valloc = &FastMallocZone::zoneValloc;
  3202. m_zone.destroy = &FastMallocZone::zoneDestroy;
  3203. m_zone.introspect = &jscore_fastmalloc_introspection;
  3204. malloc_zone_register(&m_zone);
  3205. }
  3206. void FastMallocZone::init()
  3207. {
  3208. static FastMallocZone zone(pageheap, &thread_heaps, static_cast<TCMalloc_Central_FreeListPadded*>(central_cache));
  3209. }
  3210. #endif
  3211. void releaseFastMallocFreeMemory()
  3212. {
  3213. SpinLockHolder h(&pageheap_lock);
  3214. pageheap->ReleaseFreePages();
  3215. }
  3216. #if WTF_CHANGES
  3217. } // namespace WTF
  3218. #endif
  3219. #endif // FORCE_SYSTEM_MALLOC