PageRenderTime 263ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/JavaScriptCore/wtf/FastMalloc.cpp

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