2 * This module contains the garbage collector implementation.
4 * Copyright: Copyright (C) 2001-2007 Digital Mars, www.digitalmars.com.
7 * This software is provided 'as-is', without any express or implied
8 * warranty. In no event will the authors be held liable for any damages
9 * arising from the use of this software.
11 * Permission is granted to anyone to use this software for any purpose,
12 * including commercial applications, and to alter it and redistribute it
13 * freely, in both source and binary form, subject to the following
16 * o The origin of this software must not be misrepresented; you must not
17 * claim that you wrote the original software. If you use this software
18 * in a product, an acknowledgment in the product documentation would be
19 * appreciated but is not required.
20 * o Altered source versions must be plainly marked as such, and must not
21 * be misrepresented as being the original software.
22 * o This notice may not be removed or altered from any source
24 * Authors: Walter Bright, David Friedman, Sean Kelly
29 // D Programming Language Garbage Collector implementation
31 /************** Debugging ***************************/
33 //debug = COLLECT_PRINTF; // turn on printf's
34 //debug = PTRCHECK; // more pointer checking
35 //debug = PTRCHECK2; // thorough but slow pointer checking
37 /*************** Configuration *********************/
39 version = STACKGROWSDOWN; // growing the stack means subtracting from the stack pointer
40 // (use for Intel X86 CPUs)
41 // else growing the stack means adding to the stack pointer
43 /***************************************************/
45 import rt.gc.cdgc.bits: GCBits;
46 import rt.gc.cdgc.stats: GCStats, Stats;
47 import dynarray = rt.gc.cdgc.dynarray;
48 import os = rt.gc.cdgc.os;
49 import opts = rt.gc.cdgc.opts;
51 import cstdlib = tango.stdc.stdlib;
52 import cstring = tango.stdc.string;
53 import cstdio = tango.stdc.stdio;
54 debug(COLLECT_PRINTF) alias cstdio.printf printf;
57 * This is a small optimization that proved it's usefulness. For small chunks
58 * or memory memset() seems to be slower (probably because of the call) that
59 * simply doing a simple loop to set the memory.
61 void memset(void* dst, int c, size_t n)
63 // This number (32) has been determined empirically
65 cstring.memset(dst, c, n);
68 auto p = cast(ubyte*)(dst);
75 // BUG: The following import will likely not work, since the gcc
76 // subdirectory is elsewhere. Instead, perhaps the functions
77 // could be declared directly or some other resolution could
79 static import gcc.builtins; // for __builtin_unwind_int
89 package enum BlkAttr : uint
91 FINALIZE = 0b0000_0001,
92 NO_SCAN = 0b0000_0010,
93 NO_MOVE = 0b0000_0100,
94 ALL_BITS = 0b1111_1111
97 package bool has_pointermap(uint attrs)
99 return !opts.options.conservative && !(attrs & BlkAttr.NO_SCAN);
102 private size_t round_up(size_t n, size_t to)
104 return (n + to - 1) / to;
109 alias void delegate(Object) DEvent;
110 alias void delegate( void*, void* ) scanFn;
111 enum { OPFAIL = ~cast(size_t)0 }
115 version (DigitalMars) version(OSX)
116 oid _d_osx_image_init();
118 void* rt_stackBottom();
120 void rt_finalize( void* p, bool det = true );
121 void rt_attachDisposeEvent(Object h, DEvent e);
122 bool rt_detachDisposeEvent(Object h, DEvent e);
123 void rt_scanStaticData( scanFn scan );
126 bool thread_needLock();
127 void thread_suspendAll();
128 void thread_resumeAll();
129 void thread_scanAll( scanFn fn, void* curStackTop = null );
131 void onOutOfMemoryError();
139 POOLSIZE = (4096*256),
153 B_PAGE, // start of large alloc
154 B_PAGEPLUS, // continuation of large alloc
174 int opCmp(in Range other)
176 if (pbot < other.pbot)
179 return cast(int)(pbot > other.pbot);
184 const uint binsize[B_MAX] = [ 16,32,64,128,256,512,1024,2048,4096 ];
185 const uint notbinsize[B_MAX] = [ ~(16u-1),~(32u-1),~(64u-1),~(128u-1),~(256u-1),
186 ~(512u-1),~(1024u-1),~(2048u-1),~(4096u-1) ];
189 /* ============================ GC =============================== */
192 class GCLock {} // just a dummy so we can get a global lock
203 // !=0 means don't scan stack
208 /// Turn off collections if > 0
211 // PID of the fork()ed process doing the mark() (0 if is not running)
214 /// min(pool.baseAddr)
216 /// max(pool.topAddr)
219 /// Total heap memory
224 /// Free list for each size
225 List*[B_MAX] free_list;
227 dynarray.DynArray!(void*) roots;
228 dynarray.DynArray!(Range) ranges;
229 dynarray.DynArray!(Pool*) pools;
234 // call locked if necessary
235 private T locked(T, alias Code)()
237 if (thread_needLock())
238 synchronized (gc.lock) return Code();
247 assert (gc !is null);
249 size_t total_mem = 0;
251 for (size_t i = 0; i < gc.pools.length; i++) {
252 Pool* pool = gc.pools[i];
255 assert(gc.min_addr == pool.baseAddr);
256 if (i + 1 < gc.pools.length)
257 assert(*pool < *gc.pools[i + 1]);
258 else if (i + 1 == gc.pools.length)
259 assert(gc.max_addr == pool.topAddr);
260 total_mem += pool.npages * PAGESIZE;
261 for (size_t pn = 0; pn < pool.npages; ++pn)
262 if (pool.pagetable[pn] == B_FREE)
263 free_mem += PAGESIZE;
266 gc.roots.Invariant();
267 gc.ranges.Invariant();
269 for (size_t i = 0; i < gc.ranges.length; i++) {
270 assert(gc.ranges[i].pbot);
271 assert(gc.ranges[i].ptop);
272 assert(gc.ranges[i].pbot <= gc.ranges[i].ptop);
275 for (size_t i = 0; i < B_PAGE; i++) {
276 for (List *list = gc.free_list[i]; list; list = list.next) {
277 auto pool = list.pool;
278 assert (pool !is null);
279 auto p = cast(byte*) list;
280 assert (p >= pool.baseAddr);
281 assert (p < pool.topAddr);
282 assert (pool.freebits.test((p - pool.baseAddr) / 16));
283 free_mem += binsize[i];
286 assert (gc.total_mem == total_mem);
287 assert (gc.free_mem == free_mem);
294 * Find Pool that pointer is in.
295 * Return null if not in a Pool.
296 * Assume pools is sorted.
298 Pool* findPool(void* p)
300 if (p < gc.min_addr || p >= gc.max_addr)
302 if (gc.pools.length == 0)
304 if (gc.pools.length == 1)
306 /// The pooltable[] is sorted by address, so do a binary search
308 size_t high = gc.pools.length - 1;
309 while (low <= high) {
310 size_t mid = (low + high) / 2;
311 auto pool = gc.pools[mid];
312 if (p < pool.baseAddr)
314 else if (p >= pool.topAddr)
325 * Determine the base address of the block containing p. If p is not a gc
326 * allocated pointer, return null.
328 BlkInfo getInfo(void* p)
331 Pool* pool = findPool(p);
335 info.base = pool.findBase(p);
336 if (info.base is null)
338 info.size = pool.findSize(info.base);
339 size_t bit_i = (info.base - pool.baseAddr) / 16;
340 info.attr = getAttr(pool, bit_i);
341 if (has_pointermap(info.attr)) {
342 info.size -= size_t.sizeof; // PointerMap bitmask
343 // Points to the PointerMap bitmask pointer, not user data
344 if (p >= (info.base + info.size)) {
348 if (opts.options.sentinel) {
349 info.base = sentinel_add(info.base);
350 // points to sentinel data, not user data
351 if (p < info.base || p >= sentinel_post(info.base))
353 info.size -= SENTINEL_EXTRA;
360 * Compute bin for size.
362 Bins findBin(size_t size)
406 * Allocate a new pool of at least size bytes.
407 * Sort it into pools.
408 * Mark all memory in the pool as B_FREE.
409 * Return the actual number of bytes reserved or 0 on error.
411 size_t reserve(size_t size)
414 size_t npages = round_up(size, PAGESIZE);
415 Pool* pool = newPool(npages);
419 return pool.npages * PAGESIZE;
424 * Minimizes physical memory usage by returning free pools to the OS.
426 * If full is false, keep some pools alive if the resulting free memory would
429 void minimize(bool full = true)
431 // Disabled if a parallel collection is in progress because the shared mark
432 // bits of the freed pool might be used by the mark process
433 if (gc.mark_proc_pid != 0)
436 if (gc.pools.length == 0)
439 for (size_t n = 0; n < gc.pools.length; n++)
441 Pool* pool = gc.pools[n];
443 for (pn = 0; pn < pool.npages; pn++)
445 if (cast(Bins)pool.pagetable[pn] != B_FREE)
448 if (pn < pool.npages)
451 size_t pool_size = pool.npages * PAGESIZE;
453 double percent_free = (gc.free_mem - pool_size) * 100.0 /
454 (gc.total_mem - pool_size);
455 if (percent_free < opts.options.min_free)
456 continue; // not enough free, don't remove this pool
458 gc.total_mem -= pool_size;
459 gc.free_mem -= pool_size;
462 gc.pools.remove_at(n);
465 gc.min_addr = gc.pools[0].baseAddr;
466 gc.max_addr = gc.pools[gc.pools.length - 1].topAddr;
471 * Allocate a chunk of memory that is larger than a page.
472 * Return null if out of memory.
474 void* bigAlloc(size_t npages, out Pool* pool, size_t* pn, bool* collected)
477 // This code could use some refinement when repeatedly
478 // allocating very large arrays.
482 for (size_t n = 0; n < gc.pools.length; n++)
485 *pn = pool.allocPages(npages);
487 return pool.baseAddr + *pn * PAGESIZE;
495 pool = newPool(npages);
497 return null; // let malloc handle the error
498 *pn = pool.allocPages(npages);
499 assert(*pn != OPFAIL);
500 return pool.baseAddr + *pn * PAGESIZE;
503 if (void* p = find_block())
510 size_t freedpages = fullcollectshell();
512 if (freedpages >= npages) {
513 if (void* p = find_block())
522 * Allocate a new pool with at least npages in it.
523 * Sort it into pools.
524 * Return null if failed.
526 Pool *newPool(size_t npages)
528 // Minimum of POOLSIZE
529 if (npages < POOLSIZE/PAGESIZE)
530 npages = POOLSIZE/PAGESIZE;
531 else if (npages > POOLSIZE/PAGESIZE)
533 // Give us 150% of requested size, so there's room to extend
534 auto n = npages + (npages >> 1);
535 if (n < size_t.max/PAGESIZE)
539 // Allocate successively larger pools up to 8 megs
542 size_t n = gc.pools.length;
544 n = 8; // cap pool size at 8 megs
545 n *= (POOLSIZE / PAGESIZE);
550 auto pool = cast(Pool*) cstdlib.calloc(1, Pool.sizeof);
553 pool.initialize(npages);
560 auto inserted_pool = *gc.pools.insert_sorted!("*a < *b")(pool);
561 if (inserted_pool is null) {
565 assert (inserted_pool is pool);
566 gc.min_addr = gc.pools[0].baseAddr;
567 gc.max_addr = gc.pools[gc.pools.length - 1].topAddr;
568 size_t pool_size = pool.topAddr - pool.baseAddr;
569 gc.total_mem += pool_size;
570 gc.free_mem += pool_size;
576 * Allocate a page of bin's.
580 int allocPage(Bins bin)
585 for (size_t n = 0; n < gc.pools.length; n++)
588 pn = pool.allocPages(1);
595 pool.pagetable[pn] = cast(ubyte)bin;
597 // Convert page to free list
598 size_t size = binsize[bin];
599 auto list_head = &gc.free_list[bin];
601 byte* p = pool.baseAddr + pn * PAGESIZE;
602 byte* ptop = p + PAGESIZE;
603 size_t bit_i = pn * (PAGESIZE / 16);
604 pool.freebits.set_group(bit_i, PAGESIZE / 16);
605 for (; p < ptop; p += size)
607 List* l = cast(List *) p;
617 * Search a range of memory values and mark any pointers into the GC pool using
618 * type information (bitmask of pointer locations).
620 void mark_range(void *pbot, void *ptop, size_t* pm_bitmask)
622 // TODO: make our own assert because assert uses the GC
623 assert (pbot <= ptop);
625 const BITS_PER_WORD = size_t.sizeof * 8;
627 void **p1 = cast(void **)pbot;
628 void **p2 = cast(void **)ptop;
630 bool changes = false;
632 size_t type_size = pm_bitmask[0];
633 size_t* pm_bits = pm_bitmask + 1;
634 bool has_type_info = type_size != 1 || pm_bits[0] != 1 || pm_bits[1] != 0;
636 //printf("marking range: %p -> %p\n", pbot, ptop);
637 for (; p1 + type_size <= p2; p1 += type_size) {
638 for (size_t n = 0; n < type_size; n++) {
639 // scan bit set for this word
641 !(pm_bits[n / BITS_PER_WORD] & (1 << (n % BITS_PER_WORD))))
646 if (p < gc.min_addr || p >= gc.max_addr)
649 if ((cast(size_t)p & ~(PAGESIZE-1)) == pcache)
652 Pool* pool = findPool(p);
655 size_t offset = cast(size_t)(p - pool.baseAddr);
657 size_t pn = offset / PAGESIZE;
658 Bins bin = cast(Bins)pool.pagetable[pn];
660 // Cache B_PAGE, B_PAGEPLUS and B_FREE lookups
662 pcache = cast(size_t)p & ~(PAGESIZE-1);
664 // Adjust bit to be at start of allocated memory block
666 bit_i = (offset & notbinsize[bin]) / 16;
667 else if (bin == B_PAGEPLUS)
673 while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
674 bit_i = pn * (PAGESIZE / 16);
676 else // Don't mark bits in B_FREE pages
679 if (!pool.mark.test(bit_i))
681 pool.mark.set(bit_i);
682 if (!pool.noscan.test(bit_i))
684 pool.scan.set(bit_i);
692 gc.any_changes = true;
696 * Return number of full pages free'd.
698 size_t fullcollectshell()
700 gc.stats.collection_started();
702 gc.stats.collection_finished();
704 // The purpose of the 'shell' is to ensure all the registers
705 // get put on the stack so they'll be scanned
710 gcc.builtins.__builtin_unwind_init();
717 uint eax,ecx,edx,ebx,ebp,esi,edi;
730 else version (X86_64)
732 ulong rax,rbx,rcx,rdx,rbp,rsi,rdi,r8,r9,r10,r11,r12,r13,r14,r15;
755 static assert( false, "Architecture not supported." );
766 result = fullcollect(sp);
789 size_t fullcollect(void *stackTop)
791 debug(COLLECT_PRINTF) printf("Gcx.fullcollect()\n");
793 // If eager allocation is used, we need to check first if there is a mark
794 // process running. If there isn't, we start a new one (see the next code
795 // block). If there is, we check if it's still running or already finished.
796 // If it's still running, we tell the caller process no memory has been
797 // recovered (it will allocated more to fulfill the current request). If
798 // the mark process is done, we lunch the sweep phase and hope enough
799 // memory is freed (if that not the case, the caller will allocate more
800 // memory and the next time it's exhausted it will run a new collection).
801 if (opts.options.eager_alloc) {
802 if (gc.mark_proc_pid != 0) { // there is a mark process in progress
803 os.WRes r = os.wait_pid(gc.mark_proc_pid, false); // don't block
804 assert (r != os.WRes.ERROR);
807 debug(COLLECT_PRINTF) printf("\t\tmark proc DONE\n");
808 gc.mark_proc_pid = 0;
810 case os.WRes.RUNNING:
811 debug(COLLECT_PRINTF) printf("\t\tmark proc RUNNING\n");
814 debug(COLLECT_PRINTF) printf("\t\tmark proc ERROR\n");
815 disable_fork(); // Try to keep going without forking
821 // We always need to stop the world to make threads save the CPU registers
822 // in the stack and prepare themselves for thread_scanAll()
824 gc.stats.world_stopped();
826 // If forking is enabled, we fork() and start a new mark phase in the
827 // child. The parent process will tell the caller that no memory could be
828 // recycled if eager allocation is used, allowing the mutator to keep going
829 // almost instantly (at the expense of more memory consumption because
830 // a new allocation will be triggered to fulfill the current request). If
831 // no eager allocation is used, the parent will wait for the mark phase to
832 // finish before returning control to the mutator, but other threads are
833 // restarted and may run in parallel with the mark phase (unless they
834 // allocate or use the GC themselves, in which case the global GC lock will
836 if (opts.options.fork) {
837 cstdio.fflush(null); // avoid duplicated FILE* output
838 os.pid_t child_pid = os.fork();
839 assert (child_pid != -1); // don't accept errors in non-release mode
841 case -1: // if fork() fails, fall-back to stop-the-world
844 case 0: // child process (i.e. the collectors mark phase)
847 break; // bogus, will never reach here
848 default: // parent process (i.e. the mutator)
849 // start the world again and wait for the mark phase to finish
851 gc.stats.world_started();
852 if (opts.options.eager_alloc) {
853 gc.mark_proc_pid = child_pid;
856 os.WRes r = os.wait_pid(child_pid); // block until it finishes
857 assert (r == os.WRes.DONE);
858 debug(COLLECT_PRINTF) printf("\t\tmark proc DONE (block)\n");
859 if (r == os.WRes.DONE)
861 debug(COLLECT_PRINTF) printf("\tmark() proc ERROR\n");
862 // If there was some error, try to keep going without forking
864 // Re-suspend the threads to do the marking in this process
866 gc.stats.world_stopped();
871 // If we reach here, we are using the standard stop-the-world collection,
872 // either because fork was disabled in the first place, or because it was
873 // disabled because of some error.
876 gc.stats.world_started();
885 void mark(void *stackTop)
887 debug(COLLECT_PRINTF) printf("\tmark()\n");
889 gc.any_changes = false;
891 for (size_t n = 0; n < gc.pools.length; n++)
893 Pool* pool = gc.pools[n];
894 pool.mark.copy(&pool.freebits);
898 /// Marks a range of memory in conservative mode.
899 void mark_conservative_range(void* pbot, void* ptop)
901 mark_range(pbot, ptop, PointerMap.init.bits.ptr);
904 rt_scanStaticData(&mark_conservative_range);
908 // Scan stacks and registers for each paused thread
909 thread_scanAll(&mark_conservative_range, stackTop);
913 debug(COLLECT_PRINTF) printf("scan roots[]\n");
914 mark_conservative_range(gc.roots.ptr, gc.roots.ptr + gc.roots.length);
917 debug(COLLECT_PRINTF) printf("scan ranges[]\n");
918 for (size_t n = 0; n < gc.ranges.length; n++)
920 debug(COLLECT_PRINTF) printf("\t%x .. %x\n", gc.ranges[n].pbot, gc.ranges[n].ptop);
921 mark_conservative_range(gc.ranges[n].pbot, gc.ranges[n].ptop);
924 debug(COLLECT_PRINTF) printf("\tscan heap\n");
925 while (gc.any_changes)
927 gc.any_changes = false;
928 for (size_t n = 0; n < gc.pools.length; n++)
934 Pool* pool = gc.pools[n];
936 bbase = pool.scan.base();
937 btop = bbase + pool.scan.nwords;
938 for (b = bbase; b < btop;)
954 o = pool.baseAddr + (b - bbase) * 32 * 16;
955 if (!(bitm & 0xFFFF))
960 for (; bitm; o += 16, bitm >>= 1)
965 pn = cast(size_t)(o - pool.baseAddr) / PAGESIZE;
966 bin = cast(Bins)pool.pagetable[pn];
968 if (opts.options.conservative)
969 mark_conservative_range(o, o + binsize[bin]);
971 auto end_of_blk = cast(size_t**)(o +
972 binsize[bin] - size_t.sizeof);
973 size_t* pm_bitmask = *end_of_blk;
974 mark_range(o, end_of_blk, pm_bitmask);
977 else if (bin == B_PAGE || bin == B_PAGEPLUS)
979 if (bin == B_PAGEPLUS)
981 while (pool.pagetable[pn - 1] != B_PAGE)
985 while (pn + u < pool.npages &&
986 pool.pagetable[pn + u] == B_PAGEPLUS)
989 size_t blk_size = u * PAGESIZE;
990 if (opts.options.conservative)
991 mark_conservative_range(o, o + blk_size);
993 auto end_of_blk = cast(size_t**)(o + blk_size -
995 size_t* pm_bitmask = *end_of_blk;
996 mark_range(o, end_of_blk, pm_bitmask);
1011 // Free up everything not marked
1012 debug(COLLECT_PRINTF) printf("\tsweep\n");
1015 gc.free_mem = 0; // will be recalculated
1016 size_t freedpages = 0;
1018 for (size_t n = 0; n < gc.pools.length; n++)
1020 Pool* pool = gc.pools[n];
1022 uint* bbase = pool.mark.base();
1024 for (pn = 0; pn < pool.npages; pn++, bbase += PAGESIZE / (32 * 16))
1026 Bins bin = cast(Bins)pool.pagetable[pn];
1030 auto size = binsize[bin];
1031 byte* p = pool.baseAddr + pn * PAGESIZE;
1032 byte* ptop = p + PAGESIZE;
1033 size_t bit_i = pn * (PAGESIZE/16);
1034 size_t bit_stride = size / 16;
1036 version(none) // BUG: doesn't work because freebits() must also be cleared
1038 // If free'd entire page
1039 if (bbase[0] == 0 && bbase[1] == 0 && bbase[2] == 0 &&
1040 bbase[3] == 0 && bbase[4] == 0 && bbase[5] == 0 &&
1041 bbase[6] == 0 && bbase[7] == 0)
1043 for (; p < ptop; p += size, bit_i += bit_stride)
1045 if (pool.finals.testClear(bit_i)) {
1046 if (opts.options.sentinel)
1047 rt_finalize(sentinel_add(p), false/*gc.no_stack > 0*/);
1049 rt_finalize(p, false/*gc.no_stack > 0*/);
1051 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1053 if (opts.options.mem_stomp)
1054 memset(p, 0xF3, size);
1056 pool.pagetable[pn] = B_FREE;
1061 for (; p < ptop; p += size, bit_i += bit_stride)
1063 if (!pool.mark.test(bit_i))
1065 if (opts.options.sentinel)
1066 sentinel_Invariant(sentinel_add(p));
1068 pool.freebits.set(bit_i);
1069 if (pool.finals.testClear(bit_i)) {
1070 if (opts.options.sentinel)
1071 rt_finalize(sentinel_add(p), false/*gc.no_stack > 0*/);
1073 rt_finalize(p, false/*gc.no_stack > 0*/);
1075 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1077 if (opts.options.mem_stomp)
1078 memset(p, 0xF3, size);
1084 else if (bin == B_PAGE)
1086 size_t bit_stride = PAGESIZE / 16;
1087 size_t bit_i = pn * bit_stride;
1088 if (!pool.mark.test(bit_i))
1090 byte *p = pool.baseAddr + pn * PAGESIZE;
1091 if (opts.options.sentinel)
1092 sentinel_Invariant(sentinel_add(p));
1093 if (pool.finals.testClear(bit_i)) {
1094 if (opts.options.sentinel)
1095 rt_finalize(sentinel_add(p), false/*gc.no_stack > 0*/);
1097 rt_finalize(p, false/*gc.no_stack > 0*/);
1099 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1101 debug(COLLECT_PRINTF) printf("\tcollecting big %p\n", p);
1102 pool.pagetable[pn] = B_FREE;
1103 pool.freebits.set_group(bit_i, PAGESIZE / 16);
1105 gc.free_mem += PAGESIZE;
1106 if (opts.options.mem_stomp)
1107 memset(p, 0xF3, PAGESIZE);
1108 while (pn + 1 < pool.npages && pool.pagetable[pn + 1] == B_PAGEPLUS)
1111 pool.pagetable[pn] = B_FREE;
1112 bit_i += bit_stride;
1113 pool.freebits.set_group(bit_i, PAGESIZE / 16);
1115 gc.free_mem += PAGESIZE;
1117 if (opts.options.mem_stomp)
1120 memset(p, 0xF3, PAGESIZE);
1125 else if (bin == B_FREE) {
1126 gc.free_mem += PAGESIZE;
1132 gc.free_list[] = null;
1134 // Free complete pages, rebuild free list
1135 debug(COLLECT_PRINTF) printf("\tfree complete pages\n");
1136 size_t recoveredpages = 0;
1137 for (size_t n = 0; n < gc.pools.length; n++)
1139 Pool* pool = gc.pools[n];
1140 for (size_t pn = 0; pn < pool.npages; pn++)
1142 Bins bin = cast(Bins)pool.pagetable[pn];
1148 size_t size = binsize[bin];
1149 size_t bit_stride = size / 16;
1150 size_t bit_base = pn * (PAGESIZE / 16);
1151 size_t bit_top = bit_base + (PAGESIZE / 16);
1155 for (; bit_i < bit_top; bit_i += bit_stride)
1157 if (!pool.freebits.test(bit_i))
1160 pool.pagetable[pn] = B_FREE;
1161 pool.freebits.set_group(bit_base, PAGESIZE / 16);
1163 gc.free_mem += PAGESIZE;
1167 p = pool.baseAddr + pn * PAGESIZE;
1168 for (u = 0; u < PAGESIZE; u += size)
1170 bit_i = bit_base + u / 16;
1171 if (pool.freebits.test(bit_i))
1173 assert ((p+u) >= pool.baseAddr);
1174 assert ((p+u) < pool.topAddr);
1175 List* list = cast(List*) (p + u);
1176 // avoid unnecesary writes (it really saves time)
1177 if (list.next != gc.free_list[bin])
1178 list.next = gc.free_list[bin];
1179 if (list.pool != pool)
1181 gc.free_list[bin] = list;
1182 gc.free_mem += binsize[bin];
1189 debug(COLLECT_PRINTF) printf("recovered pages = %d\n", recoveredpages);
1190 debug(COLLECT_PRINTF) printf("\tfree'd %u bytes, %u pages from %u pools\n", freed, freedpages, gc.pools.length);
1192 return freedpages + recoveredpages;
1199 uint getAttr(Pool* pool, size_t bit_i)
1207 if (pool.finals.test(bit_i))
1208 attrs |= BlkAttr.FINALIZE;
1209 if (pool.noscan.test(bit_i))
1210 attrs |= BlkAttr.NO_SCAN;
1211 // if (pool.nomove.test(bit_i))
1212 // attrs |= BlkAttr.NO_MOVE;
1220 void setAttr(Pool* pool, size_t bit_i, uint mask)
1227 if (mask & BlkAttr.FINALIZE)
1229 pool.finals.set(bit_i);
1231 if (mask & BlkAttr.NO_SCAN)
1233 pool.noscan.set(bit_i);
1235 // if (mask & BlkAttr.NO_MOVE)
1237 // if (!pool.nomove.nbits)
1238 // pool.nomove.alloc(pool.mark.nbits);
1239 // pool.nomove.set(bit_i);
1247 void clrAttr(Pool* pool, size_t bit_i, uint mask)
1254 if (mask & BlkAttr.FINALIZE)
1255 pool.finals.clear(bit_i);
1256 if (mask & BlkAttr.NO_SCAN)
1257 pool.noscan.clear(bit_i);
1258 // if (mask & BlkAttr.NO_MOVE && pool.nomove.nbits)
1259 // pool.nomove.clear(bit_i);
1265 // we have to disable both options, as eager_alloc assumes fork is enabled
1266 opts.options.fork = false;
1267 opts.options.eager_alloc = false;
1274 gc.stack_bottom = cast(char*)&dummy;
1275 opts.parse(cstdlib.getenv("D_GC_OPTS"));
1276 // If we are going to fork, make sure we have the needed OS support
1277 if (opts.options.fork)
1278 opts.options.fork = os.HAVE_SHARED && os.HAVE_FORK;
1279 // Eager allocation is only possible when forking
1280 if (!opts.options.fork)
1281 opts.options.eager_alloc = false;
1282 gc.lock = GCLock.classinfo;
1284 setStackBottom(rt_stackBottom());
1285 gc.stats = Stats(gc);
1286 if (opts.options.prealloc_npools) {
1287 size_t pages = round_up(opts.options.prealloc_psize, PAGESIZE);
1288 for (size_t i = 0; i < opts.options.prealloc_npools; ++i)
1297 private void *malloc(size_t size, uint attrs, size_t* pm_bitmask)
1301 gc.stats.malloc_started(size, attrs, pm_bitmask);
1303 gc.stats.malloc_finished(p);
1308 if (opts.options.sentinel)
1309 size += SENTINEL_EXTRA;
1311 bool has_pm = has_pointermap(attrs);
1313 size += size_t.sizeof;
1316 // Cache previous binsize lookup - Dave Fladebo.
1317 static size_t lastsize = -1;
1318 static Bins lastbin;
1319 if (size == lastsize)
1323 bin = findBin(size);
1329 size_t bit_i = void;
1330 size_t capacity = void; // to figure out where to store the bitmask
1331 bool collected = false;
1334 p = gc.free_list[bin];
1337 if (!allocPage(bin) && !gc.disabled) // try to find a new page
1339 if (!thread_needLock())
1341 /* Then we haven't locked it yet. Be sure
1342 * and gc.lock for a collection, since a finalizer
1343 * may start a new thread.
1345 synchronized (gc.lock)
1350 else if (!fullcollectshell()) // collect to find a new page
1356 if (!gc.free_list[bin] && !allocPage(bin))
1358 newPool(1); // allocate new pool to find a new page
1359 // TODO: hint allocPage() to use the pool we just created
1360 int result = allocPage(bin);
1362 onOutOfMemoryError();
1364 p = gc.free_list[bin];
1366 capacity = binsize[bin];
1368 // Return next item from free list
1369 List* list = cast(List*) p;
1370 assert ((cast(byte*)list) >= list.pool.baseAddr);
1371 assert ((cast(byte*)list) < list.pool.topAddr);
1372 gc.free_list[bin] = list.next;
1374 bit_i = (p - pool.baseAddr) / 16;
1375 assert (pool.freebits.test(bit_i));
1376 pool.freebits.clear(bit_i);
1377 if (!(attrs & BlkAttr.NO_SCAN))
1378 memset(p + size, 0, capacity - size);
1379 if (opts.options.mem_stomp)
1380 memset(p, 0xF0, size);
1385 size_t npages = round_up(size, PAGESIZE);
1386 p = bigAlloc(npages, pool, &pn, &collected);
1388 onOutOfMemoryError();
1389 assert (pool !is null);
1391 capacity = npages * PAGESIZE;
1392 bit_i = pn * (PAGESIZE / 16);
1393 pool.freebits.clear(bit_i);
1394 pool.pagetable[pn] = B_PAGE;
1396 memset(&pool.pagetable[pn + 1], B_PAGEPLUS, npages - 1);
1397 p = pool.baseAddr + pn * PAGESIZE;
1398 memset(cast(char *)p + size, 0, npages * PAGESIZE - size);
1399 if (opts.options.mem_stomp)
1400 memset(p, 0xF1, size);
1404 // Store the bit mask AFTER SENTINEL_POST
1405 // TODO: store it BEFORE, so the bitmask is protected too
1407 auto end_of_blk = cast(size_t**)(p + capacity - size_t.sizeof);
1408 *end_of_blk = pm_bitmask;
1409 size -= size_t.sizeof;
1412 if (opts.options.sentinel) {
1413 size -= SENTINEL_EXTRA;
1414 p = sentinel_add(p);
1415 sentinel_init(p, size);
1419 setAttr(pool, bit_i, attrs);
1420 assert (bin >= B_PAGE || !pool.freebits.test(bit_i));
1423 gc.free_mem -= capacity;
1425 // If there is not enough free memory, allocate a new pool big enough
1426 // to have at least the min_free% of the total heap free. If there is
1427 // too much free memory, try to free some empty pools.
1428 double percent_free = gc.free_mem * 100.0 / gc.total_mem;
1429 if (percent_free < opts.options.min_free) {
1430 auto pool_size = gc.total_mem * 1.0 / opts.options.min_free
1432 newPool(round_up(cast(size_t)pool_size, PAGESIZE));
1445 private void *calloc(size_t size, uint attrs, size_t* pm_bitmask)
1449 void *p = malloc(size, attrs, pm_bitmask);
1458 private void *realloc(void *p, size_t size, uint attrs,
1471 p = malloc(size, attrs, pm_bitmask);
1475 Pool* pool = findPool(p);
1479 // Set or retrieve attributes as appropriate
1480 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1482 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1483 setAttr(pool, bit_i, attrs);
1486 attrs = getAttr(pool, bit_i);
1488 void* blk_base_addr = pool.findBase(p);
1489 size_t blk_size = pool.findSize(p);
1490 bool has_pm = has_pointermap(attrs);
1491 size_t pm_bitmask_size = 0;
1493 pm_bitmask_size = size_t.sizeof;
1494 // Retrieve pointer map bit mask if appropriate
1495 if (pm_bitmask is null) {
1496 auto end_of_blk = cast(size_t**)(blk_base_addr +
1497 blk_size - size_t.sizeof);
1498 pm_bitmask = *end_of_blk;
1502 if (opts.options.sentinel)
1504 sentinel_Invariant(p);
1505 size_t sentinel_stored_size = *sentinel_size(p);
1506 if (sentinel_stored_size != size)
1508 void* p2 = malloc(size, attrs, pm_bitmask);
1509 if (sentinel_stored_size < size)
1510 size = sentinel_stored_size;
1511 cstring.memcpy(p2, p, size);
1517 size += pm_bitmask_size;
1518 if (blk_size >= PAGESIZE && size >= PAGESIZE)
1520 auto psz = blk_size / PAGESIZE;
1521 auto newsz = round_up(size, PAGESIZE);
1525 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
1530 if (opts.options.mem_stomp)
1531 memset(p + size - pm_bitmask_size, 0xF2,
1532 blk_size - size - pm_bitmask_size);
1533 pool.freePages(pagenum + newsz, psz - newsz);
1534 auto new_blk_size = (PAGESIZE * newsz);
1535 gc.free_mem += blk_size - new_blk_size;
1536 // update the size cache, assuming that is very likely the
1537 // size of this block will be queried in the near future
1538 pool.update_cache(p, new_blk_size);
1540 auto end_of_blk = cast(size_t**)(blk_base_addr +
1541 new_blk_size - pm_bitmask_size);
1542 *end_of_blk = pm_bitmask;
1546 else if (pagenum + newsz <= pool.npages)
1548 // Attempt to expand in place
1549 for (size_t i = pagenum + psz; 1;)
1551 if (i == pagenum + newsz)
1553 if (opts.options.mem_stomp)
1554 memset(p + blk_size - pm_bitmask_size,
1555 0xF0, size - blk_size
1557 memset(pool.pagetable + pagenum +
1558 psz, B_PAGEPLUS, newsz - psz);
1559 auto new_blk_size = (PAGESIZE * newsz);
1560 gc.free_mem -= new_blk_size - blk_size;
1561 // update the size cache, assuming that is very
1562 // likely the size of this block will be queried in
1564 pool.update_cache(p, new_blk_size);
1566 auto end_of_blk = cast(size_t**)(
1567 blk_base_addr + new_blk_size -
1569 *end_of_blk = pm_bitmask;
1573 if (i == pool.npages)
1577 if (pool.pagetable[i] != B_FREE)
1583 // if new size is bigger or less than half
1584 if (blk_size < size || blk_size > size * 2)
1586 size -= pm_bitmask_size;
1587 blk_size -= pm_bitmask_size;
1588 void* p2 = malloc(size, attrs, pm_bitmask);
1589 if (blk_size < size)
1591 cstring.memcpy(p2, p, size);
1601 * Attempt to in-place enlarge the memory block pointed to by p by at least
1602 * min_size beyond its current capacity, up to a maximum of max_size. This
1603 * does not attempt to move the memory block (like realloc() does).
1606 * 0 if could not extend p,
1607 * total size of entire memory block if successful.
1609 private size_t extend(void* p, size_t minsize, size_t maxsize)
1612 assert( minsize <= maxsize );
1616 if (opts.options.sentinel)
1619 Pool* pool = findPool(p);
1623 // Retrieve attributes
1624 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1625 uint attrs = getAttr(pool, bit_i);
1627 void* blk_base_addr = pool.findBase(p);
1628 size_t blk_size = pool.findSize(p);
1629 bool has_pm = has_pointermap(attrs);
1630 size_t* pm_bitmask = null;
1631 size_t pm_bitmask_size = 0;
1633 pm_bitmask_size = size_t.sizeof;
1634 // Retrieve pointer map bit mask
1635 auto end_of_blk = cast(size_t**)(blk_base_addr +
1636 blk_size - size_t.sizeof);
1637 pm_bitmask = *end_of_blk;
1639 minsize += size_t.sizeof;
1640 maxsize += size_t.sizeof;
1643 if (blk_size < PAGESIZE)
1644 return 0; // cannot extend buckets
1646 auto psz = blk_size / PAGESIZE;
1647 auto minsz = round_up(minsize, PAGESIZE);
1648 auto maxsz = round_up(maxsize, PAGESIZE);
1650 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
1653 for (sz = 0; sz < maxsz; sz++)
1655 auto i = pagenum + psz + sz;
1656 if (i == pool.npages)
1658 if (pool.pagetable[i] != B_FREE)
1668 size_t new_size = (psz + sz) * PAGESIZE;
1670 if (opts.options.mem_stomp)
1671 memset(p + blk_size - pm_bitmask_size, 0xF0,
1672 new_size - blk_size - pm_bitmask_size);
1673 memset(pool.pagetable + pagenum + psz, B_PAGEPLUS, sz);
1676 gc.free_mem -= new_size - blk_size;
1677 // update the size cache, assuming that is very likely the size of this
1678 // block will be queried in the near future
1679 pool.update_cache(p, new_size);
1682 new_size -= size_t.sizeof;
1683 auto end_of_blk = cast(size_t**)(blk_base_addr + new_size);
1684 *end_of_blk = pm_bitmask;
1693 private void free(void *p)
1702 // Find which page it is in
1704 if (!pool) // if not one of ours
1706 if (opts.options.sentinel) {
1707 sentinel_Invariant(p);
1708 p = sentinel_sub(p);
1710 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1711 bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1712 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1714 bin = cast(Bins)pool.pagetable[pagenum];
1715 if (bin == B_PAGE) // if large alloc
1720 pool.freebits.set_group(bit_i, PAGESIZE / 16);
1721 while (++n < pool.npages && pool.pagetable[n] == B_PAGEPLUS)
1723 size_t size = npages * PAGESIZE;
1724 if (opts.options.mem_stomp)
1725 memset(p, 0xF2, size);
1726 pool.freePages(pagenum, npages);
1727 gc.free_mem += size;
1728 // just in case we were caching this pointer
1729 pool.clear_cache(p);
1734 List* list = cast(List*) p;
1736 if (opts.options.mem_stomp)
1737 memset(p, 0xF2, binsize[bin]);
1739 list.next = gc.free_list[bin];
1741 gc.free_list[bin] = list;
1742 pool.freebits.set(bit_i);
1743 gc.free_mem += binsize[bin];
1745 double percent_free = gc.free_mem * 100.0 / gc.total_mem;
1746 if (percent_free > opts.options.min_free)
1752 * Determine the allocated size of pointer p. If p is an interior pointer
1753 * or not a gc allocated pointer, return 0.
1755 private size_t sizeOf(void *p)
1759 if (opts.options.sentinel)
1760 p = sentinel_sub(p);
1762 Pool* pool = findPool(p);
1766 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
1767 uint attrs = getAttr(pool, biti);
1769 size_t size = pool.findSize(p);
1770 size_t pm_bitmask_size = 0;
1771 if (has_pointermap(attrs))
1772 pm_bitmask_size = size_t.sizeof;
1774 if (opts.options.sentinel) {
1775 // Check for interior pointer
1777 // 1) size is a power of 2 for less than PAGESIZE values
1778 // 2) base of memory pool is aligned on PAGESIZE boundary
1779 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
1781 return size - SENTINEL_EXTRA - pm_bitmask_size;
1784 if (p == gc.p_cache)
1785 return gc.size_cache;
1787 // Check for interior pointer
1789 // 1) size is a power of 2 for less than PAGESIZE values
1790 // 2) base of memory pool is aligned on PAGESIZE boundary
1791 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
1795 gc.size_cache = size - pm_bitmask_size;
1797 return gc.size_cache;
1803 * Verify that pointer p:
1804 * 1) belongs to this memory pool
1805 * 2) points to the start of an allocated piece of memory
1806 * 3) is not on a free list
1808 private void checkNoSync(void *p)
1812 if (opts.options.sentinel)
1813 sentinel_Invariant(p);
1821 if (opts.options.sentinel)
1822 p = sentinel_sub(p);
1825 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1826 bin = cast(Bins)pool.pagetable[pagenum];
1827 assert(bin <= B_PAGE);
1828 size = binsize[bin];
1829 assert((cast(size_t)p & (size - 1)) == 0);
1835 // Check that p is not on a free list
1836 for (List* list = gc.free_list[bin]; list; list = list.next)
1838 assert(cast(void*)list != p);
1849 private void setStackBottom(void *p)
1851 version (STACKGROWSDOWN)
1853 //p = (void *)((uint *)p + 4);
1854 if (p > gc.stack_bottom)
1856 gc.stack_bottom = p;
1861 //p = (void *)((uint *)p - 4);
1862 if (p < gc.stack_bottom)
1864 gc.stack_bottom = cast(char*)p;
1871 * Retrieve statistics about garbage collection.
1872 * Useful for debugging and tuning.
1874 private GCStats getStats()
1884 for (n = 0; n < gc.pools.length; n++)
1886 Pool* pool = gc.pools[n];
1887 psize += pool.npages * PAGESIZE;
1888 for (size_t j = 0; j < pool.npages; j++)
1890 Bins bin = cast(Bins)pool.pagetable[j];
1893 else if (bin == B_PAGE)
1895 else if (bin < B_PAGE)
1900 for (n = 0; n < B_PAGE; n++)
1902 for (List* list = gc.free_list[n]; list; list = list.next)
1903 flsize += binsize[n];
1906 usize = bsize - flsize;
1908 stats.poolsize = psize;
1909 stats.usedsize = bsize - flsize;
1910 stats.freelistsize = flsize;
1914 /******************* weak-reference support *********************/
1916 private struct WeakPointer
1920 void ondestroy(Object r)
1922 assert(r is reference);
1923 // lock for memory consistency (parallel readers)
1924 // also ensures that weakpointerDestroy can be called while another
1925 // thread is freeing the reference with "delete"
1926 return locked!(void, () {
1933 * Create a weak pointer to the given object.
1934 * Returns a pointer to an opaque struct allocated in C memory.
1936 void* weakpointerCreate( Object r )
1940 // must be allocated in C memory
1941 // 1. to hide the reference from the GC
1942 // 2. the GC doesn't scan delegates added by rt_attachDisposeEvent
1944 auto wp = cast(WeakPointer*)(cstdlib.malloc(WeakPointer.sizeof));
1946 onOutOfMemoryError();
1948 rt_attachDisposeEvent(r, &wp.ondestroy);
1955 * Destroy a weak pointer returned by weakpointerCreate().
1956 * If null is passed, nothing happens.
1958 void weakpointerDestroy( void* p )
1962 auto wp = cast(WeakPointer*)p;
1963 // must be extra careful about the GC or parallel threads
1964 // finalizing the reference at the same time
1965 return locked!(void, () {
1967 rt_detachDisposeEvent(wp.reference, &wp.ondestroy);
1974 * Query a weak pointer and return either the object passed to
1975 * weakpointerCreate, or null if it was free'd in the meantime.
1976 * If null is passed, null is returned.
1978 Object weakpointerGet( void* p )
1982 // NOTE: could avoid the lock by using Fawzi style GC counters but
1983 // that'd require core.sync.Atomic and lots of care about memory
1984 // consistency it's an optional optimization see
1985 // http://dsource.org/projects/tango/browser/trunk/user/tango/core/Lifetime.d?rev=5100#L158
1986 return locked!(Object, () {
1987 return (cast(WeakPointer*)p).reference;
1993 /* ============================ Pool =============================== */
2000 GCBits mark; // entries already scanned, or should not be scanned
2001 GCBits scan; // entries that need to be scanned
2002 GCBits freebits; // entries that are on the free list
2003 GCBits finals; // entries that need finalizer run on them
2004 GCBits noscan; // entries that should not be scanned
2009 /// Cache for findSize()
2013 void clear_cache(void* ptr = null)
2015 if (ptr is null || ptr is this.cached_ptr) {
2016 this.cached_ptr = null;
2017 this.cached_size = 0;
2021 void update_cache(void* ptr, size_t size)
2023 this.cached_ptr = ptr;
2024 this.cached_size = size;
2027 void initialize(size_t npages)
2029 size_t poolsize = npages * PAGESIZE;
2030 assert(poolsize >= POOLSIZE);
2031 baseAddr = cast(byte *) os.alloc(poolsize);
2033 // Some of the code depends on page alignment of memory pools
2034 assert((cast(size_t)baseAddr & (PAGESIZE - 1)) == 0);
2041 topAddr = baseAddr + poolsize;
2043 size_t nbits = cast(size_t)poolsize / 16;
2045 // if the GC will run in parallel in a fork()ed process, we need to
2046 // share the mark bits
2047 os.Vis vis = os.Vis.PRIV;
2048 if (opts.options.fork)
2049 vis = os.Vis.SHARED;
2050 mark.alloc(nbits, vis); // shared between mark and sweep
2051 freebits.alloc(nbits); // not used by the mark phase
2052 scan.alloc(nbits); // only used in the mark phase
2053 finals.alloc(nbits); // not used by the mark phase
2054 noscan.alloc(nbits); // mark phase *MUST* have a snapshot
2056 // all is free when we start
2059 // avoid accidental sweeping of new pools while using eager allocation
2060 if (gc.mark_proc_pid)
2063 pagetable = cast(ubyte*) cstdlib.malloc(npages);
2065 onOutOfMemoryError();
2066 memset(pagetable, B_FREE, npages);
2068 this.npages = npages;
2080 result = os.dealloc(baseAddr, npages * PAGESIZE);
2088 // See Gcx.Dtor() for the rationale of the null check.
2090 cstdlib.free(pagetable);
2092 os.Vis vis = os.Vis.PRIV;
2093 if (opts.options.fork)
2094 vis = os.Vis.SHARED;
2113 //freebits.Invariant();
2114 //finals.Invariant();
2115 //noscan.Invariant();
2119 //if (baseAddr + npages * PAGESIZE != topAddr)
2120 //printf("baseAddr = %p, npages = %d, topAddr = %p\n", baseAddr, npages, topAddr);
2121 assert(baseAddr + npages * PAGESIZE == topAddr);
2124 for (size_t i = 0; i < npages; i++)
2126 Bins bin = cast(Bins)pagetable[i];
2127 assert(bin < B_MAX);
2133 * Allocate n pages from Pool.
2134 * Returns OPFAIL on failure.
2136 size_t allocPages(size_t n)
2142 for (i = 0; i < npages; i++)
2144 if (pagetable[i] == B_FREE)
2157 * Free npages pages starting with pagenum.
2159 void freePages(size_t pagenum, size_t npages)
2161 memset(&pagetable[pagenum], B_FREE, npages);
2166 * Find base address of block containing pointer p.
2167 * Returns null if the pointer doesn't belong to this pool
2169 void* findBase(void *p)
2171 size_t offset = cast(size_t)(p - this.baseAddr);
2172 size_t pagenum = offset / PAGESIZE;
2173 Bins bin = cast(Bins)this.pagetable[pagenum];
2174 // Adjust bit to be at start of allocated memory block
2176 return this.baseAddr + (offset & notbinsize[bin]);
2177 if (bin == B_PAGEPLUS) {
2179 --pagenum, offset -= PAGESIZE;
2180 } while (cast(Bins)this.pagetable[pagenum] == B_PAGEPLUS);
2181 return this.baseAddr + (offset & (offset.max ^ (PAGESIZE-1)));
2183 // we are in a B_FREE page
2189 * Find size of pointer p.
2190 * Returns 0 if p doesn't belong to this pool if if it's block size is less
2193 size_t findSize(void *p)
2195 size_t pagenum = cast(size_t)(p - this.baseAddr) / PAGESIZE;
2196 Bins bin = cast(Bins)this.pagetable[pagenum];
2198 return binsize[bin];
2199 if (this.cached_ptr == p)
2200 return this.cached_size;
2201 size_t i = pagenum + 1;
2202 for (; i < this.npages; i++)
2203 if (this.pagetable[i] != B_PAGEPLUS)
2205 this.cached_ptr = p;
2206 this.cached_size = (i - pagenum) * PAGESIZE;
2207 return this.cached_size;
2212 * Used for sorting pools
2214 int opCmp(in Pool other)
2216 if (baseAddr < other.baseAddr)
2219 return cast(int)(baseAddr > other.baseAddr);
2224 /* ============================ SENTINEL =============================== */
2227 const size_t SENTINEL_PRE = cast(size_t) 0xF4F4F4F4F4F4F4F4UL; // 32 or 64 bits
2228 const ubyte SENTINEL_POST = 0xF5; // 8 bits
2229 const uint SENTINEL_EXTRA = 2 * size_t.sizeof + 1;
2232 size_t* sentinel_size(void *p) { return &(cast(size_t *)p)[-2]; }
2233 size_t* sentinel_pre(void *p) { return &(cast(size_t *)p)[-1]; }
2234 ubyte* sentinel_post(void *p) { return &(cast(ubyte *)p)[*sentinel_size(p)]; }
2237 void sentinel_init(void *p, size_t size)
2239 *sentinel_size(p) = size;
2240 *sentinel_pre(p) = SENTINEL_PRE;
2241 *sentinel_post(p) = SENTINEL_POST;
2245 void sentinel_Invariant(void *p)
2247 if (*sentinel_pre(p) != SENTINEL_PRE ||
2248 *sentinel_post(p) != SENTINEL_POST)
2253 void *sentinel_add(void *p)
2255 return p + 2 * size_t.sizeof;
2259 void *sentinel_sub(void *p)
2261 return p - 2 * size_t.sizeof;
2266 /* ============================ C Public Interface ======================== */
2269 private int _termCleanupLevel=1;
2273 /// sets the cleanup level done by gc
2276 /// 2: fullCollect ignoring stack roots (might crash daemonThreads)
2277 /// result !=0 if the value was invalid
2278 int gc_setTermCleanupLevel(int cLevel)
2280 if (cLevel<0 || cLevel>2) return cLevel;
2281 _termCleanupLevel=cLevel;
2285 /// returns the cleanup level done by gc
2286 int gc_getTermCleanupLevel()
2288 return _termCleanupLevel;
2293 scope (exit) assert (Invariant());
2294 gc = cast(GC*) cstdlib.calloc(1, GC.sizeof);
2297 version (DigitalMars) version(OSX) {
2298 _d_osx_image_init();
2300 // NOTE: The GC must initialize the thread library
2301 // before its first collection.
2307 assert (Invariant());
2308 if (_termCleanupLevel<1) {
2310 } else if (_termCleanupLevel==2){
2311 // a more complete cleanup
2312 // NOTE: There may be daemons threads still running when this routine is
2313 // called. If so, cleaning memory out from under then is a good
2314 // way to make them crash horribly.
2315 // Often this probably doesn't matter much since the app is
2316 // supposed to be shutting down anyway, but for example tests might
2317 // crash (and be considerd failed even if the test was ok).
2318 // thus this is not the default and should be enabled by
2319 // I'm disabling cleanup for now until I can think about it some
2322 // not really a 'collect all' -- still scans static data area, roots,
2324 return locked!(void, () {
2330 // default (safe) clenup
2331 return locked!(void, () {
2339 return locked!(void, () {
2340 assert (Invariant()); scope (exit) assert (Invariant());
2341 assert (gc.disabled > 0);
2348 return locked!(void, () {
2349 assert (Invariant()); scope (exit) assert (Invariant());
2356 return locked!(void, () {
2357 assert (Invariant()); scope (exit) assert (Invariant());
2365 return locked!(void, () {
2366 assert (Invariant()); scope (exit) assert (Invariant());
2371 uint gc_getAttr(void* p)
2375 return locked!(uint, () {
2376 assert (Invariant()); scope (exit) assert (Invariant());
2377 Pool* pool = findPool(p);
2380 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2381 return getAttr(pool, bit_i);
2385 uint gc_setAttr(void* p, uint attrs)
2389 return locked!(uint, () {
2390 assert (Invariant()); scope (exit) assert (Invariant());
2391 Pool* pool = findPool(p);
2394 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2395 uint old_attrs = getAttr(pool, bit_i);
2396 setAttr(pool, bit_i, attrs);
2401 uint gc_clrAttr(void* p, uint attrs)
2405 return locked!(uint, () {
2406 assert (Invariant()); scope (exit) assert (Invariant());
2407 Pool* pool = findPool(p);
2410 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2411 uint old_attrs = getAttr(pool, bit_i);
2412 clrAttr(pool, bit_i, attrs);
2417 void* gc_malloc(size_t size, uint attrs = 0,
2418 PointerMap ptrmap = PointerMap.init)
2422 return locked!(void*, () {
2423 assert (Invariant()); scope (exit) assert (Invariant());
2424 return malloc(size, attrs, ptrmap.bits.ptr);
2428 void* gc_calloc(size_t size, uint attrs = 0,
2429 PointerMap ptrmap = PointerMap.init)
2433 return locked!(void*, () {
2434 assert (Invariant()); scope (exit) assert (Invariant());
2435 return calloc(size, attrs, ptrmap.bits.ptr);
2439 void* gc_realloc(void* p, size_t size, uint attrs = 0,
2440 PointerMap ptrmap = PointerMap.init)
2442 return locked!(void*, () {
2443 assert (Invariant()); scope (exit) assert (Invariant());
2444 return realloc(p, size, attrs, ptrmap.bits.ptr);
2448 size_t gc_extend(void* p, size_t min_size, size_t max_size)
2450 return locked!(size_t, () {
2451 assert (Invariant()); scope (exit) assert (Invariant());
2452 return extend(p, min_size, max_size);
2456 size_t gc_reserve(size_t size)
2460 return locked!(size_t, () {
2461 assert (Invariant()); scope (exit) assert (Invariant());
2462 return reserve(size);
2466 void gc_free(void* p)
2470 return locked!(void, () {
2471 assert (Invariant()); scope (exit) assert (Invariant());
2476 void* gc_addrOf(void* p)
2480 return locked!(void*, () {
2481 assert (Invariant()); scope (exit) assert (Invariant());
2482 Pool* pool = findPool(p);
2485 return pool.findBase(p);
2489 size_t gc_sizeOf(void* p)
2493 return locked!(size_t, () {
2494 assert (Invariant()); scope (exit) assert (Invariant());
2499 BlkInfo gc_query(void* p)
2502 return BlkInfo.init;
2503 return locked!(BlkInfo, () {
2504 assert (Invariant()); scope (exit) assert (Invariant());
2509 // NOTE: This routine is experimental. The stats or function name may change
2510 // before it is made officially available.
2513 return locked!(GCStats, () {
2514 assert (Invariant()); scope (exit) assert (Invariant());
2519 void gc_addRoot(void* p)
2523 return locked!(void, () {
2524 assert (Invariant()); scope (exit) assert (Invariant());
2525 if (gc.roots.append(p) is null)
2526 onOutOfMemoryError();
2530 void gc_addRange(void* p, size_t size)
2532 if (p is null || size == 0)
2534 return locked!(void, () {
2535 assert (Invariant()); scope (exit) assert (Invariant());
2536 if (gc.ranges.append(Range(p, p + size)) is null)
2537 onOutOfMemoryError();
2541 void gc_removeRoot(void* p)
2545 return locked!(void, () {
2546 assert (Invariant()); scope (exit) assert (Invariant());
2547 bool r = gc.roots.remove(p);
2552 void gc_removeRange(void* p)
2556 return locked!(void, () {
2557 assert (Invariant()); scope (exit) assert (Invariant());
2558 bool r = gc.ranges.remove(Range(p, null));
2563 void* gc_weakpointerCreate(Object r)
2565 // weakpointers do their own locking
2566 return weakpointerCreate(r);
2569 void gc_weakpointerDestroy(void* wp)
2571 // weakpointers do their own locking
2572 weakpointerDestroy(wp);
2575 Object gc_weakpointerGet(void* wp)
2577 // weakpointers do their own locking
2578 return weakpointerGet(wp);
2582 // vim: set et sw=4 sts=4 :