PageRenderTime 278ms CodeModel.GetById 29ms RepoModel.GetById 5ms app.codeStats 3ms

/webview/native/Source/WTF/wtf/FastMalloc.cpp

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