1 | // Copyright (c) 2005, 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 | // ---
|
---|
31 | // Author: Sanjay Ghemawat <[email protected]>
|
---|
32 | //
|
---|
33 | // A malloc that uses a per-thread cache to satisfy small malloc requests.
|
---|
34 | // (The time for malloc/free of a small object drops from 300 ns to 50 ns.)
|
---|
35 | //
|
---|
36 | // See doc/tcmalloc.html for a high-level
|
---|
37 | // description of how this malloc works.
|
---|
38 | //
|
---|
39 | // SYNCHRONIZATION
|
---|
40 | // 1. The thread-specific lists are accessed without acquiring any locks.
|
---|
41 | // This is safe because each such list is only accessed by one thread.
|
---|
42 | // 2. We have a lock per central free-list, and hold it while manipulating
|
---|
43 | // the central free list for a particular size.
|
---|
44 | // 3. The central page allocator is protected by "pageheap_lock".
|
---|
45 | // 4. The pagemap (which maps from page-number to descriptor),
|
---|
46 | // can be read without holding any locks, and written while holding
|
---|
47 | // the "pageheap_lock".
|
---|
48 | //
|
---|
49 | // This multi-threaded access to the pagemap is safe for fairly
|
---|
50 | // subtle reasons. We basically assume that when an object X is
|
---|
51 | // allocated by thread A and deallocated by thread B, there must
|
---|
52 | // have been appropriate synchronization in the handoff of object
|
---|
53 | // X from thread A to thread B.
|
---|
54 | //
|
---|
55 | // TODO: Bias reclamation to larger addresses
|
---|
56 | // TODO: implement mallinfo/mallopt
|
---|
57 | // TODO: Better testing
|
---|
58 | // TODO: Return memory to system
|
---|
59 | //
|
---|
60 | // 9/28/2003 (new page-level allocator replaces ptmalloc2):
|
---|
61 | // * malloc/free of small objects goes from ~300 ns to ~50 ns.
|
---|
62 | // * allocation of a reasonably complicated struct
|
---|
63 | // goes from about 1100 ns to about 300 ns.
|
---|
64 |
|
---|
65 | #include "config.h"
|
---|
66 | #include "FastMalloc.h"
|
---|
67 |
|
---|
68 | #include "Assertions.h"
|
---|
69 | #if USE(MULTIPLE_THREADS)
|
---|
70 | #include <pthread.h>
|
---|
71 | #endif
|
---|
72 |
|
---|
73 | #if !defined(USE_SYSTEM_MALLOC) && defined(NDEBUG)
|
---|
74 | #define FORCE_SYSTEM_MALLOC 0
|
---|
75 | #else
|
---|
76 | #define FORCE_SYSTEM_MALLOC 1
|
---|
77 | #endif
|
---|
78 |
|
---|
79 | #ifndef NDEBUG
|
---|
80 | namespace WTF {
|
---|
81 |
|
---|
82 | #if USE(MULTIPLE_THREADS)
|
---|
83 | static pthread_key_t isForbiddenKey;
|
---|
84 | static pthread_once_t isForbiddenKeyOnce = PTHREAD_ONCE_INIT;
|
---|
85 | static void initializeIsForbiddenKey()
|
---|
86 | {
|
---|
87 | pthread_key_create(&isForbiddenKey, 0);
|
---|
88 | }
|
---|
89 |
|
---|
90 | static bool isForbidden()
|
---|
91 | {
|
---|
92 | pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
|
---|
93 | return !!pthread_getspecific(isForbiddenKey);
|
---|
94 | }
|
---|
95 |
|
---|
96 | void fastMallocForbid()
|
---|
97 | {
|
---|
98 | pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
|
---|
99 | pthread_setspecific(isForbiddenKey, &isForbiddenKey);
|
---|
100 | }
|
---|
101 |
|
---|
102 | void fastMallocAllow()
|
---|
103 | {
|
---|
104 | pthread_once(&isForbiddenKeyOnce, initializeIsForbiddenKey);
|
---|
105 | pthread_setspecific(isForbiddenKey, 0);
|
---|
106 | }
|
---|
107 |
|
---|
108 | #else
|
---|
109 |
|
---|
110 | static bool staticIsForbidden;
|
---|
111 | static bool isForbidden()
|
---|
112 | {
|
---|
113 | return staticIsForbidden;
|
---|
114 | }
|
---|
115 |
|
---|
116 | void fastMallocForbid()
|
---|
117 | {
|
---|
118 | staticIsForbidden = true;
|
---|
119 | }
|
---|
120 |
|
---|
121 | void fastMallocAllow()
|
---|
122 | {
|
---|
123 | staticIsForbidden = false;
|
---|
124 | }
|
---|
125 | #endif // USE(MULTIPLE_THREADS)
|
---|
126 |
|
---|
127 | } // namespace WTF
|
---|
128 | #endif // NDEBUG
|
---|
129 |
|
---|
130 | #if FORCE_SYSTEM_MALLOC
|
---|
131 |
|
---|
132 | #include <stdlib.h>
|
---|
133 | #if !PLATFORM(WIN_OS)
|
---|
134 | #include <pthread.h>
|
---|
135 | #endif
|
---|
136 |
|
---|
137 | namespace WTF {
|
---|
138 |
|
---|
139 | void *fastMalloc(size_t n)
|
---|
140 | {
|
---|
141 | ASSERT(!isForbidden());
|
---|
142 | return malloc(n);
|
---|
143 | }
|
---|
144 |
|
---|
145 | void *fastCalloc(size_t n_elements, size_t element_size)
|
---|
146 | {
|
---|
147 | ASSERT(!isForbidden());
|
---|
148 | return calloc(n_elements, element_size);
|
---|
149 | }
|
---|
150 |
|
---|
151 | void fastFree(void* p)
|
---|
152 | {
|
---|
153 | ASSERT(!isForbidden());
|
---|
154 | free(p);
|
---|
155 | }
|
---|
156 |
|
---|
157 | void *fastRealloc(void* p, size_t n)
|
---|
158 | {
|
---|
159 | ASSERT(!isForbidden());
|
---|
160 | return realloc(p, n);
|
---|
161 | }
|
---|
162 |
|
---|
163 | } // namespace WTF
|
---|
164 |
|
---|
165 | #if PLATFORM(DARWIN)
|
---|
166 | // This symbol is present in the JavaScriptCore exports file even when FastMalloc is disabled.
|
---|
167 | // It will never be used in this case, so it's type and value are less interesting than its presence.
|
---|
168 | extern "C" const int jscore_fastmalloc_introspection = 0;
|
---|
169 | #endif
|
---|
170 |
|
---|
171 | #else
|
---|
172 |
|
---|
173 | #if HAVE(STDINT_H)
|
---|
174 | #include <stdint.h>
|
---|
175 | #elif HAVE(INTTYPES_H)
|
---|
176 | #include <inttypes.h>
|
---|
177 | #else
|
---|
178 | #include <sys/types.h>
|
---|
179 | #endif
|
---|
180 |
|
---|
181 | #include "AlwaysInline.h"
|
---|
182 | #include "Assertions.h"
|
---|
183 | #include "TCPageMap.h"
|
---|
184 | #include "TCSpinLock.h"
|
---|
185 | #include "TCSystemAlloc.h"
|
---|
186 | #include <errno.h>
|
---|
187 | #include <new>
|
---|
188 | #include <pthread.h>
|
---|
189 | #include <stdarg.h>
|
---|
190 | #include <stddef.h>
|
---|
191 | #include <stdio.h>
|
---|
192 | #include <string.h>
|
---|
193 | #if COMPILER(MSVC)
|
---|
194 | #define WIN32_LEAN_AND_MEAN
|
---|
195 | #include <windows.h>
|
---|
196 | #endif
|
---|
197 |
|
---|
198 | #if WTF_CHANGES
|
---|
199 |
|
---|
200 | #if PLATFORM(DARWIN)
|
---|
201 | #include "MallocZoneSupport.h"
|
---|
202 | #endif
|
---|
203 |
|
---|
204 | // Calling pthread_getspecific through a global function pointer is faster than a normal
|
---|
205 | // call to the function on Mac OS X, and it's used in performance-critical code. So we
|
---|
206 | // use a function pointer. But that's not necessarily faster on other platforms, and we had
|
---|
207 | // problems with this technique on Windows, so we'll do this only on Mac OS X.
|
---|
208 | #if PLATFORM(DARWIN)
|
---|
209 | static void* (*pthread_getspecific_function_pointer)(pthread_key_t) = pthread_getspecific;
|
---|
210 | #define pthread_getspecific(key) pthread_getspecific_function_pointer(key)
|
---|
211 | #endif
|
---|
212 |
|
---|
213 | namespace WTF {
|
---|
214 |
|
---|
215 | #define malloc fastMalloc
|
---|
216 | #define calloc fastCalloc
|
---|
217 | #define free fastFree
|
---|
218 | #define realloc fastRealloc
|
---|
219 |
|
---|
220 | #define MESSAGE LOG_ERROR
|
---|
221 | #define CHECK_CONDITION ASSERT
|
---|
222 |
|
---|
223 | #if PLATFORM(DARWIN)
|
---|
224 | class TCMalloc_PageHeap;
|
---|
225 | class TCMalloc_ThreadCache;
|
---|
226 | class TCMalloc_Central_FreeListPadded;
|
---|
227 |
|
---|
228 | class FastMallocZone {
|
---|
229 | public:
|
---|
230 | static void init();
|
---|
231 |
|
---|
232 | static kern_return_t enumerate(task_t, void*, unsigned typeMmask, vm_address_t zoneAddress, memory_reader_t, vm_range_recorder_t);
|
---|
233 | static size_t goodSize(malloc_zone_t*, size_t size) { return size; }
|
---|
234 | static boolean_t check(malloc_zone_t*) { return true; }
|
---|
235 | static void print(malloc_zone_t*, boolean_t) { }
|
---|
236 | static void log(malloc_zone_t*, void*) { }
|
---|
237 | static void forceLock(malloc_zone_t*) { }
|
---|
238 | static void forceUnlock(malloc_zone_t*) { }
|
---|
239 | static void statistics(malloc_zone_t*, malloc_statistics_t*) { }
|
---|
240 |
|
---|
241 | private:
|
---|
242 | FastMallocZone(TCMalloc_PageHeap*, TCMalloc_ThreadCache**, TCMalloc_Central_FreeListPadded*);
|
---|
243 | static size_t size(malloc_zone_t*, const void*);
|
---|
244 | static void* zoneMalloc(malloc_zone_t*, size_t);
|
---|
245 | static void* zoneCalloc(malloc_zone_t*, size_t numItems, size_t size);
|
---|
246 | static void zoneFree(malloc_zone_t*, void*);
|
---|
247 | static void* zoneRealloc(malloc_zone_t*, void*, size_t);
|
---|
248 | static void* zoneValloc(malloc_zone_t*, size_t) { LOG_ERROR("valloc is not supported"); return 0; }
|
---|
249 | static void zoneDestroy(malloc_zone_t*) { }
|
---|
250 |
|
---|
251 | malloc_zone_t m_zone;
|
---|
252 | TCMalloc_PageHeap* m_pageHeap;
|
---|
253 | TCMalloc_ThreadCache** m_threadHeaps;
|
---|
254 | TCMalloc_Central_FreeListPadded* m_centralCaches;
|
---|
255 | };
|
---|
256 |
|
---|
257 | #endif
|
---|
258 |
|
---|
259 | #endif
|
---|
260 |
|
---|
261 | #if HAVE(INTTYPES_H)
|
---|
262 | #define __STDC_FORMAT_MACROS
|
---|
263 | #include <inttypes.h>
|
---|
264 | #define LLU PRIu64
|
---|
265 | #else
|
---|
266 | #define LLU "llu" // hope for the best
|
---|
267 | #endif
|
---|
268 |
|
---|
269 | //-------------------------------------------------------------------
|
---|
270 | // Configuration
|
---|
271 | //-------------------------------------------------------------------
|
---|
272 |
|
---|
273 | // Not all possible combinations of the following parameters make
|
---|
274 | // sense. In particular, if kMaxSize increases, you may have to
|
---|
275 | // increase kNumClasses as well.
|
---|
276 | static const size_t kPageShift = 12;
|
---|
277 | static const size_t kPageSize = 1 << kPageShift;
|
---|
278 | static const size_t kMaxSize = 8u * kPageSize;
|
---|
279 | static const size_t kAlignShift = 3;
|
---|
280 | static const size_t kAlignment = 1 << kAlignShift;
|
---|
281 | static const size_t kNumClasses = 170;
|
---|
282 | static const size_t kMaxTinySize = 1 << 8;
|
---|
283 |
|
---|
284 | // Minimum number of pages to fetch from system at a time. Must be
|
---|
285 | // significantly bigger than kBlockSize to amortize system-call
|
---|
286 | // overhead, and also to reduce external fragementation. Also, we
|
---|
287 | // should keep this value big because various incarnations of Linux
|
---|
288 | // have small limits on the number of mmap() regions per
|
---|
289 | // address-space.
|
---|
290 | static const size_t kMinSystemAlloc = 1 << (20 - kPageShift);
|
---|
291 |
|
---|
292 | // Number of objects to move between a per-thread list and a central
|
---|
293 | // list in one shot. We want this to be not too small so we can
|
---|
294 | // amortize the lock overhead for accessing the central list. Making
|
---|
295 | // it too big may temporarily cause unnecessary memory wastage in the
|
---|
296 | // per-thread free list until the scavenger cleans up the list.
|
---|
297 | static const int kNumObjectsToMove = 32;
|
---|
298 |
|
---|
299 | // Maximum length we allow a per-thread free-list to have before we
|
---|
300 | // move objects from it into the corresponding central free-list. We
|
---|
301 | // want this big to avoid locking the central free-list too often. It
|
---|
302 | // should not hurt to make this list somewhat big because the
|
---|
303 | // scavenging code will shrink it down when its contents are not in use.
|
---|
304 | static const int kMaxFreeListLength = 256;
|
---|
305 |
|
---|
306 | // Lower and upper bounds on the per-thread cache sizes
|
---|
307 | static const size_t kMinThreadCacheSize = kMaxSize * 2;
|
---|
308 | static const size_t kMaxThreadCacheSize = 2 << 20;
|
---|
309 |
|
---|
310 | // Default bound on the total amount of thread caches
|
---|
311 | static const size_t kDefaultOverallThreadCacheSize = 16 << 20;
|
---|
312 |
|
---|
313 | // For all span-lengths < kMaxPages we keep an exact-size list.
|
---|
314 | // REQUIRED: kMaxPages >= kMinSystemAlloc;
|
---|
315 | static const size_t kMaxPages = kMinSystemAlloc;
|
---|
316 |
|
---|
317 | // Twice the approximate gap between sampling actions.
|
---|
318 | // I.e., we take one sample approximately once every
|
---|
319 | // kSampleParameter/2
|
---|
320 | // bytes of allocation, i.e., ~ once every 128KB.
|
---|
321 | // Must be a prime number.
|
---|
322 | static const size_t kSampleParameter = 266053;
|
---|
323 |
|
---|
324 | //-------------------------------------------------------------------
|
---|
325 | // Mapping from size to size_class and vice versa
|
---|
326 | //-------------------------------------------------------------------
|
---|
327 |
|
---|
328 | // A pair of arrays we use for implementing the mapping from a size to
|
---|
329 | // its size class. Indexed by "floor(lg(size))".
|
---|
330 | static const int kSizeBits = 8 * sizeof(size_t);
|
---|
331 | static unsigned char size_base[kSizeBits];
|
---|
332 | static unsigned char size_shift[kSizeBits];
|
---|
333 |
|
---|
334 | // Mapping from size class to size
|
---|
335 | static size_t class_to_size[kNumClasses];
|
---|
336 |
|
---|
337 | // Mapping from size class to number of pages to allocate at a time
|
---|
338 | static size_t class_to_pages[kNumClasses];
|
---|
339 |
|
---|
340 | // Return floor(log2(n)) for n > 0.
|
---|
341 | #if PLATFORM(X86) && COMPILER(GCC)
|
---|
342 | static ALWAYS_INLINE int LgFloor(size_t n) {
|
---|
343 | // "ro" for the input spec means the input can come from either a
|
---|
344 | // register ("r") or offsetable memory ("o").
|
---|
345 | int result;
|
---|
346 | __asm__("bsrl %1, %0"
|
---|
347 | : "=r" (result) // Output spec
|
---|
348 | : "ro" (n) // Input spec
|
---|
349 | : "cc" // Clobbers condition-codes
|
---|
350 | );
|
---|
351 | return result;
|
---|
352 | }
|
---|
353 |
|
---|
354 | #elif PLATFORM(PPC) && COMPILER(GCC)
|
---|
355 | static ALWAYS_INLINE int LgFloor(size_t n) {
|
---|
356 | // "r" for the input spec means the input must come from a
|
---|
357 | // register ("r")
|
---|
358 | int result;
|
---|
359 |
|
---|
360 | __asm__ ("{cntlz|cntlzw} %0,%1"
|
---|
361 | : "=r" (result) // Output spec
|
---|
362 | : "r" (n)); // Input spec
|
---|
363 |
|
---|
364 | return 31 - result;
|
---|
365 | }
|
---|
366 |
|
---|
367 | #else
|
---|
368 | // Note: the following only works for "n"s that fit in 32-bits, but
|
---|
369 | // that is fine since we only use it for small sizes.
|
---|
370 | static inline int LgFloor(size_t n) {
|
---|
371 | int log = 0;
|
---|
372 | for (int i = 4; i >= 0; --i) {
|
---|
373 | int shift = (1 << i);
|
---|
374 | size_t x = n >> shift;
|
---|
375 | if (x != 0) {
|
---|
376 | n = x;
|
---|
377 | log += shift;
|
---|
378 | }
|
---|
379 | }
|
---|
380 | ASSERT(n == 1);
|
---|
381 | return log;
|
---|
382 | }
|
---|
383 | #endif
|
---|
384 |
|
---|
385 | static ALWAYS_INLINE size_t SizeClass(size_t size) {
|
---|
386 | size += !size; // change 0 to 1 (with no branches)
|
---|
387 | const int lg = LgFloor(size);
|
---|
388 | const int align = size_shift[lg];
|
---|
389 | return size_base[lg] + ((size-1) >> align);
|
---|
390 | }
|
---|
391 |
|
---|
392 | // Get the byte-size for a specified class
|
---|
393 | static ALWAYS_INLINE size_t ByteSizeForClass(size_t cl) {
|
---|
394 | return class_to_size[cl];
|
---|
395 | }
|
---|
396 |
|
---|
397 | // Initialize the mapping arrays
|
---|
398 | static void InitSizeClasses() {
|
---|
399 | // Special initialization for small sizes
|
---|
400 | for (size_t lg = 0; lg < kAlignShift; lg++) {
|
---|
401 | size_base[lg] = 1;
|
---|
402 | size_shift[lg] = kAlignShift;
|
---|
403 | }
|
---|
404 |
|
---|
405 | size_t next_class = 1;
|
---|
406 | unsigned char alignshift = kAlignShift;
|
---|
407 | int last_lg = -1;
|
---|
408 | for (size_t size = kAlignment; size <= kMaxSize; size += (1 << alignshift)) {
|
---|
409 | int lg = LgFloor(size);
|
---|
410 | if (lg > last_lg) {
|
---|
411 | // Increase alignment every so often.
|
---|
412 | //
|
---|
413 | // Since we double the alignment every time size doubles and
|
---|
414 | // size >= 256, this means that space wasted due to alignment is
|
---|
415 | // at most 16/256 i.e., 6.25%. Plus we cap the alignment at 512
|
---|
416 | // bytes, so the space wasted as a percentage starts falling for
|
---|
417 | // sizes > 4K.
|
---|
418 | if ((lg >= 8) && (alignshift < 9)) {
|
---|
419 | alignshift++;
|
---|
420 | }
|
---|
421 | size_base[lg] = static_cast<unsigned char>(next_class - ((size-1) >> alignshift));
|
---|
422 | size_shift[lg] = alignshift;
|
---|
423 | }
|
---|
424 |
|
---|
425 | class_to_size[next_class] = size;
|
---|
426 | last_lg = lg;
|
---|
427 |
|
---|
428 | next_class++;
|
---|
429 | }
|
---|
430 | if (next_class >= kNumClasses) {
|
---|
431 | MESSAGE("used up too many size classes: %d\n", next_class);
|
---|
432 | abort();
|
---|
433 | }
|
---|
434 |
|
---|
435 | // Initialize the number of pages we should allocate to split into
|
---|
436 | // small objects for a given class.
|
---|
437 | for (size_t cl = 1; cl < next_class; cl++) {
|
---|
438 | // Allocate enough pages so leftover is less than 1/16 of total.
|
---|
439 | // This bounds wasted space to at most 6.25%.
|
---|
440 | size_t psize = kPageSize;
|
---|
441 | const size_t s = class_to_size[cl];
|
---|
442 | while ((psize % s) > (psize >> 4)) {
|
---|
443 | psize += kPageSize;
|
---|
444 | }
|
---|
445 | class_to_pages[cl] = psize >> kPageShift;
|
---|
446 | }
|
---|
447 |
|
---|
448 | // Double-check sizes just to be safe
|
---|
449 | for (size_t size = 0; size <= kMaxSize; size++) {
|
---|
450 | const size_t sc = SizeClass(size);
|
---|
451 | if (sc == 0) {
|
---|
452 | MESSAGE("Bad size class %d for %" PRIuS "\n", sc, size);
|
---|
453 | abort();
|
---|
454 | }
|
---|
455 | if (sc > 1 && size <= class_to_size[sc-1]) {
|
---|
456 | MESSAGE("Allocating unnecessarily large class %d for %" PRIuS
|
---|
457 | "\n", sc, size);
|
---|
458 | abort();
|
---|
459 | }
|
---|
460 | if (sc >= kNumClasses) {
|
---|
461 | MESSAGE("Bad size class %d for %" PRIuS "\n", sc, size);
|
---|
462 | abort();
|
---|
463 | }
|
---|
464 | const size_t s = class_to_size[sc];
|
---|
465 | if (size > s) {
|
---|
466 | MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %d)\n", s, size, sc);
|
---|
467 | abort();
|
---|
468 | }
|
---|
469 | if (s == 0) {
|
---|
470 | MESSAGE("Bad size %" PRIuS " for %" PRIuS " (sc = %d)\n", s, size, sc);
|
---|
471 | abort();
|
---|
472 | }
|
---|
473 | }
|
---|
474 | }
|
---|
475 |
|
---|
476 | // -------------------------------------------------------------------------
|
---|
477 | // Simple allocator for objects of a specified type. External locking
|
---|
478 | // is required before accessing one of these objects.
|
---|
479 | // -------------------------------------------------------------------------
|
---|
480 |
|
---|
481 | // Metadata allocator -- keeps stats about how many bytes allocated
|
---|
482 | static uint64_t metadata_system_bytes = 0;
|
---|
483 | static void* MetaDataAlloc(size_t bytes) {
|
---|
484 | void* result = TCMalloc_SystemAlloc(bytes);
|
---|
485 | if (result != NULL) {
|
---|
486 | metadata_system_bytes += bytes;
|
---|
487 | }
|
---|
488 | return result;
|
---|
489 | }
|
---|
490 |
|
---|
491 | template <class T>
|
---|
492 | class PageHeapAllocator {
|
---|
493 | private:
|
---|
494 | // How much to allocate from system at a time
|
---|
495 | static const size_t kAllocIncrement = 32 << 10;
|
---|
496 |
|
---|
497 | // Aligned size of T
|
---|
498 | static const size_t kAlignedSize
|
---|
499 | = (((sizeof(T) + kAlignment - 1) / kAlignment) * kAlignment);
|
---|
500 |
|
---|
501 | // Free area from which to carve new objects
|
---|
502 | char* free_area_;
|
---|
503 | size_t free_avail_;
|
---|
504 |
|
---|
505 | // Free list of already carved objects
|
---|
506 | void* free_list_;
|
---|
507 |
|
---|
508 | // Number of allocated but unfreed objects
|
---|
509 | int inuse_;
|
---|
510 |
|
---|
511 | public:
|
---|
512 | void Init() {
|
---|
513 | ASSERT(kAlignedSize <= kAllocIncrement);
|
---|
514 | inuse_ = 0;
|
---|
515 | free_area_ = NULL;
|
---|
516 | free_avail_ = 0;
|
---|
517 | free_list_ = NULL;
|
---|
518 | }
|
---|
519 |
|
---|
520 | T* New() {
|
---|
521 | // Consult free list
|
---|
522 | void* result;
|
---|
523 | if (free_list_ != NULL) {
|
---|
524 | result = free_list_;
|
---|
525 | free_list_ = *(reinterpret_cast<void**>(result));
|
---|
526 | } else {
|
---|
527 | if (free_avail_ < kAlignedSize) {
|
---|
528 | // Need more room
|
---|
529 | free_area_ = reinterpret_cast<char*>(MetaDataAlloc(kAllocIncrement));
|
---|
530 | if (free_area_ == NULL) abort();
|
---|
531 | free_avail_ = kAllocIncrement;
|
---|
532 | }
|
---|
533 | result = free_area_;
|
---|
534 | free_area_ += kAlignedSize;
|
---|
535 | free_avail_ -= kAlignedSize;
|
---|
536 | }
|
---|
537 | inuse_++;
|
---|
538 | return reinterpret_cast<T*>(result);
|
---|
539 | }
|
---|
540 |
|
---|
541 | void Delete(T* p) {
|
---|
542 | *(reinterpret_cast<void**>(p)) = free_list_;
|
---|
543 | free_list_ = p;
|
---|
544 | inuse_--;
|
---|
545 | }
|
---|
546 |
|
---|
547 | int inuse() const { return inuse_; }
|
---|
548 | };
|
---|
549 |
|
---|
550 | // -------------------------------------------------------------------------
|
---|
551 | // Span - a contiguous run of pages
|
---|
552 | // -------------------------------------------------------------------------
|
---|
553 |
|
---|
554 | // Type that can hold a page number
|
---|
555 | typedef uintptr_t PageID;
|
---|
556 |
|
---|
557 | // Type that can hold the length of a run of pages
|
---|
558 | typedef uintptr_t Length;
|
---|
559 |
|
---|
560 | // Convert byte size into pages
|
---|
561 | static inline Length pages(size_t bytes) {
|
---|
562 | return ((bytes + kPageSize - 1) >> kPageShift);
|
---|
563 | }
|
---|
564 |
|
---|
565 | // Convert a user size into the number of bytes that will actually be
|
---|
566 | // allocated
|
---|
567 | static size_t AllocationSize(size_t bytes) {
|
---|
568 | if (bytes > kMaxSize) {
|
---|
569 | // Large object: we allocate an integral number of pages
|
---|
570 | return pages(bytes) << kPageShift;
|
---|
571 | } else {
|
---|
572 | // Small object: find the size class to which it belongs
|
---|
573 | return ByteSizeForClass(SizeClass(bytes));
|
---|
574 | }
|
---|
575 | }
|
---|
576 |
|
---|
577 | // Information kept for a span (a contiguous run of pages).
|
---|
578 | struct Span {
|
---|
579 | PageID start; // Starting page number
|
---|
580 | Length length; // Number of pages in span
|
---|
581 | Span* next; // Used when in link list
|
---|
582 | Span* prev; // Used when in link list
|
---|
583 | void* objects; // Linked list of free objects
|
---|
584 | unsigned int free : 1; // Is the span free
|
---|
585 | unsigned int sample : 1; // Sampled object?
|
---|
586 | unsigned int sizeclass : 8; // Size-class for small objects (or 0)
|
---|
587 | unsigned int refcount : 11; // Number of non-free objects
|
---|
588 |
|
---|
589 | #undef SPAN_HISTORY
|
---|
590 | #ifdef SPAN_HISTORY
|
---|
591 | // For debugging, we can keep a log events per span
|
---|
592 | int nexthistory;
|
---|
593 | char history[64];
|
---|
594 | int value[64];
|
---|
595 | #endif
|
---|
596 | };
|
---|
597 |
|
---|
598 | #ifdef SPAN_HISTORY
|
---|
599 | void Event(Span* span, char op, int v = 0) {
|
---|
600 | span->history[span->nexthistory] = op;
|
---|
601 | span->value[span->nexthistory] = v;
|
---|
602 | span->nexthistory++;
|
---|
603 | if (span->nexthistory == sizeof(span->history)) span->nexthistory = 0;
|
---|
604 | }
|
---|
605 | #else
|
---|
606 | #define Event(s,o,v) ((void) 0)
|
---|
607 | #endif
|
---|
608 |
|
---|
609 | // Allocator/deallocator for spans
|
---|
610 | static PageHeapAllocator<Span> span_allocator;
|
---|
611 | static Span* NewSpan(PageID p, Length len) {
|
---|
612 | Span* result = span_allocator.New();
|
---|
613 | memset(result, 0, sizeof(*result));
|
---|
614 | result->start = p;
|
---|
615 | result->length = len;
|
---|
616 | #ifdef SPAN_HISTORY
|
---|
617 | result->nexthistory = 0;
|
---|
618 | #endif
|
---|
619 | return result;
|
---|
620 | }
|
---|
621 |
|
---|
622 | static inline void DeleteSpan(Span* span) {
|
---|
623 | #ifndef NDEBUG
|
---|
624 | // In debug mode, trash the contents of deleted Spans
|
---|
625 | memset(span, 0x3f, sizeof(*span));
|
---|
626 | #endif
|
---|
627 | span_allocator.Delete(span);
|
---|
628 | }
|
---|
629 |
|
---|
630 | // -------------------------------------------------------------------------
|
---|
631 | // Doubly linked list of spans.
|
---|
632 | // -------------------------------------------------------------------------
|
---|
633 |
|
---|
634 | static inline void DLL_Init(Span* list) {
|
---|
635 | list->next = list;
|
---|
636 | list->prev = list;
|
---|
637 | }
|
---|
638 |
|
---|
639 | static inline void DLL_Remove(Span* span) {
|
---|
640 | span->prev->next = span->next;
|
---|
641 | span->next->prev = span->prev;
|
---|
642 | span->prev = NULL;
|
---|
643 | span->next = NULL;
|
---|
644 | }
|
---|
645 |
|
---|
646 | static ALWAYS_INLINE bool DLL_IsEmpty(const Span* list) {
|
---|
647 | return list->next == list;
|
---|
648 | }
|
---|
649 |
|
---|
650 | #ifndef WTF_CHANGES
|
---|
651 | static int DLL_Length(const Span* list) {
|
---|
652 | int result = 0;
|
---|
653 | for (Span* s = list->next; s != list; s = s->next) {
|
---|
654 | result++;
|
---|
655 | }
|
---|
656 | return result;
|
---|
657 | }
|
---|
658 | #endif
|
---|
659 |
|
---|
660 | #if 0 /* Not needed at the moment -- causes compiler warnings if not used */
|
---|
661 | static void DLL_Print(const char* label, const Span* list) {
|
---|
662 | MESSAGE("%-10s %p:", label, list);
|
---|
663 | for (const Span* s = list->next; s != list; s = s->next) {
|
---|
664 | MESSAGE(" <%p,%u,%u>", s, s->start, s->length);
|
---|
665 | }
|
---|
666 | MESSAGE("\n");
|
---|
667 | }
|
---|
668 | #endif
|
---|
669 |
|
---|
670 | static inline void DLL_Prepend(Span* list, Span* span) {
|
---|
671 | ASSERT(span->next == NULL);
|
---|
672 | ASSERT(span->prev == NULL);
|
---|
673 | span->next = list->next;
|
---|
674 | span->prev = list;
|
---|
675 | list->next->prev = span;
|
---|
676 | list->next = span;
|
---|
677 | }
|
---|
678 |
|
---|
679 | static void DLL_InsertOrdered(Span* list, Span* span) {
|
---|
680 | ASSERT(span->next == NULL);
|
---|
681 | ASSERT(span->prev == NULL);
|
---|
682 | // Look for appropriate place to insert
|
---|
683 | Span* x = list;
|
---|
684 | while ((x->next != list) && (x->next->start < span->start)) {
|
---|
685 | x = x->next;
|
---|
686 | }
|
---|
687 | span->next = x->next;
|
---|
688 | span->prev = x;
|
---|
689 | x->next->prev = span;
|
---|
690 | x->next = span;
|
---|
691 | }
|
---|
692 |
|
---|
693 | // -------------------------------------------------------------------------
|
---|
694 | // Stack traces kept for sampled allocations
|
---|
695 | // The following state is protected by pageheap_lock_.
|
---|
696 | // -------------------------------------------------------------------------
|
---|
697 |
|
---|
698 | static const int kMaxStackDepth = 31;
|
---|
699 | struct StackTrace {
|
---|
700 | uintptr_t size; // Size of object
|
---|
701 | int depth; // Number of PC values stored in array below
|
---|
702 | void* stack[kMaxStackDepth];
|
---|
703 | };
|
---|
704 | static PageHeapAllocator<StackTrace> stacktrace_allocator;
|
---|
705 | static Span sampled_objects;
|
---|
706 |
|
---|
707 | // -------------------------------------------------------------------------
|
---|
708 | // Map from page-id to per-page data
|
---|
709 | // -------------------------------------------------------------------------
|
---|
710 |
|
---|
711 | // We use PageMap2<> for 32-bit and PageMap3<> for 64-bit machines.
|
---|
712 |
|
---|
713 | // Selector class -- general selector uses 3-level map
|
---|
714 | template <int BITS> class MapSelector {
|
---|
715 | public:
|
---|
716 | typedef TCMalloc_PageMap3<BITS-kPageShift> Type;
|
---|
717 | };
|
---|
718 |
|
---|
719 | // A two-level map for 32-bit machines
|
---|
720 | template <> class MapSelector<32> {
|
---|
721 | public:
|
---|
722 | typedef TCMalloc_PageMap2<32-kPageShift> Type;
|
---|
723 | };
|
---|
724 |
|
---|
725 | // -------------------------------------------------------------------------
|
---|
726 | // Page-level allocator
|
---|
727 | // * Eager coalescing
|
---|
728 | //
|
---|
729 | // Heap for page-level allocation. We allow allocating and freeing a
|
---|
730 | // contiguous runs of pages (called a "span").
|
---|
731 | // -------------------------------------------------------------------------
|
---|
732 |
|
---|
733 | class TCMalloc_PageHeap {
|
---|
734 | public:
|
---|
735 | void init();
|
---|
736 |
|
---|
737 | // Allocate a run of "n" pages. Returns zero if out of memory.
|
---|
738 | Span* New(Length n);
|
---|
739 |
|
---|
740 | // Delete the span "[p, p+n-1]".
|
---|
741 | // REQUIRES: span was returned by earlier call to New() and
|
---|
742 | // has not yet been deleted.
|
---|
743 | void Delete(Span* span);
|
---|
744 |
|
---|
745 | // Mark an allocated span as being used for small objects of the
|
---|
746 | // specified size-class.
|
---|
747 | // REQUIRES: span was returned by an earlier call to New()
|
---|
748 | // and has not yet been deleted.
|
---|
749 | void RegisterSizeClass(Span* span, size_t sc);
|
---|
750 |
|
---|
751 | // Split an allocated span into two spans: one of length "n" pages
|
---|
752 | // followed by another span of length "span->length - n" pages.
|
---|
753 | // Modifies "*span" to point to the first span of length "n" pages.
|
---|
754 | // Returns a pointer to the second span.
|
---|
755 | //
|
---|
756 | // REQUIRES: "0 < n < span->length"
|
---|
757 | // REQUIRES: !span->free
|
---|
758 | // REQUIRES: span->sizeclass == 0
|
---|
759 | Span* Split(Span* span, Length n);
|
---|
760 |
|
---|
761 | // Return the descriptor for the specified page.
|
---|
762 | inline Span* GetDescriptor(PageID p) const {
|
---|
763 | return reinterpret_cast<Span*>(pagemap_.get(p));
|
---|
764 | }
|
---|
765 |
|
---|
766 | #ifdef WTF_CHANGES
|
---|
767 | inline Span* GetDescriptorEnsureSafe(PageID p)
|
---|
768 | {
|
---|
769 | pagemap_.Ensure(p, 1);
|
---|
770 | return GetDescriptor(p);
|
---|
771 | }
|
---|
772 | #endif
|
---|
773 |
|
---|
774 | // Dump state to stderr
|
---|
775 | #ifndef WTF_CHANGES
|
---|
776 | void Dump(TCMalloc_Printer* out);
|
---|
777 | #endif
|
---|
778 |
|
---|
779 | // Return number of bytes allocated from system
|
---|
780 | inline uint64_t SystemBytes() const { return system_bytes_; }
|
---|
781 |
|
---|
782 | // Return number of free bytes in heap
|
---|
783 | uint64_t FreeBytes() const {
|
---|
784 | return (static_cast<uint64_t>(free_pages_) << kPageShift);
|
---|
785 | }
|
---|
786 |
|
---|
787 | bool Check();
|
---|
788 | bool CheckList(Span* list, Length min_pages, Length max_pages);
|
---|
789 |
|
---|
790 | private:
|
---|
791 | // Pick the appropriate map type based on pointer size
|
---|
792 | typedef MapSelector<8*sizeof(uintptr_t)>::Type PageMap;
|
---|
793 | PageMap pagemap_;
|
---|
794 |
|
---|
795 | // List of free spans of length >= kMaxPages
|
---|
796 | Span large_;
|
---|
797 |
|
---|
798 | // Array mapping from span length to a doubly linked list of free spans
|
---|
799 | Span free_[kMaxPages];
|
---|
800 |
|
---|
801 | // Number of pages kept in free lists
|
---|
802 | uintptr_t free_pages_;
|
---|
803 |
|
---|
804 | // Bytes allocated from system
|
---|
805 | uint64_t system_bytes_;
|
---|
806 |
|
---|
807 | bool GrowHeap(Length n);
|
---|
808 |
|
---|
809 | // REQUIRES span->length >= n
|
---|
810 | // Remove span from its free list, and move any leftover part of
|
---|
811 | // span into appropriate free lists. Also update "span" to have
|
---|
812 | // length exactly "n" and mark it as non-free so it can be returned
|
---|
813 | // to the client.
|
---|
814 | void Carve(Span* span, Length n);
|
---|
815 |
|
---|
816 | void RecordSpan(Span* span) {
|
---|
817 | pagemap_.set(span->start, span);
|
---|
818 | if (span->length > 1) {
|
---|
819 | pagemap_.set(span->start + span->length - 1, span);
|
---|
820 | }
|
---|
821 | }
|
---|
822 | #if defined(WTF_CHANGES) && PLATFORM(DARWIN)
|
---|
823 | friend class FastMallocZone;
|
---|
824 | #endif
|
---|
825 | };
|
---|
826 |
|
---|
827 | void TCMalloc_PageHeap::init()
|
---|
828 | {
|
---|
829 | pagemap_.init(MetaDataAlloc);
|
---|
830 | free_pages_ = 0;
|
---|
831 | system_bytes_ = 0;
|
---|
832 |
|
---|
833 | DLL_Init(&large_);
|
---|
834 | for (size_t i = 0; i < kMaxPages; i++) {
|
---|
835 | DLL_Init(&free_[i]);
|
---|
836 | }
|
---|
837 | }
|
---|
838 |
|
---|
839 | inline Span* TCMalloc_PageHeap::New(Length n) {
|
---|
840 | ASSERT(Check());
|
---|
841 | if (n == 0) n = 1;
|
---|
842 |
|
---|
843 | // Find first size >= n that has a non-empty list
|
---|
844 | for (size_t s = n; s < kMaxPages; s++) {
|
---|
845 | if (!DLL_IsEmpty(&free_[s])) {
|
---|
846 | Span* result = free_[s].next;
|
---|
847 | Carve(result, n);
|
---|
848 | ASSERT(Check());
|
---|
849 | free_pages_ -= n;
|
---|
850 | return result;
|
---|
851 | }
|
---|
852 | }
|
---|
853 |
|
---|
854 | // Look in large list. If we first do not find something, we try to
|
---|
855 | // grow the heap and try again.
|
---|
856 | for (int i = 0; i < 2; i++) {
|
---|
857 | // find the best span (closest to n in size)
|
---|
858 | Span *best = NULL;
|
---|
859 | for (Span* span = large_.next; span != &large_; span = span->next) {
|
---|
860 | if (span->length >= n &&
|
---|
861 | (best == NULL || span->length < best->length)) {
|
---|
862 | best = span;
|
---|
863 | }
|
---|
864 | }
|
---|
865 | if (best != NULL) {
|
---|
866 | Carve(best, n);
|
---|
867 | ASSERT(Check());
|
---|
868 | free_pages_ -= n;
|
---|
869 | return best;
|
---|
870 | }
|
---|
871 | if (i == 0) {
|
---|
872 | // Nothing suitable in large list. Grow the heap and look again.
|
---|
873 | if (!GrowHeap(n)) {
|
---|
874 | ASSERT(Check());
|
---|
875 | return NULL;
|
---|
876 | }
|
---|
877 | }
|
---|
878 | }
|
---|
879 | return NULL;
|
---|
880 | }
|
---|
881 |
|
---|
882 | Span* TCMalloc_PageHeap::Split(Span* span, Length n) {
|
---|
883 | ASSERT(0 < n);
|
---|
884 | ASSERT(n < span->length);
|
---|
885 | ASSERT(!span->free);
|
---|
886 | ASSERT(span->sizeclass == 0);
|
---|
887 | Event(span, 'T', n);
|
---|
888 |
|
---|
889 | const Length extra = span->length - n;
|
---|
890 | Span* leftover = NewSpan(span->start + n, extra);
|
---|
891 | Event(leftover, 'U', extra);
|
---|
892 | RecordSpan(leftover);
|
---|
893 | pagemap_.set(span->start + n - 1, span); // Update map from pageid to span
|
---|
894 | span->length = n;
|
---|
895 |
|
---|
896 | return leftover;
|
---|
897 | }
|
---|
898 |
|
---|
899 | inline void TCMalloc_PageHeap::Carve(Span* span, Length n) {
|
---|
900 | ASSERT(n > 0);
|
---|
901 | DLL_Remove(span);
|
---|
902 | span->free = 0;
|
---|
903 | Event(span, 'A', n);
|
---|
904 |
|
---|
905 | const size_t extra = span->length - n;
|
---|
906 | ASSERT(extra >= 0);
|
---|
907 | if (extra > 0) {
|
---|
908 | Span* leftover = NewSpan(span->start + n, extra);
|
---|
909 | leftover->free = 1;
|
---|
910 | Event(leftover, 'S', extra);
|
---|
911 | RecordSpan(leftover);
|
---|
912 | if (extra < kMaxPages) {
|
---|
913 | DLL_Prepend(&free_[extra], leftover);
|
---|
914 | } else {
|
---|
915 | DLL_InsertOrdered(&large_, leftover);
|
---|
916 | }
|
---|
917 | span->length = n;
|
---|
918 | pagemap_.set(span->start + n - 1, span);
|
---|
919 | }
|
---|
920 | }
|
---|
921 |
|
---|
922 | inline void TCMalloc_PageHeap::Delete(Span* span) {
|
---|
923 | ASSERT(Check());
|
---|
924 | ASSERT(!span->free);
|
---|
925 | ASSERT(span->length > 0);
|
---|
926 | ASSERT(GetDescriptor(span->start) == span);
|
---|
927 | ASSERT(GetDescriptor(span->start + span->length - 1) == span);
|
---|
928 | span->sizeclass = 0;
|
---|
929 | span->sample = 0;
|
---|
930 |
|
---|
931 | // Coalesce -- we guarantee that "p" != 0, so no bounds checking
|
---|
932 | // necessary. We do not bother resetting the stale pagemap
|
---|
933 | // entries for the pieces we are merging together because we only
|
---|
934 | // care about the pagemap entries for the boundaries.
|
---|
935 | const PageID p = span->start;
|
---|
936 | const Length n = span->length;
|
---|
937 | Span* prev = GetDescriptor(p-1);
|
---|
938 | if (prev != NULL && prev->free) {
|
---|
939 | // Merge preceding span into this span
|
---|
940 | ASSERT(prev->start + prev->length == p);
|
---|
941 | const Length len = prev->length;
|
---|
942 | DLL_Remove(prev);
|
---|
943 | DeleteSpan(prev);
|
---|
944 | span->start -= len;
|
---|
945 | span->length += len;
|
---|
946 | pagemap_.set(span->start, span);
|
---|
947 | Event(span, 'L', len);
|
---|
948 | }
|
---|
949 | Span* next = GetDescriptor(p+n);
|
---|
950 | if (next != NULL && next->free) {
|
---|
951 | // Merge next span into this span
|
---|
952 | ASSERT(next->start == p+n);
|
---|
953 | const Length len = next->length;
|
---|
954 | DLL_Remove(next);
|
---|
955 | DeleteSpan(next);
|
---|
956 | span->length += len;
|
---|
957 | pagemap_.set(span->start + span->length - 1, span);
|
---|
958 | Event(span, 'R', len);
|
---|
959 | }
|
---|
960 |
|
---|
961 | Event(span, 'D', span->length);
|
---|
962 | span->free = 1;
|
---|
963 | if (span->length < kMaxPages) {
|
---|
964 | DLL_Prepend(&free_[span->length], span);
|
---|
965 | } else {
|
---|
966 | DLL_InsertOrdered(&large_, span);
|
---|
967 | }
|
---|
968 | free_pages_ += n;
|
---|
969 |
|
---|
970 | ASSERT(Check());
|
---|
971 | }
|
---|
972 |
|
---|
973 | void TCMalloc_PageHeap::RegisterSizeClass(Span* span, size_t sc) {
|
---|
974 | // Associate span object with all interior pages as well
|
---|
975 | ASSERT(!span->free);
|
---|
976 | ASSERT(GetDescriptor(span->start) == span);
|
---|
977 | ASSERT(GetDescriptor(span->start+span->length-1) == span);
|
---|
978 | Event(span, 'C', sc);
|
---|
979 | span->sizeclass = static_cast<unsigned int>(sc);
|
---|
980 | for (Length i = 1; i < span->length-1; i++) {
|
---|
981 | pagemap_.set(span->start+i, span);
|
---|
982 | }
|
---|
983 | }
|
---|
984 |
|
---|
985 | #ifndef WTF_CHANGES
|
---|
986 | void TCMalloc_PageHeap::Dump(TCMalloc_Printer* out) {
|
---|
987 | int nonempty_sizes = 0;
|
---|
988 | for (int s = 0; s < kMaxPages; s++) {
|
---|
989 | if (!DLL_IsEmpty(&free_[s])) nonempty_sizes++;
|
---|
990 | }
|
---|
991 | out->printf("------------------------------------------------\n");
|
---|
992 | out->printf("PageHeap: %d sizes; %6.1f MB free\n", nonempty_sizes,
|
---|
993 | (static_cast<double>(free_pages_) * kPageSize) / 1048576.0);
|
---|
994 | out->printf("------------------------------------------------\n");
|
---|
995 | uint64_t cumulative = 0;
|
---|
996 | for (int s = 0; s < kMaxPages; s++) {
|
---|
997 | if (!DLL_IsEmpty(&free_[s])) {
|
---|
998 | const int list_length = DLL_Length(&free_[s]);
|
---|
999 | uint64_t s_pages = s * list_length;
|
---|
1000 | cumulative += s_pages;
|
---|
1001 | out->printf("%6u pages * %6u spans ~ %6.1f MB; %6.1f MB cum\n",
|
---|
1002 | s, list_length,
|
---|
1003 | (s_pages << kPageShift) / 1048576.0,
|
---|
1004 | (cumulative << kPageShift) / 1048576.0);
|
---|
1005 | }
|
---|
1006 | }
|
---|
1007 |
|
---|
1008 | uint64_t large_pages = 0;
|
---|
1009 | int large_spans = 0;
|
---|
1010 | for (Span* s = large_.next; s != &large_; s = s->next) {
|
---|
1011 | out->printf(" [ %6" PRIuS " spans ]\n", s->length);
|
---|
1012 | large_pages += s->length;
|
---|
1013 | large_spans++;
|
---|
1014 | }
|
---|
1015 | cumulative += large_pages;
|
---|
1016 | out->printf(">255 large * %6u spans ~ %6.1f MB; %6.1f MB cum\n",
|
---|
1017 | large_spans,
|
---|
1018 | (large_pages << kPageShift) / 1048576.0,
|
---|
1019 | (cumulative << kPageShift) / 1048576.0);
|
---|
1020 | }
|
---|
1021 | #endif
|
---|
1022 |
|
---|
1023 | bool TCMalloc_PageHeap::GrowHeap(Length n) {
|
---|
1024 | ASSERT(kMaxPages >= kMinSystemAlloc);
|
---|
1025 | Length ask = (n>kMinSystemAlloc) ? n : static_cast<Length>(kMinSystemAlloc);
|
---|
1026 | void* ptr = TCMalloc_SystemAlloc(ask << kPageShift, kPageSize);
|
---|
1027 | if (ptr == NULL) {
|
---|
1028 | if (n < ask) {
|
---|
1029 | // Try growing just "n" pages
|
---|
1030 | ask = n;
|
---|
1031 | ptr = TCMalloc_SystemAlloc(ask << kPageShift, kPageSize);
|
---|
1032 | }
|
---|
1033 | if (ptr == NULL) return false;
|
---|
1034 | }
|
---|
1035 | system_bytes_ += (ask << kPageShift);
|
---|
1036 | const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
|
---|
1037 | ASSERT(p > 0);
|
---|
1038 |
|
---|
1039 | // Make sure pagemap_ has entries for all of the new pages.
|
---|
1040 | // Plus ensure one before and one after so coalescing code
|
---|
1041 | // does not need bounds-checking.
|
---|
1042 | if (pagemap_.Ensure(p-1, ask+2)) {
|
---|
1043 | // Pretend the new area is allocated and then Delete() it to
|
---|
1044 | // cause any necessary coalescing to occur.
|
---|
1045 | //
|
---|
1046 | // We do not adjust free_pages_ here since Delete() will do it for us.
|
---|
1047 | Span* span = NewSpan(p, ask);
|
---|
1048 | RecordSpan(span);
|
---|
1049 | Delete(span);
|
---|
1050 | ASSERT(Check());
|
---|
1051 | return true;
|
---|
1052 | } else {
|
---|
1053 | // We could not allocate memory within "pagemap_"
|
---|
1054 | // TODO: Once we can return memory to the system, return the new span
|
---|
1055 | return false;
|
---|
1056 | }
|
---|
1057 | }
|
---|
1058 |
|
---|
1059 | bool TCMalloc_PageHeap::Check() {
|
---|
1060 | ASSERT(free_[0].next == &free_[0]);
|
---|
1061 | CheckList(&large_, kMaxPages, 1000000000);
|
---|
1062 | for (Length s = 1; s < kMaxPages; s++) {
|
---|
1063 | CheckList(&free_[s], s, s);
|
---|
1064 | }
|
---|
1065 | return true;
|
---|
1066 | }
|
---|
1067 |
|
---|
1068 | #if ASSERT_DISABLED
|
---|
1069 | bool TCMalloc_PageHeap::CheckList(Span*, Length, Length) {
|
---|
1070 | return true;
|
---|
1071 | }
|
---|
1072 | #else
|
---|
1073 | bool TCMalloc_PageHeap::CheckList(Span* list, Length min_pages, Length max_pages) {
|
---|
1074 | for (Span* s = list->next; s != list; s = s->next) {
|
---|
1075 | CHECK_CONDITION(s->free);
|
---|
1076 | CHECK_CONDITION(s->length >= min_pages);
|
---|
1077 | CHECK_CONDITION(s->length <= max_pages);
|
---|
1078 | CHECK_CONDITION(GetDescriptor(s->start) == s);
|
---|
1079 | CHECK_CONDITION(GetDescriptor(s->start+s->length-1) == s);
|
---|
1080 | }
|
---|
1081 | return true;
|
---|
1082 | }
|
---|
1083 | #endif
|
---|
1084 |
|
---|
1085 | //-------------------------------------------------------------------
|
---|
1086 | // Free list
|
---|
1087 | //-------------------------------------------------------------------
|
---|
1088 |
|
---|
1089 | class TCMalloc_ThreadCache_FreeList {
|
---|
1090 | private:
|
---|
1091 | void* list_; // Linked list of nodes
|
---|
1092 | uint16_t length_; // Current length
|
---|
1093 | uint16_t lowater_; // Low water mark for list length
|
---|
1094 |
|
---|
1095 | public:
|
---|
1096 | void Init() {
|
---|
1097 | list_ = NULL;
|
---|
1098 | length_ = 0;
|
---|
1099 | lowater_ = 0;
|
---|
1100 | }
|
---|
1101 |
|
---|
1102 | // Return current length of list
|
---|
1103 | int length() const {
|
---|
1104 | return length_;
|
---|
1105 | }
|
---|
1106 |
|
---|
1107 | // Is list empty?
|
---|
1108 | bool empty() const {
|
---|
1109 | return list_ == NULL;
|
---|
1110 | }
|
---|
1111 |
|
---|
1112 | // Low-water mark management
|
---|
1113 | int lowwatermark() const { return lowater_; }
|
---|
1114 | void clear_lowwatermark() { lowater_ = length_; }
|
---|
1115 |
|
---|
1116 | ALWAYS_INLINE void Push(void* ptr) {
|
---|
1117 | *(reinterpret_cast<void**>(ptr)) = list_;
|
---|
1118 | list_ = ptr;
|
---|
1119 | length_++;
|
---|
1120 | }
|
---|
1121 |
|
---|
1122 | ALWAYS_INLINE void* Pop() {
|
---|
1123 | ASSERT(list_ != NULL);
|
---|
1124 | void* result = list_;
|
---|
1125 | list_ = *(reinterpret_cast<void**>(result));
|
---|
1126 | length_--;
|
---|
1127 | if (length_ < lowater_) lowater_ = length_;
|
---|
1128 | return result;
|
---|
1129 | }
|
---|
1130 |
|
---|
1131 | #ifdef WTF_CHANGES
|
---|
1132 | template <class Finder, class Reader>
|
---|
1133 | void enumerateFreeObjects(Finder& finder, const Reader& reader)
|
---|
1134 | {
|
---|
1135 | for (void* nextObject = list_; nextObject; nextObject = *reader(reinterpret_cast<void**>(nextObject)))
|
---|
1136 | finder.visit(nextObject);
|
---|
1137 | }
|
---|
1138 | #endif
|
---|
1139 | };
|
---|
1140 |
|
---|
1141 | //-------------------------------------------------------------------
|
---|
1142 | // Data kept per thread
|
---|
1143 | //-------------------------------------------------------------------
|
---|
1144 |
|
---|
1145 | class TCMalloc_ThreadCache {
|
---|
1146 | private:
|
---|
1147 | typedef TCMalloc_ThreadCache_FreeList FreeList;
|
---|
1148 | #if COMPILER(MSVC)
|
---|
1149 | typedef DWORD ThreadIdentifier;
|
---|
1150 | #else
|
---|
1151 | typedef pthread_t ThreadIdentifier;
|
---|
1152 | #endif
|
---|
1153 |
|
---|
1154 | size_t size_; // Combined size of data
|
---|
1155 | ThreadIdentifier tid_; // Which thread owns it
|
---|
1156 | bool setspecific_; // Called pthread_setspecific?
|
---|
1157 | FreeList list_[kNumClasses]; // Array indexed by size-class
|
---|
1158 |
|
---|
1159 | // We sample allocations, biased by the size of the allocation
|
---|
1160 | uint32_t rnd_; // Cheap random number generator
|
---|
1161 | size_t bytes_until_sample_; // Bytes until we sample next
|
---|
1162 |
|
---|
1163 | public:
|
---|
1164 | // All ThreadCache objects are kept in a linked list (for stats collection)
|
---|
1165 | TCMalloc_ThreadCache* next_;
|
---|
1166 | TCMalloc_ThreadCache* prev_;
|
---|
1167 |
|
---|
1168 | void Init(ThreadIdentifier tid);
|
---|
1169 | void Cleanup();
|
---|
1170 |
|
---|
1171 | // Accessors (mostly just for printing stats)
|
---|
1172 | int freelist_length(size_t cl) const { return list_[cl].length(); }
|
---|
1173 |
|
---|
1174 | // Total byte size in cache
|
---|
1175 | size_t Size() const { return size_; }
|
---|
1176 |
|
---|
1177 | void* Allocate(size_t size);
|
---|
1178 | void Deallocate(void* ptr, size_t size_class);
|
---|
1179 |
|
---|
1180 | void FetchFromCentralCache(size_t cl, size_t allocationSize);
|
---|
1181 | void ReleaseToCentralCache(size_t cl, int N);
|
---|
1182 | void Scavenge();
|
---|
1183 | void Print() const;
|
---|
1184 |
|
---|
1185 | // Record allocation of "k" bytes. Return true iff allocation
|
---|
1186 | // should be sampled
|
---|
1187 | bool SampleAllocation(size_t k);
|
---|
1188 |
|
---|
1189 | // Pick next sampling point
|
---|
1190 | void PickNextSample();
|
---|
1191 |
|
---|
1192 | static void InitModule();
|
---|
1193 | static void InitTSD();
|
---|
1194 | static TCMalloc_ThreadCache* GetCache();
|
---|
1195 | static TCMalloc_ThreadCache* GetCacheIfPresent();
|
---|
1196 | static TCMalloc_ThreadCache* CreateCacheIfNecessary();
|
---|
1197 | static void DeleteCache(void* ptr);
|
---|
1198 | static void RecomputeThreadCacheSize();
|
---|
1199 |
|
---|
1200 | #ifdef WTF_CHANGES
|
---|
1201 | template <class Finder, class Reader>
|
---|
1202 | void enumerateFreeObjects(Finder& finder, const Reader& reader)
|
---|
1203 | {
|
---|
1204 | for (unsigned sizeClass = 0; sizeClass < kNumClasses; sizeClass++)
|
---|
1205 | list_[sizeClass].enumerateFreeObjects(finder, reader);
|
---|
1206 | }
|
---|
1207 | #endif
|
---|
1208 | };
|
---|
1209 |
|
---|
1210 | //-------------------------------------------------------------------
|
---|
1211 | // Data kept per size-class in central cache
|
---|
1212 | //-------------------------------------------------------------------
|
---|
1213 |
|
---|
1214 | class TCMalloc_Central_FreeList {
|
---|
1215 | public:
|
---|
1216 | void Init(size_t cl);
|
---|
1217 |
|
---|
1218 | // REQUIRES: lock_ is held
|
---|
1219 | // Insert object.
|
---|
1220 | // May temporarily release lock_.
|
---|
1221 | void Insert(void* object);
|
---|
1222 |
|
---|
1223 | // REQUIRES: lock_ is held
|
---|
1224 | // Remove object from cache and return.
|
---|
1225 | // Return NULL if no free entries in cache.
|
---|
1226 | void* Remove();
|
---|
1227 |
|
---|
1228 | // REQUIRES: lock_ is held
|
---|
1229 | // Populate cache by fetching from the page heap.
|
---|
1230 | // May temporarily release lock_.
|
---|
1231 | void Populate();
|
---|
1232 |
|
---|
1233 | // REQUIRES: lock_ is held
|
---|
1234 | // Number of free objects in cache
|
---|
1235 | size_t length() const { return counter_; }
|
---|
1236 |
|
---|
1237 | // Lock -- exposed because caller grabs it before touching this object
|
---|
1238 | SpinLock lock_;
|
---|
1239 |
|
---|
1240 | #ifdef WTF_CHANGES
|
---|
1241 | template <class Finder, class Reader>
|
---|
1242 | void enumerateFreeObjects(Finder& finder, const Reader& reader)
|
---|
1243 | {
|
---|
1244 | for (Span* span = &empty_; span && span != &empty_; span = (span->next ? reader(span->next) : 0))
|
---|
1245 | ASSERT(!span->objects);
|
---|
1246 |
|
---|
1247 | ASSERT(!nonempty_.objects);
|
---|
1248 | for (Span* span = reader(nonempty_.next); span && span != &nonempty_; span = (span->next ? reader(span->next) : 0)) {
|
---|
1249 | for (void* nextObject = span->objects; nextObject; nextObject = *reader(reinterpret_cast<void**>(nextObject)))
|
---|
1250 | finder.visit(nextObject);
|
---|
1251 | }
|
---|
1252 | }
|
---|
1253 | #endif
|
---|
1254 |
|
---|
1255 | private:
|
---|
1256 | // We keep linked lists of empty and non-emoty spans.
|
---|
1257 | size_t size_class_; // My size class
|
---|
1258 | Span empty_; // Dummy header for list of empty spans
|
---|
1259 | Span nonempty_; // Dummy header for list of non-empty spans
|
---|
1260 | size_t counter_; // Number of free objects in cache entry
|
---|
1261 | };
|
---|
1262 |
|
---|
1263 | // Pad each CentralCache object to multiple of 64 bytes
|
---|
1264 | class TCMalloc_Central_FreeListPadded : public TCMalloc_Central_FreeList {
|
---|
1265 | private:
|
---|
1266 | char pad_[(64 - (sizeof(TCMalloc_Central_FreeList) % 64)) % 64];
|
---|
1267 | };
|
---|
1268 |
|
---|
1269 | //-------------------------------------------------------------------
|
---|
1270 | // Global variables
|
---|
1271 | //-------------------------------------------------------------------
|
---|
1272 |
|
---|
1273 | // Central cache -- a collection of free-lists, one per size-class.
|
---|
1274 | // We have a separate lock per free-list to reduce contention.
|
---|
1275 | static TCMalloc_Central_FreeListPadded central_cache[kNumClasses];
|
---|
1276 |
|
---|
1277 | // Page-level allocator
|
---|
1278 | static SpinLock pageheap_lock = SPINLOCK_INITIALIZER;
|
---|
1279 | static void* pageheap_memory[(sizeof(TCMalloc_PageHeap) + sizeof(void*) - 1) / sizeof(void*)];
|
---|
1280 | static bool phinited = false;
|
---|
1281 |
|
---|
1282 | // Avoid extra level of indirection by making "pageheap" be just an alias
|
---|
1283 | // of pageheap_memory.
|
---|
1284 |
|
---|
1285 | typedef union {
|
---|
1286 | void* m_memory;
|
---|
1287 | TCMalloc_PageHeap m_pageHeap;
|
---|
1288 | } PageHeapUnion;
|
---|
1289 |
|
---|
1290 | static inline TCMalloc_PageHeap* getPageHeap()
|
---|
1291 | {
|
---|
1292 | return &reinterpret_cast<PageHeapUnion*>(&pageheap_memory[0])->m_pageHeap;
|
---|
1293 | }
|
---|
1294 |
|
---|
1295 | #define pageheap getPageHeap()
|
---|
1296 |
|
---|
1297 | // Thread-specific key. Initialization here is somewhat tricky
|
---|
1298 | // because some Linux startup code invokes malloc() before it
|
---|
1299 | // is in a good enough state to handle pthread_keycreate().
|
---|
1300 | // Therefore, we use TSD keys only after tsd_inited is set to true.
|
---|
1301 | // Until then, we use a slow path to get the heap object.
|
---|
1302 | static bool tsd_inited = false;
|
---|
1303 | static pthread_key_t heap_key;
|
---|
1304 | #if COMPILER(MSVC)
|
---|
1305 | DWORD tlsIndex = TLS_OUT_OF_INDEXES;
|
---|
1306 | #endif
|
---|
1307 |
|
---|
1308 | static ALWAYS_INLINE TCMalloc_ThreadCache* getThreadHeap()
|
---|
1309 | {
|
---|
1310 | #if COMPILER(MSVC)
|
---|
1311 | return static_cast<TCMalloc_ThreadCache*>(TlsGetValue(tlsIndex));
|
---|
1312 | #else
|
---|
1313 | return static_cast<TCMalloc_ThreadCache*>(pthread_getspecific(heap_key));
|
---|
1314 | #endif
|
---|
1315 | }
|
---|
1316 |
|
---|
1317 | static ALWAYS_INLINE void setThreadHeap(TCMalloc_ThreadCache* heap)
|
---|
1318 | {
|
---|
1319 | // still do pthread_setspecific when using MSVC fast TLS to
|
---|
1320 | // benefit from the delete callback.
|
---|
1321 | pthread_setspecific(heap_key, heap);
|
---|
1322 | #if COMPILER(MSVC)
|
---|
1323 | TlsSetValue(tlsIndex, heap);
|
---|
1324 | #endif
|
---|
1325 | }
|
---|
1326 |
|
---|
1327 | // Allocator for thread heaps
|
---|
1328 | static PageHeapAllocator<TCMalloc_ThreadCache> threadheap_allocator;
|
---|
1329 |
|
---|
1330 | // Linked list of heap objects. Protected by pageheap_lock.
|
---|
1331 | static TCMalloc_ThreadCache* thread_heaps = NULL;
|
---|
1332 | static int thread_heap_count = 0;
|
---|
1333 |
|
---|
1334 | // Overall thread cache size. Protected by pageheap_lock.
|
---|
1335 | static size_t overall_thread_cache_size = kDefaultOverallThreadCacheSize;
|
---|
1336 |
|
---|
1337 | // Global per-thread cache size. Writes are protected by
|
---|
1338 | // pageheap_lock. Reads are done without any locking, which should be
|
---|
1339 | // fine as long as size_t can be written atomically and we don't place
|
---|
1340 | // invariants between this variable and other pieces of state.
|
---|
1341 | static volatile size_t per_thread_cache_size = kMaxThreadCacheSize;
|
---|
1342 |
|
---|
1343 | //-------------------------------------------------------------------
|
---|
1344 | // Central cache implementation
|
---|
1345 | //-------------------------------------------------------------------
|
---|
1346 |
|
---|
1347 | void TCMalloc_Central_FreeList::Init(size_t cl) {
|
---|
1348 | lock_.Init();
|
---|
1349 | size_class_ = cl;
|
---|
1350 | DLL_Init(&empty_);
|
---|
1351 | DLL_Init(&nonempty_);
|
---|
1352 | counter_ = 0;
|
---|
1353 | }
|
---|
1354 |
|
---|
1355 | ALWAYS_INLINE void TCMalloc_Central_FreeList::Insert(void* object) {
|
---|
1356 | const PageID p = reinterpret_cast<uintptr_t>(object) >> kPageShift;
|
---|
1357 | Span* span = pageheap->GetDescriptor(p);
|
---|
1358 | ASSERT(span != NULL);
|
---|
1359 | ASSERT(span->refcount > 0);
|
---|
1360 |
|
---|
1361 | // If span is empty, move it to non-empty list
|
---|
1362 | if (span->objects == NULL) {
|
---|
1363 | DLL_Remove(span);
|
---|
1364 | DLL_Prepend(&nonempty_, span);
|
---|
1365 | Event(span, 'N', 0);
|
---|
1366 | }
|
---|
1367 |
|
---|
1368 | // The following check is expensive, so it is disabled by default
|
---|
1369 | if (false) {
|
---|
1370 | // Check that object does not occur in list
|
---|
1371 | int got = 0;
|
---|
1372 | for (void* p = span->objects; p != NULL; p = *((void**) p)) {
|
---|
1373 | ASSERT(p != object);
|
---|
1374 | got++;
|
---|
1375 | }
|
---|
1376 | ASSERT(got + span->refcount ==
|
---|
1377 | (span->length<<kPageShift)/ByteSizeForClass(span->sizeclass));
|
---|
1378 | }
|
---|
1379 |
|
---|
1380 | counter_++;
|
---|
1381 | span->refcount--;
|
---|
1382 | if (span->refcount == 0) {
|
---|
1383 | Event(span, '#', 0);
|
---|
1384 | counter_ -= (span->length<<kPageShift) / ByteSizeForClass(span->sizeclass);
|
---|
1385 | DLL_Remove(span);
|
---|
1386 |
|
---|
1387 | // Release central list lock while operating on pageheap
|
---|
1388 | lock_.Unlock();
|
---|
1389 | {
|
---|
1390 | SpinLockHolder h(&pageheap_lock);
|
---|
1391 | pageheap->Delete(span);
|
---|
1392 | }
|
---|
1393 | lock_.Lock();
|
---|
1394 | } else {
|
---|
1395 | *(reinterpret_cast<void**>(object)) = span->objects;
|
---|
1396 | span->objects = object;
|
---|
1397 | }
|
---|
1398 | }
|
---|
1399 |
|
---|
1400 | ALWAYS_INLINE void* TCMalloc_Central_FreeList::Remove() {
|
---|
1401 | if (DLL_IsEmpty(&nonempty_)) return NULL;
|
---|
1402 | Span* span = nonempty_.next;
|
---|
1403 |
|
---|
1404 | ASSERT(span->objects != NULL);
|
---|
1405 | span->refcount++;
|
---|
1406 | void* result = span->objects;
|
---|
1407 | span->objects = *(reinterpret_cast<void**>(result));
|
---|
1408 | if (span->objects == NULL) {
|
---|
1409 | // Move to empty list
|
---|
1410 | DLL_Remove(span);
|
---|
1411 | DLL_Prepend(&empty_, span);
|
---|
1412 | Event(span, 'E', 0);
|
---|
1413 | }
|
---|
1414 | counter_--;
|
---|
1415 | return result;
|
---|
1416 | }
|
---|
1417 |
|
---|
1418 | // Fetch memory from the system and add to the central cache freelist.
|
---|
1419 | ALWAYS_INLINE void TCMalloc_Central_FreeList::Populate() {
|
---|
1420 | // Release central list lock while operating on pageheap
|
---|
1421 | lock_.Unlock();
|
---|
1422 | const size_t npages = class_to_pages[size_class_];
|
---|
1423 |
|
---|
1424 | Span* span;
|
---|
1425 | {
|
---|
1426 | SpinLockHolder h(&pageheap_lock);
|
---|
1427 | span = pageheap->New(npages);
|
---|
1428 | if (span) pageheap->RegisterSizeClass(span, size_class_);
|
---|
1429 | }
|
---|
1430 | if (span == NULL) {
|
---|
1431 | MESSAGE("allocation failed: %d\n", errno);
|
---|
1432 | lock_.Lock();
|
---|
1433 | return;
|
---|
1434 | }
|
---|
1435 |
|
---|
1436 | // Split the block into pieces and add to the free-list
|
---|
1437 | // TODO: coloring of objects to avoid cache conflicts?
|
---|
1438 | void** tail = &span->objects;
|
---|
1439 | char* ptr = reinterpret_cast<char*>(span->start << kPageShift);
|
---|
1440 | char* limit = ptr + (npages << kPageShift);
|
---|
1441 | const size_t size = ByteSizeForClass(size_class_);
|
---|
1442 | int num = 0;
|
---|
1443 | char* nptr;
|
---|
1444 | while ((nptr = ptr + size) <= limit) {
|
---|
1445 | *tail = ptr;
|
---|
1446 | tail = reinterpret_cast<void**>(ptr);
|
---|
1447 | ptr = nptr;
|
---|
1448 | num++;
|
---|
1449 | }
|
---|
1450 | ASSERT(ptr <= limit);
|
---|
1451 | *tail = NULL;
|
---|
1452 | span->refcount = 0; // No sub-object in use yet
|
---|
1453 |
|
---|
1454 | // Add span to list of non-empty spans
|
---|
1455 | lock_.Lock();
|
---|
1456 | DLL_Prepend(&nonempty_, span);
|
---|
1457 | counter_ += num;
|
---|
1458 | }
|
---|
1459 |
|
---|
1460 | //-------------------------------------------------------------------
|
---|
1461 | // TCMalloc_ThreadCache implementation
|
---|
1462 | //-------------------------------------------------------------------
|
---|
1463 |
|
---|
1464 | inline bool TCMalloc_ThreadCache::SampleAllocation(size_t k) {
|
---|
1465 | if (bytes_until_sample_ < k) {
|
---|
1466 | PickNextSample();
|
---|
1467 | return true;
|
---|
1468 | } else {
|
---|
1469 | bytes_until_sample_ -= k;
|
---|
1470 | return false;
|
---|
1471 | }
|
---|
1472 | }
|
---|
1473 |
|
---|
1474 | void TCMalloc_ThreadCache::Init(ThreadIdentifier tid) {
|
---|
1475 | size_ = 0;
|
---|
1476 | next_ = NULL;
|
---|
1477 | prev_ = NULL;
|
---|
1478 | tid_ = tid;
|
---|
1479 | setspecific_ = false;
|
---|
1480 | for (size_t cl = 0; cl < kNumClasses; ++cl) {
|
---|
1481 | list_[cl].Init();
|
---|
1482 | }
|
---|
1483 |
|
---|
1484 | // Initialize RNG -- run it for a bit to get to good values
|
---|
1485 | rnd_ = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(this));
|
---|
1486 | for (int i = 0; i < 100; i++) {
|
---|
1487 | PickNextSample();
|
---|
1488 | }
|
---|
1489 | }
|
---|
1490 |
|
---|
1491 | void TCMalloc_ThreadCache::Cleanup() {
|
---|
1492 | // Put unused memory back into central cache
|
---|
1493 | for (size_t cl = 0; cl < kNumClasses; ++cl) {
|
---|
1494 | FreeList* src = &list_[cl];
|
---|
1495 | TCMalloc_Central_FreeList* dst = ¢ral_cache[cl];
|
---|
1496 | SpinLockHolder h(&dst->lock_);
|
---|
1497 | while (!src->empty()) {
|
---|
1498 | dst->Insert(src->Pop());
|
---|
1499 | }
|
---|
1500 | }
|
---|
1501 | }
|
---|
1502 |
|
---|
1503 | ALWAYS_INLINE void* TCMalloc_ThreadCache::Allocate(size_t size) {
|
---|
1504 | ASSERT(size <= kMaxSize);
|
---|
1505 | const size_t cl = SizeClass(size);
|
---|
1506 | FreeList* list = &list_[cl];
|
---|
1507 | size_t allocationSize = (size <= kMaxTinySize) ? (size + 7) & ~0x7 : ByteSizeForClass(cl);
|
---|
1508 | if (list->empty()) {
|
---|
1509 | FetchFromCentralCache(cl, allocationSize);
|
---|
1510 | if (list->empty()) return NULL;
|
---|
1511 | }
|
---|
1512 | size_ -= allocationSize;
|
---|
1513 | return list->Pop();
|
---|
1514 | }
|
---|
1515 |
|
---|
1516 | inline void TCMalloc_ThreadCache::Deallocate(void* ptr, size_t cl) {
|
---|
1517 | size_ += ByteSizeForClass(cl);
|
---|
1518 | FreeList* list = &list_[cl];
|
---|
1519 | list->Push(ptr);
|
---|
1520 | // If enough data is free, put back into central cache
|
---|
1521 | if (list->length() > kMaxFreeListLength) {
|
---|
1522 | ReleaseToCentralCache(cl, kNumObjectsToMove);
|
---|
1523 | }
|
---|
1524 | if (size_ >= per_thread_cache_size) Scavenge();
|
---|
1525 | }
|
---|
1526 |
|
---|
1527 | // Remove some objects of class "cl" from central cache and add to thread heap
|
---|
1528 | ALWAYS_INLINE void TCMalloc_ThreadCache::FetchFromCentralCache(size_t cl, size_t byteSize) {
|
---|
1529 | TCMalloc_Central_FreeList* src = ¢ral_cache[cl];
|
---|
1530 | FreeList* dst = &list_[cl];
|
---|
1531 | SpinLockHolder h(&src->lock_);
|
---|
1532 | for (int i = 0; i < kNumObjectsToMove; i++) {
|
---|
1533 | void* object = src->Remove();
|
---|
1534 | if (object == NULL) {
|
---|
1535 | if (i == 0) {
|
---|
1536 | src->Populate(); // Temporarily releases src->lock_
|
---|
1537 | object = src->Remove();
|
---|
1538 | }
|
---|
1539 | if (object == NULL) {
|
---|
1540 | break;
|
---|
1541 | }
|
---|
1542 | }
|
---|
1543 | dst->Push(object);
|
---|
1544 | size_ += byteSize;
|
---|
1545 | }
|
---|
1546 | }
|
---|
1547 |
|
---|
1548 | // Remove some objects of class "cl" from thread heap and add to central cache
|
---|
1549 | inline void TCMalloc_ThreadCache::ReleaseToCentralCache(size_t cl, int N) {
|
---|
1550 | FreeList* src = &list_[cl];
|
---|
1551 | TCMalloc_Central_FreeList* dst = ¢ral_cache[cl];
|
---|
1552 | SpinLockHolder h(&dst->lock_);
|
---|
1553 | if (N > src->length()) N = src->length();
|
---|
1554 | size_ -= N*ByteSizeForClass(cl);
|
---|
1555 | while (N-- > 0) {
|
---|
1556 | void* ptr = src->Pop();
|
---|
1557 | dst->Insert(ptr);
|
---|
1558 | }
|
---|
1559 | }
|
---|
1560 |
|
---|
1561 | // Release idle memory to the central cache
|
---|
1562 | inline void TCMalloc_ThreadCache::Scavenge() {
|
---|
1563 | // If the low-water mark for the free list is L, it means we would
|
---|
1564 | // not have had to allocate anything from the central cache even if
|
---|
1565 | // we had reduced the free list size by L. We aim to get closer to
|
---|
1566 | // that situation by dropping L/2 nodes from the free list. This
|
---|
1567 | // may not release much memory, but if so we will call scavenge again
|
---|
1568 | // pretty soon and the low-water marks will be high on that call.
|
---|
1569 | #ifndef WTF_CHANGES
|
---|
1570 | int64 start = CycleClock::Now();
|
---|
1571 | #endif
|
---|
1572 |
|
---|
1573 | for (size_t cl = 0; cl < kNumClasses; cl++) {
|
---|
1574 | FreeList* list = &list_[cl];
|
---|
1575 | const int lowmark = list->lowwatermark();
|
---|
1576 | if (lowmark > 0) {
|
---|
1577 | const int drop = (lowmark > 1) ? lowmark/2 : 1;
|
---|
1578 | ReleaseToCentralCache(cl, drop);
|
---|
1579 | }
|
---|
1580 | list->clear_lowwatermark();
|
---|
1581 | }
|
---|
1582 |
|
---|
1583 | #ifndef WTF_CHANGES
|
---|
1584 | int64 finish = CycleClock::Now();
|
---|
1585 | CycleTimer ct;
|
---|
1586 | MESSAGE("GC: %.0f ns\n", ct.CyclesToUsec(finish-start)*1000.0);
|
---|
1587 | #endif
|
---|
1588 | }
|
---|
1589 |
|
---|
1590 | ALWAYS_INLINE TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCache() {
|
---|
1591 | TCMalloc_ThreadCache* ptr = NULL;
|
---|
1592 | if (!tsd_inited) {
|
---|
1593 | InitModule();
|
---|
1594 | } else {
|
---|
1595 | ptr = getThreadHeap();
|
---|
1596 | }
|
---|
1597 | if (ptr == NULL) ptr = CreateCacheIfNecessary();
|
---|
1598 | return ptr;
|
---|
1599 | }
|
---|
1600 |
|
---|
1601 | // In deletion paths, we do not try to create a thread-cache. This is
|
---|
1602 | // because we may be in the thread destruction code and may have
|
---|
1603 | // already cleaned up the cache for this thread.
|
---|
1604 | inline TCMalloc_ThreadCache* TCMalloc_ThreadCache::GetCacheIfPresent() {
|
---|
1605 | if (!tsd_inited) return NULL;
|
---|
1606 | return getThreadHeap();
|
---|
1607 | }
|
---|
1608 |
|
---|
1609 | void TCMalloc_ThreadCache::PickNextSample() {
|
---|
1610 | // Make next "random" number
|
---|
1611 | // x^32+x^22+x^2+x^1+1 is a primitive polynomial for random numbers
|
---|
1612 | static const uint32_t kPoly = (1 << 22) | (1 << 2) | (1 << 1) | (1 << 0);
|
---|
1613 | uint32_t r = rnd_;
|
---|
1614 | rnd_ = (r << 1) ^ ((static_cast<int32_t>(r) >> 31) & kPoly);
|
---|
1615 |
|
---|
1616 | // Next point is "rnd_ % (2*sample_period)". I.e., average
|
---|
1617 | // increment is "sample_period".
|
---|
1618 | bytes_until_sample_ = rnd_ % kSampleParameter;
|
---|
1619 | }
|
---|
1620 |
|
---|
1621 | void TCMalloc_ThreadCache::InitModule() {
|
---|
1622 | // There is a slight potential race here because of double-checked
|
---|
1623 | // locking idiom. However, as long as the program does a small
|
---|
1624 | // allocation before switching to multi-threaded mode, we will be
|
---|
1625 | // fine. We increase the chances of doing such a small allocation
|
---|
1626 | // by doing one in the constructor of the module_enter_exit_hook
|
---|
1627 | // object declared below.
|
---|
1628 | SpinLockHolder h(&pageheap_lock);
|
---|
1629 | if (!phinited) {
|
---|
1630 | #ifdef WTF_CHANGES
|
---|
1631 | InitTSD();
|
---|
1632 | #endif
|
---|
1633 | InitSizeClasses();
|
---|
1634 | threadheap_allocator.Init();
|
---|
1635 | span_allocator.Init();
|
---|
1636 | span_allocator.New(); // Reduce cache conflicts
|
---|
1637 | span_allocator.New(); // Reduce cache conflicts
|
---|
1638 | stacktrace_allocator.Init();
|
---|
1639 | DLL_Init(&sampled_objects);
|
---|
1640 | for (size_t i = 0; i < kNumClasses; ++i) {
|
---|
1641 | central_cache[i].Init(i);
|
---|
1642 | }
|
---|
1643 | pageheap->init();
|
---|
1644 | phinited = 1;
|
---|
1645 | #if defined(WTF_CHANGES) && PLATFORM(DARWIN)
|
---|
1646 | FastMallocZone::init();
|
---|
1647 | #endif
|
---|
1648 | }
|
---|
1649 | }
|
---|
1650 |
|
---|
1651 | void TCMalloc_ThreadCache::InitTSD() {
|
---|
1652 | ASSERT(!tsd_inited);
|
---|
1653 | pthread_key_create(&heap_key, DeleteCache);
|
---|
1654 | #if COMPILER(MSVC)
|
---|
1655 | tlsIndex = TlsAlloc();
|
---|
1656 | #endif
|
---|
1657 | tsd_inited = true;
|
---|
1658 |
|
---|
1659 | #if !COMPILER(MSVC)
|
---|
1660 | // We may have used a fake pthread_t for the main thread. Fix it.
|
---|
1661 | pthread_t zero;
|
---|
1662 | memset(&zero, 0, sizeof(zero));
|
---|
1663 | #endif
|
---|
1664 | #ifndef WTF_CHANGES
|
---|
1665 | SpinLockHolder h(&pageheap_lock);
|
---|
1666 | #else
|
---|
1667 | ASSERT(pageheap_lock.IsLocked());
|
---|
1668 | #endif
|
---|
1669 | for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
|
---|
1670 | #if COMPILER(MSVC)
|
---|
1671 | if (h->tid_ == 0) {
|
---|
1672 | h->tid_ = GetCurrentThreadId();
|
---|
1673 | }
|
---|
1674 | #else
|
---|
1675 | if (pthread_equal(h->tid_, zero)) {
|
---|
1676 | h->tid_ = pthread_self();
|
---|
1677 | }
|
---|
1678 | #endif
|
---|
1679 | }
|
---|
1680 | }
|
---|
1681 |
|
---|
1682 | TCMalloc_ThreadCache* TCMalloc_ThreadCache::CreateCacheIfNecessary() {
|
---|
1683 | // Initialize per-thread data if necessary
|
---|
1684 | TCMalloc_ThreadCache* heap = NULL;
|
---|
1685 | {
|
---|
1686 | SpinLockHolder h(&pageheap_lock);
|
---|
1687 |
|
---|
1688 | #if COMPILER(MSVC)
|
---|
1689 | DWORD me;
|
---|
1690 | if (!tsd_inited) {
|
---|
1691 | me = 0;
|
---|
1692 | } else {
|
---|
1693 | me = GetCurrentThreadId();
|
---|
1694 | }
|
---|
1695 | #else
|
---|
1696 | // Early on in glibc's life, we cannot even call pthread_self()
|
---|
1697 | pthread_t me;
|
---|
1698 | if (!tsd_inited) {
|
---|
1699 | memset(&me, 0, sizeof(me));
|
---|
1700 | } else {
|
---|
1701 | me = pthread_self();
|
---|
1702 | }
|
---|
1703 | #endif
|
---|
1704 |
|
---|
1705 | // This may be a recursive malloc call from pthread_setspecific()
|
---|
1706 | // In that case, the heap for this thread has already been created
|
---|
1707 | // and added to the linked list. So we search for that first.
|
---|
1708 | for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
|
---|
1709 | #if COMPILER(MSVC)
|
---|
1710 | if (h->tid_ == me) {
|
---|
1711 | #else
|
---|
1712 | if (pthread_equal(h->tid_, me)) {
|
---|
1713 | #endif
|
---|
1714 | heap = h;
|
---|
1715 | break;
|
---|
1716 | }
|
---|
1717 | }
|
---|
1718 |
|
---|
1719 | if (heap == NULL) {
|
---|
1720 | // Create the heap and add it to the linked list
|
---|
1721 | heap = threadheap_allocator.New();
|
---|
1722 | heap->Init(me);
|
---|
1723 | heap->next_ = thread_heaps;
|
---|
1724 | heap->prev_ = NULL;
|
---|
1725 | if (thread_heaps != NULL) thread_heaps->prev_ = heap;
|
---|
1726 | thread_heaps = heap;
|
---|
1727 | thread_heap_count++;
|
---|
1728 | RecomputeThreadCacheSize();
|
---|
1729 | }
|
---|
1730 | }
|
---|
1731 |
|
---|
1732 | // We call pthread_setspecific() outside the lock because it may
|
---|
1733 | // call malloc() recursively. The recursive call will never get
|
---|
1734 | // here again because it will find the already allocated heap in the
|
---|
1735 | // linked list of heaps.
|
---|
1736 | if (!heap->setspecific_ && tsd_inited) {
|
---|
1737 | heap->setspecific_ = true;
|
---|
1738 | setThreadHeap(heap);
|
---|
1739 | }
|
---|
1740 | return heap;
|
---|
1741 | }
|
---|
1742 |
|
---|
1743 | void TCMalloc_ThreadCache::DeleteCache(void* ptr) {
|
---|
1744 | // Remove all memory from heap
|
---|
1745 | TCMalloc_ThreadCache* heap;
|
---|
1746 | heap = static_cast<TCMalloc_ThreadCache*>(ptr);
|
---|
1747 | heap->Cleanup();
|
---|
1748 |
|
---|
1749 | // Remove from linked list
|
---|
1750 | SpinLockHolder h(&pageheap_lock);
|
---|
1751 | if (heap->next_ != NULL) heap->next_->prev_ = heap->prev_;
|
---|
1752 | if (heap->prev_ != NULL) heap->prev_->next_ = heap->next_;
|
---|
1753 | if (thread_heaps == heap) thread_heaps = heap->next_;
|
---|
1754 | thread_heap_count--;
|
---|
1755 | RecomputeThreadCacheSize();
|
---|
1756 |
|
---|
1757 | threadheap_allocator.Delete(heap);
|
---|
1758 | }
|
---|
1759 |
|
---|
1760 | void TCMalloc_ThreadCache::RecomputeThreadCacheSize() {
|
---|
1761 | // Divide available space across threads
|
---|
1762 | int n = thread_heap_count > 0 ? thread_heap_count : 1;
|
---|
1763 | size_t space = overall_thread_cache_size / n;
|
---|
1764 |
|
---|
1765 | // Limit to allowed range
|
---|
1766 | if (space < kMinThreadCacheSize) space = kMinThreadCacheSize;
|
---|
1767 | if (space > kMaxThreadCacheSize) space = kMaxThreadCacheSize;
|
---|
1768 |
|
---|
1769 | per_thread_cache_size = space;
|
---|
1770 | }
|
---|
1771 |
|
---|
1772 | void TCMalloc_ThreadCache::Print() const {
|
---|
1773 | for (size_t cl = 0; cl < kNumClasses; ++cl) {
|
---|
1774 | MESSAGE(" %5" PRIuS " : %4d len; %4d lo\n",
|
---|
1775 | ByteSizeForClass(cl),
|
---|
1776 | list_[cl].length(),
|
---|
1777 | list_[cl].lowwatermark());
|
---|
1778 | }
|
---|
1779 | }
|
---|
1780 |
|
---|
1781 | // Extract interesting stats
|
---|
1782 | struct TCMallocStats {
|
---|
1783 | uint64_t system_bytes; // Bytes alloced from system
|
---|
1784 | uint64_t thread_bytes; // Bytes in thread caches
|
---|
1785 | uint64_t central_bytes; // Bytes in central cache
|
---|
1786 | uint64_t pageheap_bytes; // Bytes in page heap
|
---|
1787 | uint64_t metadata_bytes; // Bytes alloced for metadata
|
---|
1788 | };
|
---|
1789 |
|
---|
1790 | #ifndef WTF_CHANGES
|
---|
1791 | // Get stats into "r". Also get per-size-class counts if class_count != NULL
|
---|
1792 | static void ExtractStats(TCMallocStats* r, uint64_t* class_count) {
|
---|
1793 | r->central_bytes = 0;
|
---|
1794 | for (size_t cl = 0; cl < kNumClasses; ++cl) {
|
---|
1795 | SpinLockHolder h(¢ral_cache[cl].lock_);
|
---|
1796 | const int length = central_cache[cl].length();
|
---|
1797 | r->central_bytes += static_cast<uint64_t>(ByteSizeForClass(cl)) * length;
|
---|
1798 | if (class_count) class_count[cl] = length;
|
---|
1799 | }
|
---|
1800 |
|
---|
1801 | // Add stats from per-thread heaps
|
---|
1802 | r->thread_bytes = 0;
|
---|
1803 | { // scope
|
---|
1804 | SpinLockHolder h(&pageheap_lock);
|
---|
1805 | for (TCMalloc_ThreadCache* h = thread_heaps; h != NULL; h = h->next_) {
|
---|
1806 | r->thread_bytes += h->Size();
|
---|
1807 | if (class_count) {
|
---|
1808 | for (size_t cl = 0; cl < kNumClasses; ++cl) {
|
---|
1809 | class_count[cl] += h->freelist_length(cl);
|
---|
1810 | }
|
---|
1811 | }
|
---|
1812 | }
|
---|
1813 | }
|
---|
1814 |
|
---|
1815 | { //scope
|
---|
1816 | SpinLockHolder h(&pageheap_lock);
|
---|
1817 | r->system_bytes = pageheap->SystemBytes();
|
---|
1818 | r->metadata_bytes = metadata_system_bytes;
|
---|
1819 | r->pageheap_bytes = pageheap->FreeBytes();
|
---|
1820 | }
|
---|
1821 | }
|
---|
1822 | #endif
|
---|
1823 |
|
---|
1824 | #ifndef WTF_CHANGES
|
---|
1825 | // WRITE stats to "out"
|
---|
1826 | static void DumpStats(TCMalloc_Printer* out, int level) {
|
---|
1827 | TCMallocStats stats;
|
---|
1828 | uint64_t class_count[kNumClasses];
|
---|
1829 | ExtractStats(&stats, (level >= 2 ? class_count : NULL));
|
---|
1830 |
|
---|
1831 | if (level >= 2) {
|
---|
1832 | out->printf("------------------------------------------------\n");
|
---|
1833 | uint64_t cumulative = 0;
|
---|
1834 | for (int cl = 0; cl < kNumClasses; ++cl) {
|
---|
1835 | if (class_count[cl] > 0) {
|
---|
1836 | uint64_t class_bytes = class_count[cl] * ByteSizeForClass(cl);
|
---|
1837 | cumulative += class_bytes;
|
---|
1838 | out->printf("class %3d [ %8" PRIuS " bytes ] : "
|
---|
1839 | "%8" LLU " objs; %5.1f MB; %5.1f cum MB\n",
|
---|
1840 | cl, ByteSizeForClass(cl),
|
---|
1841 | class_count[cl],
|
---|
1842 | class_bytes / 1048576.0,
|
---|
1843 | cumulative / 1048576.0);
|
---|
1844 | }
|
---|
1845 | }
|
---|
1846 |
|
---|
1847 | SpinLockHolder h(&pageheap_lock);
|
---|
1848 | pageheap->Dump(out);
|
---|
1849 | }
|
---|
1850 |
|
---|
1851 | const uint64_t bytes_in_use = stats.system_bytes
|
---|
1852 | - stats.pageheap_bytes
|
---|
1853 | - stats.central_bytes
|
---|
1854 | - stats.thread_bytes;
|
---|
1855 |
|
---|
1856 | out->printf("------------------------------------------------\n"
|
---|
1857 | "MALLOC: %12" LLU " Heap size\n"
|
---|
1858 | "MALLOC: %12" LLU " Bytes in use by application\n"
|
---|
1859 | "MALLOC: %12" LLU " Bytes free in page heap\n"
|
---|
1860 | "MALLOC: %12" LLU " Bytes free in central cache\n"
|
---|
1861 | "MALLOC: %12" LLU " Bytes free in thread caches\n"
|
---|
1862 | "MALLOC: %12" LLU " Spans in use\n"
|
---|
1863 | "MALLOC: %12" LLU " Thread heaps in use\n"
|
---|
1864 | "MALLOC: %12" LLU " Metadata allocated\n"
|
---|
1865 | "------------------------------------------------\n",
|
---|
1866 | stats.system_bytes,
|
---|
1867 | bytes_in_use,
|
---|
1868 | stats.pageheap_bytes,
|
---|
1869 | stats.central_bytes,
|
---|
1870 | stats.thread_bytes,
|
---|
1871 | uint64_t(span_allocator.inuse()),
|
---|
1872 | uint64_t(threadheap_allocator.inuse()),
|
---|
1873 | stats.metadata_bytes);
|
---|
1874 | }
|
---|
1875 |
|
---|
1876 | static void PrintStats(int level) {
|
---|
1877 | const int kBufferSize = 16 << 10;
|
---|
1878 | char* buffer = new char[kBufferSize];
|
---|
1879 | TCMalloc_Printer printer(buffer, kBufferSize);
|
---|
1880 | DumpStats(&printer, level);
|
---|
1881 | write(STDERR_FILENO, buffer, strlen(buffer));
|
---|
1882 | delete[] buffer;
|
---|
1883 | }
|
---|
1884 |
|
---|
1885 | static void** DumpStackTraces() {
|
---|
1886 | // Count how much space we need
|
---|
1887 | int needed_slots = 0;
|
---|
1888 | {
|
---|
1889 | SpinLockHolder h(&pageheap_lock);
|
---|
1890 | for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
|
---|
1891 | StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
|
---|
1892 | needed_slots += 3 + stack->depth;
|
---|
1893 | }
|
---|
1894 | needed_slots += 100; // Slop in case sample grows
|
---|
1895 | needed_slots += needed_slots/8; // An extra 12.5% slop
|
---|
1896 | }
|
---|
1897 |
|
---|
1898 | void** result = new void*[needed_slots];
|
---|
1899 | if (result == NULL) {
|
---|
1900 | MESSAGE("tcmalloc: could not allocate %d slots for stack traces\n",
|
---|
1901 | needed_slots);
|
---|
1902 | return NULL;
|
---|
1903 | }
|
---|
1904 |
|
---|
1905 | SpinLockHolder h(&pageheap_lock);
|
---|
1906 | int used_slots = 0;
|
---|
1907 | for (Span* s = sampled_objects.next; s != &sampled_objects; s = s->next) {
|
---|
1908 | ASSERT(used_slots < needed_slots); // Need to leave room for terminator
|
---|
1909 | StackTrace* stack = reinterpret_cast<StackTrace*>(s->objects);
|
---|
1910 | if (used_slots + 3 + stack->depth >= needed_slots) {
|
---|
1911 | // No more room
|
---|
1912 | break;
|
---|
1913 | }
|
---|
1914 |
|
---|
1915 | result[used_slots+0] = reinterpret_cast<void*>(1);
|
---|
1916 | result[used_slots+1] = reinterpret_cast<void*>(stack->size);
|
---|
1917 | result[used_slots+2] = reinterpret_cast<void*>(stack->depth);
|
---|
1918 | for (int d = 0; d < stack->depth; d++) {
|
---|
1919 | result[used_slots+3+d] = stack->stack[d];
|
---|
1920 | }
|
---|
1921 | used_slots += 3 + stack->depth;
|
---|
1922 | }
|
---|
1923 | result[used_slots] = reinterpret_cast<void*>(0);
|
---|
1924 | return result;
|
---|
1925 | }
|
---|
1926 | #endif
|
---|
1927 |
|
---|
1928 | #ifndef WTF_CHANGES
|
---|
1929 |
|
---|
1930 | // TCMalloc's support for extra malloc interfaces
|
---|
1931 | class TCMallocImplementation : public MallocExtension {
|
---|
1932 | public:
|
---|
1933 | virtual void GetStats(char* buffer, int buffer_length) {
|
---|
1934 | ASSERT(buffer_length > 0);
|
---|
1935 | TCMalloc_Printer printer(buffer, buffer_length);
|
---|
1936 |
|
---|
1937 | // Print level one stats unless lots of space is available
|
---|
1938 | if (buffer_length < 10000) {
|
---|
1939 | DumpStats(&printer, 1);
|
---|
1940 | } else {
|
---|
1941 | DumpStats(&printer, 2);
|
---|
1942 | }
|
---|
1943 | }
|
---|
1944 |
|
---|
1945 | virtual void** ReadStackTraces() {
|
---|
1946 | return DumpStackTraces();
|
---|
1947 | }
|
---|
1948 |
|
---|
1949 | virtual bool GetNumericProperty(const char* name, size_t* value) {
|
---|
1950 | ASSERT(name != NULL);
|
---|
1951 |
|
---|
1952 | if (strcmp(name, "generic.current_allocated_bytes") == 0) {
|
---|
1953 | TCMallocStats stats;
|
---|
1954 | ExtractStats(&stats, NULL);
|
---|
1955 | *value = stats.system_bytes
|
---|
1956 | - stats.thread_bytes
|
---|
1957 | - stats.central_bytes
|
---|
1958 | - stats.pageheap_bytes;
|
---|
1959 | return true;
|
---|
1960 | }
|
---|
1961 |
|
---|
1962 | if (strcmp(name, "generic.heap_size") == 0) {
|
---|
1963 | TCMallocStats stats;
|
---|
1964 | ExtractStats(&stats, NULL);
|
---|
1965 | *value = stats.system_bytes;
|
---|
1966 | return true;
|
---|
1967 | }
|
---|
1968 |
|
---|
1969 | if (strcmp(name, "tcmalloc.slack_bytes") == 0) {
|
---|
1970 | // We assume that bytes in the page heap are not fragmented too
|
---|
1971 | // badly, and are therefore available for allocation.
|
---|
1972 | SpinLockHolder l(&pageheap_lock);
|
---|
1973 | *value = pageheap->FreeBytes();
|
---|
1974 | return true;
|
---|
1975 | }
|
---|
1976 |
|
---|
1977 | if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
|
---|
1978 | SpinLockHolder l(&pageheap_lock);
|
---|
1979 | *value = overall_thread_cache_size;
|
---|
1980 | return true;
|
---|
1981 | }
|
---|
1982 |
|
---|
1983 | if (strcmp(name, "tcmalloc.current_total_thread_cache_bytes") == 0) {
|
---|
1984 | TCMallocStats stats;
|
---|
1985 | ExtractStats(&stats, NULL);
|
---|
1986 | *value = stats.thread_bytes;
|
---|
1987 | return true;
|
---|
1988 | }
|
---|
1989 |
|
---|
1990 | return false;
|
---|
1991 | }
|
---|
1992 |
|
---|
1993 | virtual bool SetNumericProperty(const char* name, size_t value) {
|
---|
1994 | ASSERT(name != NULL);
|
---|
1995 |
|
---|
1996 | if (strcmp(name, "tcmalloc.max_total_thread_cache_bytes") == 0) {
|
---|
1997 | // Clip the value to a reasonable range
|
---|
1998 | if (value < kMinThreadCacheSize) value = kMinThreadCacheSize;
|
---|
1999 | if (value > (1<<30)) value = (1<<30); // Limit to 1GB
|
---|
2000 |
|
---|
2001 | SpinLockHolder l(&pageheap_lock);
|
---|
2002 | overall_thread_cache_size = static_cast<size_t>(value);
|
---|
2003 | TCMalloc_ThreadCache::RecomputeThreadCacheSize();
|
---|
2004 | return true;
|
---|
2005 | }
|
---|
2006 |
|
---|
2007 | return false;
|
---|
2008 | }
|
---|
2009 | };
|
---|
2010 | #endif
|
---|
2011 |
|
---|
2012 | // RedHat 9's pthread manager allocates an object directly by calling
|
---|
2013 | // a __libc_XXX() routine. This memory block is not known to tcmalloc.
|
---|
2014 | // At cleanup time, the pthread manager calls free() on this
|
---|
2015 | // pointer, which then crashes.
|
---|
2016 | //
|
---|
2017 | // We hack around this problem by disabling all deallocations
|
---|
2018 | // after a global object destructor in this module has been called.
|
---|
2019 | #ifndef WTF_CHANGES
|
---|
2020 | static bool tcmalloc_is_destroyed = false;
|
---|
2021 | #endif
|
---|
2022 |
|
---|
2023 | //-------------------------------------------------------------------
|
---|
2024 | // Helpers for the exported routines below
|
---|
2025 | //-------------------------------------------------------------------
|
---|
2026 |
|
---|
2027 | #ifndef WTF_CHANGES
|
---|
2028 |
|
---|
2029 | static Span* DoSampledAllocation(size_t size) {
|
---|
2030 | SpinLockHolder h(&pageheap_lock);
|
---|
2031 |
|
---|
2032 | // Allocate span
|
---|
2033 | Span* span = pageheap->New(pages(size == 0 ? 1 : size));
|
---|
2034 | if (span == NULL) {
|
---|
2035 | return NULL;
|
---|
2036 | }
|
---|
2037 |
|
---|
2038 | // Allocate stack trace
|
---|
2039 | StackTrace* stack = stacktrace_allocator.New();
|
---|
2040 | if (stack == NULL) {
|
---|
2041 | // Sampling failed because of lack of memory
|
---|
2042 | return span;
|
---|
2043 | }
|
---|
2044 |
|
---|
2045 | // Fill stack trace and record properly
|
---|
2046 | stack->depth = GetStackTrace(stack->stack, kMaxStackDepth, 2);
|
---|
2047 | stack->size = size;
|
---|
2048 | span->sample = 1;
|
---|
2049 | span->objects = stack;
|
---|
2050 | DLL_Prepend(&sampled_objects, span);
|
---|
2051 |
|
---|
2052 | return span;
|
---|
2053 | }
|
---|
2054 | #endif
|
---|
2055 |
|
---|
2056 | static ALWAYS_INLINE void* do_malloc(size_t size) {
|
---|
2057 |
|
---|
2058 | #ifdef WTF_CHANGES
|
---|
2059 | ASSERT(!isForbidden());
|
---|
2060 | #endif
|
---|
2061 |
|
---|
2062 | #ifndef WTF_CHANGES
|
---|
2063 | if (TCMallocDebug::level >= TCMallocDebug::kVerbose)
|
---|
2064 | MESSAGE("In tcmalloc do_malloc(%" PRIuS")\n", size);
|
---|
2065 | #endif
|
---|
2066 | // The following call forces module initialization
|
---|
2067 | TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
|
---|
2068 | #ifndef WTF_CHANGES
|
---|
2069 | if (heap->SampleAllocation(size)) {
|
---|
2070 | Span* span = DoSampledAllocation(size);
|
---|
2071 | if (span == NULL) return NULL;
|
---|
2072 | return reinterpret_cast<void*>(span->start << kPageShift);
|
---|
2073 | } else
|
---|
2074 | #endif
|
---|
2075 | if (size > kMaxSize) {
|
---|
2076 | // Use page-level allocator
|
---|
2077 | SpinLockHolder h(&pageheap_lock);
|
---|
2078 | Span* span = pageheap->New(pages(size));
|
---|
2079 | if (span == NULL) return NULL;
|
---|
2080 | return reinterpret_cast<void*>(span->start << kPageShift);
|
---|
2081 | } else {
|
---|
2082 | return heap->Allocate(size);
|
---|
2083 | }
|
---|
2084 | }
|
---|
2085 |
|
---|
2086 | static ALWAYS_INLINE void do_free(void* ptr) {
|
---|
2087 | #ifndef WTF_CHANGES
|
---|
2088 | if (TCMallocDebug::level >= TCMallocDebug::kVerbose)
|
---|
2089 | MESSAGE("In tcmalloc do_free(%p)\n", ptr);
|
---|
2090 | #endif
|
---|
2091 | #if WTF_CHANGES
|
---|
2092 | if (ptr == NULL) return;
|
---|
2093 | #else
|
---|
2094 | if (ptr == NULL || tcmalloc_is_destroyed) return;
|
---|
2095 | #endif
|
---|
2096 |
|
---|
2097 | ASSERT(pageheap != NULL); // Should not call free() before malloc()
|
---|
2098 | const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
|
---|
2099 | Span* span = pageheap->GetDescriptor(p);
|
---|
2100 |
|
---|
2101 | #ifndef WTF_CHANGES
|
---|
2102 | if (span == NULL) {
|
---|
2103 | // We've seen systems where a piece of memory allocated using the
|
---|
2104 | // allocator built in to libc is deallocated using free() and
|
---|
2105 | // therefore ends up inside tcmalloc which can't find the
|
---|
2106 | // corresponding span. We silently throw this object on the floor
|
---|
2107 | // instead of crashing.
|
---|
2108 | MESSAGE("tcmalloc: ignoring potential glibc-2.3.5 induced free "
|
---|
2109 | "of an unknown object %p\n", ptr);
|
---|
2110 | return;
|
---|
2111 | }
|
---|
2112 | #endif
|
---|
2113 |
|
---|
2114 | ASSERT(span != NULL);
|
---|
2115 | ASSERT(!span->free);
|
---|
2116 | const size_t cl = span->sizeclass;
|
---|
2117 | if (cl != 0) {
|
---|
2118 | ASSERT(!span->sample);
|
---|
2119 | TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCacheIfPresent();
|
---|
2120 | if (heap != NULL) {
|
---|
2121 | heap->Deallocate(ptr, cl);
|
---|
2122 | } else {
|
---|
2123 | // Delete directly into central cache
|
---|
2124 | SpinLockHolder h(¢ral_cache[cl].lock_);
|
---|
2125 | central_cache[cl].Insert(ptr);
|
---|
2126 | }
|
---|
2127 | } else {
|
---|
2128 | SpinLockHolder h(&pageheap_lock);
|
---|
2129 | ASSERT(reinterpret_cast<uintptr_t>(ptr) % kPageSize == 0);
|
---|
2130 | ASSERT(span->start == p);
|
---|
2131 | if (span->sample) {
|
---|
2132 | DLL_Remove(span);
|
---|
2133 | stacktrace_allocator.Delete(reinterpret_cast<StackTrace*>(span->objects));
|
---|
2134 | span->objects = NULL;
|
---|
2135 | }
|
---|
2136 | pageheap->Delete(span);
|
---|
2137 | }
|
---|
2138 | }
|
---|
2139 |
|
---|
2140 | #ifndef WTF_CHANGES
|
---|
2141 | // For use by exported routines below that want specific alignments
|
---|
2142 | //
|
---|
2143 | // Note: this code can be slow, and can significantly fragment memory.
|
---|
2144 | // The expectation is that memalign/posix_memalign/valloc/pvalloc will
|
---|
2145 | // not be invoked very often. This requirement simplifies our
|
---|
2146 | // implementation and allows us to tune for expected allocation
|
---|
2147 | // patterns.
|
---|
2148 | static void* do_memalign(size_t align, size_t size) {
|
---|
2149 | ASSERT((align & (align - 1)) == 0);
|
---|
2150 | ASSERT(align > 0);
|
---|
2151 | if (pageheap == NULL) TCMalloc_ThreadCache::InitModule();
|
---|
2152 |
|
---|
2153 | // Allocate at least one byte to avoid boundary conditions below
|
---|
2154 | if (size == 0) size = 1;
|
---|
2155 |
|
---|
2156 | if (size <= kMaxSize && align < kPageSize) {
|
---|
2157 | // Search through acceptable size classes looking for one with
|
---|
2158 | // enough alignment. This depends on the fact that
|
---|
2159 | // InitSizeClasses() currently produces several size classes that
|
---|
2160 | // are aligned at powers of two. We will waste time and space if
|
---|
2161 | // we miss in the size class array, but that is deemed acceptable
|
---|
2162 | // since memalign() should be used rarely.
|
---|
2163 | size_t cl = SizeClass(size);
|
---|
2164 | while (cl < kNumClasses && ((class_to_size[cl] & (align - 1)) != 0)) {
|
---|
2165 | cl++;
|
---|
2166 | }
|
---|
2167 | if (cl < kNumClasses) {
|
---|
2168 | TCMalloc_ThreadCache* heap = TCMalloc_ThreadCache::GetCache();
|
---|
2169 | return heap->Allocate(class_to_size[cl]);
|
---|
2170 | }
|
---|
2171 | }
|
---|
2172 |
|
---|
2173 | // We will allocate directly from the page heap
|
---|
2174 | SpinLockHolder h(&pageheap_lock);
|
---|
2175 |
|
---|
2176 | if (align <= kPageSize) {
|
---|
2177 | // Any page-level allocation will be fine
|
---|
2178 | // TODO: We could put the rest of this page in the appropriate
|
---|
2179 | // TODO: cache but it does not seem worth it.
|
---|
2180 | Span* span = pageheap->New(pages(size));
|
---|
2181 | if (span == NULL) return NULL;
|
---|
2182 | return reinterpret_cast<void*>(span->start << kPageShift);
|
---|
2183 | }
|
---|
2184 |
|
---|
2185 | // Allocate extra pages and carve off an aligned portion
|
---|
2186 | const int alloc = pages(size + align);
|
---|
2187 | Span* span = pageheap->New(alloc);
|
---|
2188 | if (span == NULL) return NULL;
|
---|
2189 |
|
---|
2190 | // Skip starting portion so that we end up aligned
|
---|
2191 | int skip = 0;
|
---|
2192 | while ((((span->start+skip) << kPageShift) & (align - 1)) != 0) {
|
---|
2193 | skip++;
|
---|
2194 | }
|
---|
2195 | ASSERT(skip < alloc);
|
---|
2196 | if (skip > 0) {
|
---|
2197 | Span* rest = pageheap->Split(span, skip);
|
---|
2198 | pageheap->Delete(span);
|
---|
2199 | span = rest;
|
---|
2200 | }
|
---|
2201 |
|
---|
2202 | // Skip trailing portion that we do not need to return
|
---|
2203 | const size_t needed = pages(size);
|
---|
2204 | ASSERT(span->length >= needed);
|
---|
2205 | if (span->length > needed) {
|
---|
2206 | Span* trailer = pageheap->Split(span, needed);
|
---|
2207 | pageheap->Delete(trailer);
|
---|
2208 | }
|
---|
2209 | return reinterpret_cast<void*>(span->start << kPageShift);
|
---|
2210 | }
|
---|
2211 | #endif
|
---|
2212 |
|
---|
2213 |
|
---|
2214 | // The constructor allocates an object to ensure that initialization
|
---|
2215 | // runs before main(), and therefore we do not have a chance to become
|
---|
2216 | // multi-threaded before initialization. We also create the TSD key
|
---|
2217 | // here. Presumably by the time this constructor runs, glibc is in
|
---|
2218 | // good enough shape to handle pthread_key_create().
|
---|
2219 | //
|
---|
2220 | // The constructor also takes the opportunity to tell STL to use
|
---|
2221 | // tcmalloc. We want to do this early, before construct time, so
|
---|
2222 | // all user STL allocations go through tcmalloc (which works really
|
---|
2223 | // well for STL).
|
---|
2224 | //
|
---|
2225 | // The destructor prints stats when the program exits.
|
---|
2226 |
|
---|
2227 | class TCMallocGuard {
|
---|
2228 | public:
|
---|
2229 | TCMallocGuard() {
|
---|
2230 | #ifndef WTF_CHANGES
|
---|
2231 | char *envval;
|
---|
2232 | if ((envval = getenv("TCMALLOC_DEBUG"))) {
|
---|
2233 | TCMallocDebug::level = atoi(envval);
|
---|
2234 | MESSAGE("Set tcmalloc debugging level to %d\n", TCMallocDebug::level);
|
---|
2235 | }
|
---|
2236 | #endif
|
---|
2237 | do_free(do_malloc(1));
|
---|
2238 | TCMalloc_ThreadCache::InitTSD();
|
---|
2239 | do_free(do_malloc(1));
|
---|
2240 | #ifndef WTF_CHANGES
|
---|
2241 | MallocExtension::Register(new TCMallocImplementation);
|
---|
2242 | #endif
|
---|
2243 | }
|
---|
2244 |
|
---|
2245 | #ifndef WTF_CHANGES
|
---|
2246 | ~TCMallocGuard() {
|
---|
2247 | const char* env = getenv("MALLOCSTATS");
|
---|
2248 | if (env != NULL) {
|
---|
2249 | int level = atoi(env);
|
---|
2250 | if (level < 1) level = 1;
|
---|
2251 | PrintStats(level);
|
---|
2252 | }
|
---|
2253 | }
|
---|
2254 | #endif
|
---|
2255 | };
|
---|
2256 |
|
---|
2257 | #ifndef WTF_CHANGES
|
---|
2258 | static TCMallocGuard module_enter_exit_hook;
|
---|
2259 | #endif
|
---|
2260 |
|
---|
2261 | //-------------------------------------------------------------------
|
---|
2262 | // Exported routines
|
---|
2263 | //-------------------------------------------------------------------
|
---|
2264 |
|
---|
2265 | // CAVEAT: The code structure below ensures that MallocHook methods are always
|
---|
2266 | // called from the stack frame of the invoked allocation function.
|
---|
2267 | // heap-checker.cc depends on this to start a stack trace from
|
---|
2268 | // the call to the (de)allocation function.
|
---|
2269 |
|
---|
2270 | #ifndef WTF_CHANGES
|
---|
2271 | extern "C"
|
---|
2272 | #endif
|
---|
2273 | void* malloc(size_t size) {
|
---|
2274 | void* result = do_malloc(size);
|
---|
2275 | #ifndef WTF_CHANGES
|
---|
2276 | MallocHook::InvokeNewHook(result, size);
|
---|
2277 | #endif
|
---|
2278 | return result;
|
---|
2279 | }
|
---|
2280 |
|
---|
2281 | #ifndef WTF_CHANGES
|
---|
2282 | extern "C"
|
---|
2283 | #endif
|
---|
2284 | void free(void* ptr) {
|
---|
2285 | #ifndef WTF_CHANGES
|
---|
2286 | MallocHook::InvokeDeleteHook(ptr);
|
---|
2287 | #endif
|
---|
2288 | do_free(ptr);
|
---|
2289 | }
|
---|
2290 |
|
---|
2291 | #ifndef WTF_CHANGES
|
---|
2292 | extern "C"
|
---|
2293 | #endif
|
---|
2294 | void* calloc(size_t n, size_t elem_size) {
|
---|
2295 | void* result = do_malloc(n * elem_size);
|
---|
2296 | if (result != NULL) {
|
---|
2297 | memset(result, 0, n * elem_size);
|
---|
2298 | }
|
---|
2299 | #ifndef WTF_CHANGES
|
---|
2300 | MallocHook::InvokeNewHook(result, n * elem_size);
|
---|
2301 | #endif
|
---|
2302 | return result;
|
---|
2303 | }
|
---|
2304 |
|
---|
2305 | #ifndef WTF_CHANGES
|
---|
2306 | extern "C"
|
---|
2307 | #endif
|
---|
2308 | void cfree(void* ptr) {
|
---|
2309 | #ifndef WTF_CHANGES
|
---|
2310 | MallocHook::InvokeDeleteHook(ptr);
|
---|
2311 | #endif
|
---|
2312 | do_free(ptr);
|
---|
2313 | }
|
---|
2314 |
|
---|
2315 | #ifndef WTF_CHANGES
|
---|
2316 | extern "C"
|
---|
2317 | #endif
|
---|
2318 | void* realloc(void* old_ptr, size_t new_size) {
|
---|
2319 | if (old_ptr == NULL) {
|
---|
2320 | void* result = do_malloc(new_size);
|
---|
2321 | #ifndef WTF_CHANGES
|
---|
2322 | MallocHook::InvokeNewHook(result, new_size);
|
---|
2323 | #endif
|
---|
2324 | return result;
|
---|
2325 | }
|
---|
2326 | if (new_size == 0) {
|
---|
2327 | #ifndef WTF_CHANGES
|
---|
2328 | MallocHook::InvokeDeleteHook(old_ptr);
|
---|
2329 | #endif
|
---|
2330 | free(old_ptr);
|
---|
2331 | return NULL;
|
---|
2332 | }
|
---|
2333 |
|
---|
2334 | // Get the size of the old entry
|
---|
2335 | const PageID p = reinterpret_cast<uintptr_t>(old_ptr) >> kPageShift;
|
---|
2336 | Span* span = pageheap->GetDescriptor(p);
|
---|
2337 | size_t old_size;
|
---|
2338 | if (span->sizeclass != 0) {
|
---|
2339 | old_size = ByteSizeForClass(span->sizeclass);
|
---|
2340 | } else {
|
---|
2341 | old_size = span->length << kPageShift;
|
---|
2342 | }
|
---|
2343 |
|
---|
2344 | // Reallocate if the new size is larger than the old size,
|
---|
2345 | // or if the new size is significantly smaller than the old size.
|
---|
2346 | if ((new_size > old_size) || (AllocationSize(new_size) < old_size)) {
|
---|
2347 | // Need to reallocate
|
---|
2348 | void* new_ptr = do_malloc(new_size);
|
---|
2349 | if (new_ptr == NULL) {
|
---|
2350 | return NULL;
|
---|
2351 | }
|
---|
2352 | #ifndef WTF_CHANGES
|
---|
2353 | MallocHook::InvokeNewHook(new_ptr, new_size);
|
---|
2354 | #endif
|
---|
2355 | memcpy(new_ptr, old_ptr, ((old_size < new_size) ? old_size : new_size));
|
---|
2356 | #ifndef WTF_CHANGES
|
---|
2357 | MallocHook::InvokeDeleteHook(old_ptr);
|
---|
2358 | #endif
|
---|
2359 | free(old_ptr);
|
---|
2360 | return new_ptr;
|
---|
2361 | } else {
|
---|
2362 | return old_ptr;
|
---|
2363 | }
|
---|
2364 | }
|
---|
2365 |
|
---|
2366 | #ifndef COMPILER_INTEL
|
---|
2367 | #define OPNEW_THROW
|
---|
2368 | #define OPDELETE_THROW
|
---|
2369 | #else
|
---|
2370 | #define OPNEW_THROW throw(std::bad_alloc)
|
---|
2371 | #define OPDELETE_THROW throw()
|
---|
2372 | #endif
|
---|
2373 |
|
---|
2374 | #ifndef WTF_CHANGES
|
---|
2375 |
|
---|
2376 | void* operator new(size_t size) OPNEW_THROW {
|
---|
2377 | void* p = do_malloc(size);
|
---|
2378 | if (p == NULL) {
|
---|
2379 | MESSAGE("Unable to allocate %" PRIuS " bytes: new failed\n", size);
|
---|
2380 | abort();
|
---|
2381 | }
|
---|
2382 | MallocHook::InvokeNewHook(p, size);
|
---|
2383 | return p;
|
---|
2384 | }
|
---|
2385 |
|
---|
2386 | void operator delete(void* p) OPDELETE_THROW {
|
---|
2387 | MallocHook::InvokeDeleteHook(p);
|
---|
2388 | do_free(p);
|
---|
2389 | }
|
---|
2390 |
|
---|
2391 | void* operator new[](size_t size) OPNEW_THROW {
|
---|
2392 | void* p = do_malloc(size);
|
---|
2393 | if (p == NULL) {
|
---|
2394 | MESSAGE("Unable to allocate %" PRIuS " bytes: new failed\n", size);
|
---|
2395 | abort();
|
---|
2396 | }
|
---|
2397 | MallocHook::InvokeNewHook(p, size);
|
---|
2398 | return p;
|
---|
2399 | }
|
---|
2400 |
|
---|
2401 | void operator delete[](void* p) OPDELETE_THROW {
|
---|
2402 | MallocHook::InvokeDeleteHook(p);
|
---|
2403 | do_free(p);
|
---|
2404 | }
|
---|
2405 |
|
---|
2406 | extern "C" void* memalign(size_t align, size_t size) {
|
---|
2407 | void* result = do_memalign(align, size);
|
---|
2408 | MallocHook::InvokeNewHook(result, size);
|
---|
2409 | return result;
|
---|
2410 | }
|
---|
2411 |
|
---|
2412 | extern "C" int posix_memalign(void** result_ptr, size_t align, size_t size) {
|
---|
2413 | if (((align % sizeof(void*)) != 0) ||
|
---|
2414 | ((align & (align - 1)) != 0) ||
|
---|
2415 | (align == 0)) {
|
---|
2416 | return EINVAL;
|
---|
2417 | }
|
---|
2418 |
|
---|
2419 | void* result = do_memalign(align, size);
|
---|
2420 | MallocHook::InvokeNewHook(result, size);
|
---|
2421 | if (result == NULL) {
|
---|
2422 | return ENOMEM;
|
---|
2423 | } else {
|
---|
2424 | *result_ptr = result;
|
---|
2425 | return 0;
|
---|
2426 | }
|
---|
2427 | }
|
---|
2428 |
|
---|
2429 | static size_t pagesize = 0;
|
---|
2430 |
|
---|
2431 | extern "C" void* valloc(size_t size) {
|
---|
2432 | // Allocate page-aligned object of length >= size bytes
|
---|
2433 | if (pagesize == 0) pagesize = getpagesize();
|
---|
2434 | void* result = do_memalign(pagesize, size);
|
---|
2435 | MallocHook::InvokeNewHook(result, size);
|
---|
2436 | return result;
|
---|
2437 | }
|
---|
2438 |
|
---|
2439 | extern "C" void* pvalloc(size_t size) {
|
---|
2440 | // Round up size to a multiple of pagesize
|
---|
2441 | if (pagesize == 0) pagesize = getpagesize();
|
---|
2442 | size = (size + pagesize - 1) & ~(pagesize - 1);
|
---|
2443 | void* result = do_memalign(pagesize, size);
|
---|
2444 | MallocHook::InvokeNewHook(result, size);
|
---|
2445 | return result;
|
---|
2446 | }
|
---|
2447 |
|
---|
2448 | extern "C" void malloc_stats(void) {
|
---|
2449 | PrintStats(1);
|
---|
2450 | }
|
---|
2451 |
|
---|
2452 | extern "C" int mallopt(int cmd, int value) {
|
---|
2453 | return 1; // Indicates error
|
---|
2454 | }
|
---|
2455 |
|
---|
2456 | extern "C" struct mallinfo mallinfo(void) {
|
---|
2457 | TCMallocStats stats;
|
---|
2458 | ExtractStats(&stats, NULL);
|
---|
2459 |
|
---|
2460 | // Just some of the fields are filled in.
|
---|
2461 | struct mallinfo info;
|
---|
2462 | memset(&info, 0, sizeof(info));
|
---|
2463 |
|
---|
2464 | // Unfortunately, the struct contains "int" field, so some of the
|
---|
2465 | // size values will be truncated.
|
---|
2466 | info.arena = static_cast<int>(stats.system_bytes);
|
---|
2467 | info.fsmblks = static_cast<int>(stats.thread_bytes + stats.central_bytes);
|
---|
2468 | info.fordblks = static_cast<int>(stats.pageheap_bytes);
|
---|
2469 | info.uordblks = static_cast<int>(stats.system_bytes
|
---|
2470 | - stats.thread_bytes
|
---|
2471 | - stats.central_bytes
|
---|
2472 | - stats.pageheap_bytes);
|
---|
2473 |
|
---|
2474 | return info;
|
---|
2475 | }
|
---|
2476 |
|
---|
2477 | //-------------------------------------------------------------------
|
---|
2478 | // Some library routines on RedHat 9 allocate memory using malloc()
|
---|
2479 | // and free it using __libc_free() (or vice-versa). Since we provide
|
---|
2480 | // our own implementations of malloc/free, we need to make sure that
|
---|
2481 | // the __libc_XXX variants also point to the same implementations.
|
---|
2482 | //-------------------------------------------------------------------
|
---|
2483 |
|
---|
2484 | extern "C" {
|
---|
2485 | #if COMPILER(GCC) && HAVE(__ATTRIBUTE__)
|
---|
2486 | // Potentially faster variants that use the gcc alias extension
|
---|
2487 | #define ALIAS(x) __attribute__ ((weak, alias (x)))
|
---|
2488 | void* __libc_malloc(size_t size) ALIAS("malloc");
|
---|
2489 | void __libc_free(void* ptr) ALIAS("free");
|
---|
2490 | void* __libc_realloc(void* ptr, size_t size) ALIAS("realloc");
|
---|
2491 | void* __libc_calloc(size_t n, size_t size) ALIAS("calloc");
|
---|
2492 | void __libc_cfree(void* ptr) ALIAS("cfree");
|
---|
2493 | void* __libc_memalign(size_t align, size_t s) ALIAS("memalign");
|
---|
2494 | void* __libc_valloc(size_t size) ALIAS("valloc");
|
---|
2495 | void* __libc_pvalloc(size_t size) ALIAS("pvalloc");
|
---|
2496 | int __posix_memalign(void** r, size_t a, size_t s) ALIAS("posix_memalign");
|
---|
2497 | #undef ALIAS
|
---|
2498 | #else
|
---|
2499 | // Portable wrappers
|
---|
2500 | void* __libc_malloc(size_t size) { return malloc(size); }
|
---|
2501 | void __libc_free(void* ptr) { free(ptr); }
|
---|
2502 | void* __libc_realloc(void* ptr, size_t size) { return realloc(ptr, size); }
|
---|
2503 | void* __libc_calloc(size_t n, size_t size) { return calloc(n, size); }
|
---|
2504 | void __libc_cfree(void* ptr) { cfree(ptr); }
|
---|
2505 | void* __libc_memalign(size_t align, size_t s) { return memalign(align, s); }
|
---|
2506 | void* __libc_valloc(size_t size) { return valloc(size); }
|
---|
2507 | void* __libc_pvalloc(size_t size) { return pvalloc(size); }
|
---|
2508 | int __posix_memalign(void** r, size_t a, size_t s) {
|
---|
2509 | return posix_memalign(r, a, s);
|
---|
2510 | }
|
---|
2511 | #endif
|
---|
2512 |
|
---|
2513 | }
|
---|
2514 |
|
---|
2515 | #endif
|
---|
2516 |
|
---|
2517 | #if defined(WTF_CHANGES) && PLATFORM(DARWIN)
|
---|
2518 | #include <wtf/HashSet.h>
|
---|
2519 |
|
---|
2520 | class FreeObjectFinder {
|
---|
2521 | const RemoteMemoryReader& m_reader;
|
---|
2522 | HashSet<void*> m_freeObjects;
|
---|
2523 |
|
---|
2524 | public:
|
---|
2525 | FreeObjectFinder(const RemoteMemoryReader& reader) : m_reader(reader) { }
|
---|
2526 |
|
---|
2527 | void visit(void* ptr) { m_freeObjects.add(ptr); }
|
---|
2528 | bool isFreeObject(void* ptr) const { return m_freeObjects.contains(ptr); }
|
---|
2529 | size_t freeObjectCount() const { return m_freeObjects.size(); }
|
---|
2530 |
|
---|
2531 | void findFreeObjects(TCMalloc_ThreadCache* threadCache)
|
---|
2532 | {
|
---|
2533 | for (; threadCache; threadCache = (threadCache->next_ ? m_reader(threadCache->next_) : 0))
|
---|
2534 | threadCache->enumerateFreeObjects(*this, m_reader);
|
---|
2535 | }
|
---|
2536 |
|
---|
2537 | void findFreeObjects(TCMalloc_Central_FreeListPadded* centralFreeList, size_t numSizes)
|
---|
2538 | {
|
---|
2539 | for (unsigned i = 0; i < numSizes; i++)
|
---|
2540 | centralFreeList[i].enumerateFreeObjects(*this, m_reader);
|
---|
2541 | }
|
---|
2542 | };
|
---|
2543 |
|
---|
2544 | class PageMapFreeObjectFinder {
|
---|
2545 | const RemoteMemoryReader& m_reader;
|
---|
2546 | FreeObjectFinder& m_freeObjectFinder;
|
---|
2547 |
|
---|
2548 | public:
|
---|
2549 | PageMapFreeObjectFinder(const RemoteMemoryReader& reader, FreeObjectFinder& freeObjectFinder)
|
---|
2550 | : m_reader(reader)
|
---|
2551 | , m_freeObjectFinder(freeObjectFinder)
|
---|
2552 | { }
|
---|
2553 |
|
---|
2554 | int visit(void* ptr) const
|
---|
2555 | {
|
---|
2556 | if (!ptr)
|
---|
2557 | return 1;
|
---|
2558 |
|
---|
2559 | Span* span = m_reader(reinterpret_cast<Span*>(ptr));
|
---|
2560 | if (span->free) {
|
---|
2561 | void* ptr = reinterpret_cast<void*>(span->start << kPageShift);
|
---|
2562 | m_freeObjectFinder.visit(ptr);
|
---|
2563 | } else if (span->sizeclass) {
|
---|
2564 | // Walk the free list of the small-object span, keeping track of each object seen
|
---|
2565 | for (void* nextObject = span->objects; nextObject; nextObject = *m_reader(reinterpret_cast<void**>(nextObject)))
|
---|
2566 | m_freeObjectFinder.visit(nextObject);
|
---|
2567 | }
|
---|
2568 | return span->length;
|
---|
2569 | }
|
---|
2570 | };
|
---|
2571 |
|
---|
2572 | class PageMapMemoryUsageRecorder {
|
---|
2573 | task_t m_task;
|
---|
2574 | void* m_context;
|
---|
2575 | unsigned m_typeMask;
|
---|
2576 | vm_range_recorder_t* m_recorder;
|
---|
2577 | const RemoteMemoryReader& m_reader;
|
---|
2578 | const FreeObjectFinder& m_freeObjectFinder;
|
---|
2579 | mutable HashSet<void*> m_seenPointers;
|
---|
2580 |
|
---|
2581 | public:
|
---|
2582 | PageMapMemoryUsageRecorder(task_t task, void* context, unsigned typeMask, vm_range_recorder_t* recorder, const RemoteMemoryReader& reader, const FreeObjectFinder& freeObjectFinder)
|
---|
2583 | : m_task(task)
|
---|
2584 | , m_context(context)
|
---|
2585 | , m_typeMask(typeMask)
|
---|
2586 | , m_recorder(recorder)
|
---|
2587 | , m_reader(reader)
|
---|
2588 | , m_freeObjectFinder(freeObjectFinder)
|
---|
2589 | { }
|
---|
2590 |
|
---|
2591 | int visit(void* ptr) const
|
---|
2592 | {
|
---|
2593 | if (!ptr)
|
---|
2594 | return 1;
|
---|
2595 |
|
---|
2596 | Span* span = m_reader(reinterpret_cast<Span*>(ptr));
|
---|
2597 | if (m_seenPointers.contains(ptr))
|
---|
2598 | return span->length;
|
---|
2599 | m_seenPointers.add(ptr);
|
---|
2600 |
|
---|
2601 | // Mark the memory used for the Span itself as an administrative region
|
---|
2602 | vm_range_t ptrRange = { reinterpret_cast<vm_address_t>(ptr), sizeof(Span) };
|
---|
2603 | if (m_typeMask & (MALLOC_PTR_REGION_RANGE_TYPE | MALLOC_ADMIN_REGION_RANGE_TYPE))
|
---|
2604 | (*m_recorder)(m_task, m_context, MALLOC_ADMIN_REGION_RANGE_TYPE, &ptrRange, 1);
|
---|
2605 |
|
---|
2606 | ptrRange.address = span->start << kPageShift;
|
---|
2607 | ptrRange.size = span->length * kPageSize;
|
---|
2608 |
|
---|
2609 | // Mark the memory region the span represents as candidates for containing pointers
|
---|
2610 | if (m_typeMask & (MALLOC_PTR_REGION_RANGE_TYPE | MALLOC_ADMIN_REGION_RANGE_TYPE))
|
---|
2611 | (*m_recorder)(m_task, m_context, MALLOC_PTR_REGION_RANGE_TYPE, &ptrRange, 1);
|
---|
2612 |
|
---|
2613 | if (!span->free && (m_typeMask & MALLOC_PTR_IN_USE_RANGE_TYPE)) {
|
---|
2614 | // If it's an allocated large object span, mark it as in use
|
---|
2615 | if (span->sizeclass == 0 && !m_freeObjectFinder.isFreeObject(reinterpret_cast<void*>(ptrRange.address)))
|
---|
2616 | (*m_recorder)(m_task, m_context, MALLOC_PTR_IN_USE_RANGE_TYPE, &ptrRange, 1);
|
---|
2617 | else if (span->sizeclass) {
|
---|
2618 | const size_t byteSize = ByteSizeForClass(span->sizeclass);
|
---|
2619 | unsigned totalObjects = (span->length << kPageShift) / byteSize;
|
---|
2620 | ASSERT(span->refcount <= totalObjects);
|
---|
2621 | char* ptr = reinterpret_cast<char*>(span->start << kPageShift);
|
---|
2622 |
|
---|
2623 | // Mark each allocated small object within the span as in use
|
---|
2624 | for (unsigned i = 0; i < totalObjects; i++) {
|
---|
2625 | char* thisObject = ptr + (i * byteSize);
|
---|
2626 | if (m_freeObjectFinder.isFreeObject(thisObject))
|
---|
2627 | continue;
|
---|
2628 |
|
---|
2629 | vm_range_t objectRange = { reinterpret_cast<vm_address_t>(thisObject), byteSize };
|
---|
2630 | (*m_recorder)(m_task, m_context, MALLOC_PTR_IN_USE_RANGE_TYPE, &objectRange, 1);
|
---|
2631 | }
|
---|
2632 | }
|
---|
2633 | }
|
---|
2634 |
|
---|
2635 | return span->length;
|
---|
2636 | }
|
---|
2637 | };
|
---|
2638 |
|
---|
2639 | 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)
|
---|
2640 | {
|
---|
2641 | RemoteMemoryReader memoryReader(task, reader);
|
---|
2642 |
|
---|
2643 | InitSizeClasses();
|
---|
2644 |
|
---|
2645 | FastMallocZone* mzone = memoryReader(reinterpret_cast<FastMallocZone*>(zoneAddress));
|
---|
2646 | TCMalloc_PageHeap* pageHeap = memoryReader(mzone->m_pageHeap);
|
---|
2647 | TCMalloc_ThreadCache** threadHeapsPointer = memoryReader(mzone->m_threadHeaps);
|
---|
2648 | TCMalloc_ThreadCache* threadHeaps = memoryReader(*threadHeapsPointer);
|
---|
2649 |
|
---|
2650 | TCMalloc_Central_FreeListPadded* centralCaches = memoryReader(mzone->m_centralCaches, sizeof(TCMalloc_Central_FreeListPadded) * kNumClasses);
|
---|
2651 |
|
---|
2652 | FreeObjectFinder finder(memoryReader);
|
---|
2653 | finder.findFreeObjects(threadHeaps);
|
---|
2654 | finder.findFreeObjects(centralCaches, kNumClasses);
|
---|
2655 |
|
---|
2656 | TCMalloc_PageHeap::PageMap* pageMap = &pageHeap->pagemap_;
|
---|
2657 | PageMapFreeObjectFinder pageMapFinder(memoryReader, finder);
|
---|
2658 | pageMap->visit(pageMapFinder, memoryReader);
|
---|
2659 |
|
---|
2660 | PageMapMemoryUsageRecorder usageRecorder(task, context, typeMask, recorder, memoryReader, finder);
|
---|
2661 | pageMap->visit(usageRecorder, memoryReader);
|
---|
2662 |
|
---|
2663 | return 0;
|
---|
2664 | }
|
---|
2665 |
|
---|
2666 | size_t FastMallocZone::size(malloc_zone_t*, const void*)
|
---|
2667 | {
|
---|
2668 | return 0;
|
---|
2669 | }
|
---|
2670 |
|
---|
2671 | void* FastMallocZone::zoneMalloc(malloc_zone_t*, size_t)
|
---|
2672 | {
|
---|
2673 | return 0;
|
---|
2674 | }
|
---|
2675 |
|
---|
2676 | void* FastMallocZone::zoneCalloc(malloc_zone_t*, size_t, size_t)
|
---|
2677 | {
|
---|
2678 | return 0;
|
---|
2679 | }
|
---|
2680 |
|
---|
2681 | void FastMallocZone::zoneFree(malloc_zone_t*, void*)
|
---|
2682 | {
|
---|
2683 | }
|
---|
2684 |
|
---|
2685 | void* FastMallocZone::zoneRealloc(malloc_zone_t*, void*, size_t)
|
---|
2686 | {
|
---|
2687 | return 0;
|
---|
2688 | }
|
---|
2689 |
|
---|
2690 |
|
---|
2691 | #undef malloc
|
---|
2692 | #undef free
|
---|
2693 | #undef realloc
|
---|
2694 | #undef calloc
|
---|
2695 |
|
---|
2696 | extern "C" {
|
---|
2697 | malloc_introspection_t jscore_fastmalloc_introspection = { &FastMallocZone::enumerate, &FastMallocZone::goodSize, &FastMallocZone::check, &FastMallocZone::print,
|
---|
2698 | &FastMallocZone::log, &FastMallocZone::forceLock, &FastMallocZone::forceUnlock, &FastMallocZone::statistics };
|
---|
2699 | }
|
---|
2700 |
|
---|
2701 | FastMallocZone::FastMallocZone(TCMalloc_PageHeap* pageHeap, TCMalloc_ThreadCache** threadHeaps, TCMalloc_Central_FreeListPadded* centralCaches)
|
---|
2702 | : m_pageHeap(pageHeap)
|
---|
2703 | , m_threadHeaps(threadHeaps)
|
---|
2704 | , m_centralCaches(centralCaches)
|
---|
2705 | {
|
---|
2706 | memset(&m_zone, 0, sizeof(m_zone));
|
---|
2707 | m_zone.zone_name = "JavaScriptCore FastMalloc";
|
---|
2708 | m_zone.size = &FastMallocZone::size;
|
---|
2709 | m_zone.malloc = &FastMallocZone::zoneMalloc;
|
---|
2710 | m_zone.calloc = &FastMallocZone::zoneCalloc;
|
---|
2711 | m_zone.realloc = &FastMallocZone::zoneRealloc;
|
---|
2712 | m_zone.free = &FastMallocZone::zoneFree;
|
---|
2713 | m_zone.valloc = &FastMallocZone::zoneValloc;
|
---|
2714 | m_zone.destroy = &FastMallocZone::zoneDestroy;
|
---|
2715 | m_zone.introspect = &jscore_fastmalloc_introspection;
|
---|
2716 | malloc_zone_register(&m_zone);
|
---|
2717 | }
|
---|
2718 |
|
---|
2719 |
|
---|
2720 | void FastMallocZone::init()
|
---|
2721 | {
|
---|
2722 | static FastMallocZone zone(getPageHeap(), &thread_heaps, static_cast<TCMalloc_Central_FreeListPadded*>(central_cache));
|
---|
2723 | }
|
---|
2724 |
|
---|
2725 | #endif
|
---|
2726 |
|
---|
2727 | #if WTF_CHANGES
|
---|
2728 | } // namespace WTF
|
---|
2729 | #endif
|
---|
2730 |
|
---|
2731 | #endif // USE_SYSTEM_MALLOC
|
---|