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 /// Free list for each size
220 List*[B_MAX] free_list;
222 dynarray.DynArray!(void*) roots;
223 dynarray.DynArray!(Range) ranges;
224 dynarray.DynArray!(Pool*) pools;
229 // call locked if necessary
230 private T locked(T, alias Code)()
232 if (thread_needLock())
233 synchronized (gc.lock) return Code();
242 assert (gc !is null);
244 for (size_t i = 0; i < gc.pools.length; i++) {
245 Pool* pool = gc.pools[i];
248 assert(gc.min_addr == pool.baseAddr);
249 if (i + 1 < gc.pools.length)
250 assert(*pool < *gc.pools[i + 1]);
251 else if (i + 1 == gc.pools.length)
252 assert(gc.max_addr == pool.topAddr);
255 gc.roots.Invariant();
256 gc.ranges.Invariant();
258 for (size_t i = 0; i < gc.ranges.length; i++) {
259 assert(gc.ranges[i].pbot);
260 assert(gc.ranges[i].ptop);
261 assert(gc.ranges[i].pbot <= gc.ranges[i].ptop);
264 for (size_t i = 0; i < B_PAGE; i++) {
265 for (List *list = gc.free_list[i]; list; list = list.next) {
266 auto pool = list.pool;
267 assert (pool !is null);
268 auto p = cast(byte*) list;
269 assert (p >= pool.baseAddr);
270 assert (p < pool.topAddr);
271 assert (pool.freebits.test((p - pool.baseAddr) / 16));
280 * Find Pool that pointer is in.
281 * Return null if not in a Pool.
282 * Assume pools is sorted.
284 Pool* findPool(void* p)
286 if (p < gc.min_addr || p >= gc.max_addr)
288 if (gc.pools.length == 0)
290 if (gc.pools.length == 1)
292 /// The pooltable[] is sorted by address, so do a binary search
294 size_t high = gc.pools.length - 1;
295 while (low <= high) {
296 size_t mid = (low + high) / 2;
297 auto pool = gc.pools[mid];
298 if (p < pool.baseAddr)
300 else if (p >= pool.topAddr)
311 * Determine the base address of the block containing p. If p is not a gc
312 * allocated pointer, return null.
314 BlkInfo getInfo(void* p)
317 Pool* pool = findPool(p);
321 info.base = pool.findBase(p);
322 if (info.base is null)
324 info.size = pool.findSize(info.base);
325 size_t bit_i = (info.base - pool.baseAddr) / 16;
326 info.attr = getAttr(pool, bit_i);
327 if (has_pointermap(info.attr)) {
328 info.size -= size_t.sizeof; // PointerMap bitmask
329 // Points to the PointerMap bitmask pointer, not user data
330 if (p >= (info.base + info.size)) {
334 if (opts.options.sentinel) {
335 info.base = sentinel_add(info.base);
336 // points to sentinel data, not user data
337 if (p < info.base || p >= sentinel_post(info.base))
339 info.size -= SENTINEL_EXTRA;
346 * Compute bin for size.
348 Bins findBin(size_t size)
392 * Allocate a new pool of at least size bytes.
393 * Sort it into pools.
394 * Mark all memory in the pool as B_FREE.
395 * Return the actual number of bytes reserved or 0 on error.
397 size_t reserve(size_t size)
400 size_t npages = round_up(size, PAGESIZE);
401 Pool* pool = newPool(npages);
405 return pool.npages * PAGESIZE;
410 * Minimizes physical memory usage by returning free pools to the OS.
414 // Disabled if a parallel collection is in progress because the shared mark
415 // bits of the freed pool might be used by the mark process
416 if (gc.mark_proc_pid != 0)
423 for (n = 0; n < gc.pools.length; n++)
426 for (pn = 0; pn < pool.npages; pn++)
428 if (cast(Bins)pool.pagetable[pn] != B_FREE)
431 if (pn < pool.npages)
435 gc.pools.remove_at(n);
438 gc.min_addr = gc.pools[0].baseAddr;
439 gc.max_addr = gc.pools[gc.pools.length - 1].topAddr;
444 * Allocate a chunk of memory that is larger than a page.
445 * Return null if out of memory.
447 void* bigAlloc(size_t size, out Pool* pool)
456 npages = round_up(size, PAGESIZE);
460 // This code could use some refinement when repeatedly
461 // allocating very large arrays.
463 for (n = 0; n < gc.pools.length; n++)
466 pn = pool.allocPages(npages);
481 freedpages = fullcollectshell();
482 if (freedpages >= gc.pools.length * ((POOLSIZE / PAGESIZE) / 4))
487 // Release empty pools to prevent bloat
490 pool = newPool(npages);
496 pn = pool.allocPages(npages);
497 assert(pn != OPFAIL);
500 // Release empty pools to prevent bloat
503 pool = newPool(npages);
506 pn = pool.allocPages(npages);
507 assert(pn != OPFAIL);
517 size_t bit_i = pn * (PAGESIZE / 16);
518 pool.freebits.clear(bit_i);
519 pool.pagetable[pn] = B_PAGE;
521 memset(&pool.pagetable[pn + 1], B_PAGEPLUS, npages - 1);
522 p = pool.baseAddr + pn * PAGESIZE;
523 memset(cast(char *)p + size, 0, npages * PAGESIZE - size);
524 if (opts.options.mem_stomp)
525 memset(p, 0xF1, size);
529 return null; // let mallocNoSync handle the error
534 * Allocate a new pool with at least npages in it.
535 * Sort it into pools.
536 * Return null if failed.
538 Pool *newPool(size_t npages)
540 // Minimum of POOLSIZE
541 if (npages < POOLSIZE/PAGESIZE)
542 npages = POOLSIZE/PAGESIZE;
543 else if (npages > POOLSIZE/PAGESIZE)
545 // Give us 150% of requested size, so there's room to extend
546 auto n = npages + (npages >> 1);
547 if (n < size_t.max/PAGESIZE)
551 // Allocate successively larger pools up to 8 megs
554 size_t n = gc.pools.length;
556 n = 8; // cap pool size at 8 megs
557 n *= (POOLSIZE / PAGESIZE);
562 auto pool = cast(Pool*) cstdlib.calloc(1, Pool.sizeof);
565 pool.initialize(npages);
572 auto inserted_pool = *gc.pools.insert_sorted!("*a < *b")(pool);
573 if (inserted_pool is null) {
577 assert (inserted_pool is pool);
578 gc.min_addr = gc.pools[0].baseAddr;
579 gc.max_addr = gc.pools[gc.pools.length - 1].topAddr;
585 * Allocate a page of bin's.
589 int allocPage(Bins bin)
594 for (size_t n = 0; n < gc.pools.length; n++)
597 pn = pool.allocPages(1);
604 pool.pagetable[pn] = cast(ubyte)bin;
606 // Convert page to free list
607 size_t size = binsize[bin];
608 auto list_head = &gc.free_list[bin];
610 byte* p = pool.baseAddr + pn * PAGESIZE;
611 byte* ptop = p + PAGESIZE;
612 size_t bit_i = pn * (PAGESIZE / 16);
613 pool.freebits.set_group(bit_i, PAGESIZE / 16);
614 for (; p < ptop; p += size)
616 List* l = cast(List *) p;
626 * Search a range of memory values and mark any pointers into the GC pool using
627 * type information (bitmask of pointer locations).
629 void mark_range(void *pbot, void *ptop, size_t* pm_bitmask)
631 // TODO: make our own assert because assert uses the GC
632 assert (pbot <= ptop);
634 const BITS_PER_WORD = size_t.sizeof * 8;
636 void **p1 = cast(void **)pbot;
637 void **p2 = cast(void **)ptop;
639 bool changes = false;
641 size_t type_size = pm_bitmask[0];
642 size_t* pm_bits = pm_bitmask + 1;
643 bool has_type_info = type_size != 1 || pm_bits[0] != 1 || pm_bits[1] != 0;
645 //printf("marking range: %p -> %p\n", pbot, ptop);
646 for (; p1 + type_size <= p2; p1 += type_size) {
647 for (size_t n = 0; n < type_size; n++) {
648 // scan bit set for this word
650 !(pm_bits[n / BITS_PER_WORD] & (1 << (n % BITS_PER_WORD))))
655 if (p < gc.min_addr || p >= gc.max_addr)
658 if ((cast(size_t)p & ~(PAGESIZE-1)) == pcache)
661 Pool* pool = findPool(p);
664 size_t offset = cast(size_t)(p - pool.baseAddr);
666 size_t pn = offset / PAGESIZE;
667 Bins bin = cast(Bins)pool.pagetable[pn];
669 // Cache B_PAGE, B_PAGEPLUS and B_FREE lookups
671 pcache = cast(size_t)p & ~(PAGESIZE-1);
673 // Adjust bit to be at start of allocated memory block
675 bit_i = (offset & notbinsize[bin]) / 16;
676 else if (bin == B_PAGEPLUS)
682 while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
683 bit_i = pn * (PAGESIZE / 16);
685 else // Don't mark bits in B_FREE pages
688 if (!pool.mark.test(bit_i))
690 pool.mark.set(bit_i);
691 if (!pool.noscan.test(bit_i))
693 pool.scan.set(bit_i);
701 gc.any_changes = true;
705 * Return number of full pages free'd.
707 size_t fullcollectshell()
709 gc.stats.collection_started();
711 gc.stats.collection_finished();
713 // The purpose of the 'shell' is to ensure all the registers
714 // get put on the stack so they'll be scanned
719 gcc.builtins.__builtin_unwind_init();
726 uint eax,ecx,edx,ebx,ebp,esi,edi;
739 else version (X86_64)
741 ulong rax,rbx,rcx,rdx,rbp,rsi,rdi,r8,r9,r10,r11,r12,r13,r14,r15;
764 static assert( false, "Architecture not supported." );
775 result = fullcollect(sp);
798 size_t fullcollect(void *stackTop)
800 debug(COLLECT_PRINTF) printf("Gcx.fullcollect()\n");
802 // If eager allocation is used, we need to check first if there is a mark
803 // process running. If there isn't, we start a new one (see the next code
804 // block). If there is, we check if it's still running or already finished.
805 // If it's still running, we tell the caller process no memory has been
806 // recovered (it will allocated more to fulfill the current request). If
807 // the mark process is done, we lunch the sweep phase and hope enough
808 // memory is freed (if that not the case, the caller will allocate more
809 // memory and the next time it's exhausted it will run a new collection).
810 if (opts.options.eager_alloc) {
811 if (gc.mark_proc_pid != 0) { // there is a mark process in progress
812 os.WRes r = os.wait_pid(gc.mark_proc_pid, false); // don't block
813 assert (r != os.WRes.ERROR);
816 debug(COLLECT_PRINTF) printf("\t\tmark proc DONE\n");
817 gc.mark_proc_pid = 0;
819 case os.WRes.RUNNING:
820 debug(COLLECT_PRINTF) printf("\t\tmark proc RUNNING\n");
823 debug(COLLECT_PRINTF) printf("\t\tmark proc ERROR\n");
824 disable_fork(); // Try to keep going without forking
830 // We always need to stop the world to make threads save the CPU registers
831 // in the stack and prepare themselves for thread_scanAll()
833 gc.stats.world_stopped();
835 // If forking is enabled, we fork() and start a new mark phase in the
836 // child. The parent process will tell the caller that no memory could be
837 // recycled if eager allocation is used, allowing the mutator to keep going
838 // almost instantly (at the expense of more memory consumption because
839 // a new allocation will be triggered to fulfill the current request). If
840 // no eager allocation is used, the parent will wait for the mark phase to
841 // finish before returning control to the mutator, but other threads are
842 // restarted and may run in parallel with the mark phase (unless they
843 // allocate or use the GC themselves, in which case the global GC lock will
845 if (opts.options.fork) {
846 cstdio.fflush(null); // avoid duplicated FILE* output
847 os.pid_t child_pid = os.fork();
848 assert (child_pid != -1); // don't accept errors in non-release mode
850 case -1: // if fork() fails, fall-back to stop-the-world
853 case 0: // child process (i.e. the collectors mark phase)
856 break; // bogus, will never reach here
857 default: // parent process (i.e. the mutator)
858 // start the world again and wait for the mark phase to finish
860 gc.stats.world_started();
861 if (opts.options.eager_alloc) {
862 gc.mark_proc_pid = child_pid;
865 os.WRes r = os.wait_pid(child_pid); // block until it finishes
866 assert (r == os.WRes.DONE);
867 debug(COLLECT_PRINTF) printf("\t\tmark proc DONE (block)\n");
868 if (r == os.WRes.DONE)
870 debug(COLLECT_PRINTF) printf("\tmark() proc ERROR\n");
871 // If there was some error, try to keep going without forking
873 // Re-suspend the threads to do the marking in this process
875 gc.stats.world_stopped();
880 // If we reach here, we are using the standard stop-the-world collection,
881 // either because fork was disabled in the first place, or because it was
882 // disabled because of some error.
885 gc.stats.world_started();
894 void mark(void *stackTop)
896 debug(COLLECT_PRINTF) printf("\tmark()\n");
898 gc.any_changes = false;
900 for (size_t n = 0; n < gc.pools.length; n++)
902 Pool* pool = gc.pools[n];
903 pool.mark.copy(&pool.freebits);
907 /// Marks a range of memory in conservative mode.
908 void mark_conservative_range(void* pbot, void* ptop)
910 mark_range(pbot, ptop, PointerMap.init.bits.ptr);
913 rt_scanStaticData(&mark_conservative_range);
917 // Scan stacks and registers for each paused thread
918 thread_scanAll(&mark_conservative_range, stackTop);
922 debug(COLLECT_PRINTF) printf("scan roots[]\n");
923 mark_conservative_range(gc.roots.ptr, gc.roots.ptr + gc.roots.length);
926 debug(COLLECT_PRINTF) printf("scan ranges[]\n");
927 for (size_t n = 0; n < gc.ranges.length; n++)
929 debug(COLLECT_PRINTF) printf("\t%x .. %x\n", gc.ranges[n].pbot, gc.ranges[n].ptop);
930 mark_conservative_range(gc.ranges[n].pbot, gc.ranges[n].ptop);
933 debug(COLLECT_PRINTF) printf("\tscan heap\n");
934 while (gc.any_changes)
936 gc.any_changes = false;
937 for (size_t n = 0; n < gc.pools.length; n++)
943 Pool* pool = gc.pools[n];
945 bbase = pool.scan.base();
946 btop = bbase + pool.scan.nwords;
947 for (b = bbase; b < btop;)
963 o = pool.baseAddr + (b - bbase) * 32 * 16;
964 if (!(bitm & 0xFFFF))
969 for (; bitm; o += 16, bitm >>= 1)
974 pn = cast(size_t)(o - pool.baseAddr) / PAGESIZE;
975 bin = cast(Bins)pool.pagetable[pn];
977 if (opts.options.conservative)
978 mark_conservative_range(o, o + binsize[bin]);
980 auto end_of_blk = cast(size_t**)(o +
981 binsize[bin] - size_t.sizeof);
982 size_t* pm_bitmask = *end_of_blk;
983 mark_range(o, end_of_blk, pm_bitmask);
986 else if (bin == B_PAGE || bin == B_PAGEPLUS)
988 if (bin == B_PAGEPLUS)
990 while (pool.pagetable[pn - 1] != B_PAGE)
994 while (pn + u < pool.npages &&
995 pool.pagetable[pn + u] == B_PAGEPLUS)
998 size_t blk_size = u * PAGESIZE;
999 if (opts.options.conservative)
1000 mark_conservative_range(o, o + blk_size);
1002 auto end_of_blk = cast(size_t**)(o + blk_size -
1004 size_t* pm_bitmask = *end_of_blk;
1005 mark_range(o, end_of_blk, pm_bitmask);
1020 // Free up everything not marked
1021 debug(COLLECT_PRINTF) printf("\tsweep\n");
1024 size_t freedpages = 0;
1026 for (size_t n = 0; n < gc.pools.length; n++)
1028 Pool* pool = gc.pools[n];
1030 uint* bbase = pool.mark.base();
1032 for (pn = 0; pn < pool.npages; pn++, bbase += PAGESIZE / (32 * 16))
1034 Bins bin = cast(Bins)pool.pagetable[pn];
1038 auto size = binsize[bin];
1039 byte* p = pool.baseAddr + pn * PAGESIZE;
1040 byte* ptop = p + PAGESIZE;
1041 size_t bit_i = pn * (PAGESIZE/16);
1042 size_t bit_stride = size / 16;
1044 version(none) // BUG: doesn't work because freebits() must also be cleared
1046 // If free'd entire page
1047 if (bbase[0] == 0 && bbase[1] == 0 && bbase[2] == 0 &&
1048 bbase[3] == 0 && bbase[4] == 0 && bbase[5] == 0 &&
1049 bbase[6] == 0 && bbase[7] == 0)
1051 for (; p < ptop; p += size, bit_i += bit_stride)
1053 if (pool.finals.testClear(bit_i)) {
1054 if (opts.options.sentinel)
1055 rt_finalize(sentinel_add(p), false/*gc.no_stack > 0*/);
1057 rt_finalize(p, false/*gc.no_stack > 0*/);
1059 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1061 if (opts.options.mem_stomp)
1062 memset(p, 0xF3, size);
1064 pool.pagetable[pn] = B_FREE;
1069 for (; p < ptop; p += size, bit_i += bit_stride)
1071 if (!pool.mark.test(bit_i))
1073 if (opts.options.sentinel)
1074 sentinel_Invariant(sentinel_add(p));
1076 pool.freebits.set(bit_i);
1077 if (pool.finals.testClear(bit_i)) {
1078 if (opts.options.sentinel)
1079 rt_finalize(sentinel_add(p), false/*gc.no_stack > 0*/);
1081 rt_finalize(p, false/*gc.no_stack > 0*/);
1083 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1085 if (opts.options.mem_stomp)
1086 memset(p, 0xF3, size);
1092 else if (bin == B_PAGE)
1094 size_t bit_stride = PAGESIZE / 16;
1095 size_t bit_i = pn * bit_stride;
1096 if (!pool.mark.test(bit_i))
1098 byte *p = pool.baseAddr + pn * PAGESIZE;
1099 if (opts.options.sentinel)
1100 sentinel_Invariant(sentinel_add(p));
1101 if (pool.finals.testClear(bit_i)) {
1102 if (opts.options.sentinel)
1103 rt_finalize(sentinel_add(p), false/*gc.no_stack > 0*/);
1105 rt_finalize(p, false/*gc.no_stack > 0*/);
1107 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1109 debug(COLLECT_PRINTF) printf("\tcollecting big %p\n", p);
1110 pool.pagetable[pn] = B_FREE;
1111 pool.freebits.set_group(bit_i, PAGESIZE / 16);
1113 if (opts.options.mem_stomp)
1114 memset(p, 0xF3, PAGESIZE);
1115 while (pn + 1 < pool.npages && pool.pagetable[pn + 1] == B_PAGEPLUS)
1118 pool.pagetable[pn] = B_FREE;
1119 bit_i += bit_stride;
1120 pool.freebits.set_group(bit_i, PAGESIZE / 16);
1123 if (opts.options.mem_stomp)
1126 memset(p, 0xF3, PAGESIZE);
1135 gc.free_list[] = null;
1137 // Free complete pages, rebuild free list
1138 debug(COLLECT_PRINTF) printf("\tfree complete pages\n");
1139 size_t recoveredpages = 0;
1140 for (size_t n = 0; n < gc.pools.length; n++)
1142 Pool* pool = gc.pools[n];
1143 for (size_t pn = 0; pn < pool.npages; pn++)
1145 Bins bin = cast(Bins)pool.pagetable[pn];
1151 size_t size = binsize[bin];
1152 size_t bit_stride = size / 16;
1153 size_t bit_base = pn * (PAGESIZE / 16);
1154 size_t bit_top = bit_base + (PAGESIZE / 16);
1158 for (; bit_i < bit_top; bit_i += bit_stride)
1160 if (!pool.freebits.test(bit_i))
1163 pool.pagetable[pn] = B_FREE;
1164 pool.freebits.set_group(bit_base, PAGESIZE / 16);
1169 p = pool.baseAddr + pn * PAGESIZE;
1170 for (u = 0; u < PAGESIZE; u += size)
1172 bit_i = bit_base + u / 16;
1173 if (pool.freebits.test(bit_i))
1175 assert ((p+u) >= pool.baseAddr);
1176 assert ((p+u) < pool.topAddr);
1177 List* list = cast(List*) (p + u);
1178 // avoid unnecesary writes (it really saves time)
1179 if (list.next != gc.free_list[bin])
1180 list.next = gc.free_list[bin];
1181 if (list.pool != pool)
1183 gc.free_list[bin] = list;
1190 debug(COLLECT_PRINTF) printf("recovered pages = %d\n", recoveredpages);
1191 debug(COLLECT_PRINTF) printf("\tfree'd %u bytes, %u pages from %u pools\n", freed, freedpages, gc.pools.length);
1193 return freedpages + recoveredpages;
1200 uint getAttr(Pool* pool, size_t bit_i)
1208 if (pool.finals.test(bit_i))
1209 attrs |= BlkAttr.FINALIZE;
1210 if (pool.noscan.test(bit_i))
1211 attrs |= BlkAttr.NO_SCAN;
1212 // if (pool.nomove.test(bit_i))
1213 // attrs |= BlkAttr.NO_MOVE;
1221 void setAttr(Pool* pool, size_t bit_i, uint mask)
1228 if (mask & BlkAttr.FINALIZE)
1230 pool.finals.set(bit_i);
1232 if (mask & BlkAttr.NO_SCAN)
1234 pool.noscan.set(bit_i);
1236 // if (mask & BlkAttr.NO_MOVE)
1238 // if (!pool.nomove.nbits)
1239 // pool.nomove.alloc(pool.mark.nbits);
1240 // pool.nomove.set(bit_i);
1248 void clrAttr(Pool* pool, size_t bit_i, uint mask)
1255 if (mask & BlkAttr.FINALIZE)
1256 pool.finals.clear(bit_i);
1257 if (mask & BlkAttr.NO_SCAN)
1258 pool.noscan.clear(bit_i);
1259 // if (mask & BlkAttr.NO_MOVE && pool.nomove.nbits)
1260 // pool.nomove.clear(bit_i);
1266 // we have to disable both options, as eager_alloc assumes fork is enabled
1267 opts.options.fork = false;
1268 opts.options.eager_alloc = false;
1275 gc.stack_bottom = cast(char*)&dummy;
1276 opts.parse(cstdlib.getenv("D_GC_OPTS"));
1277 // If we are going to fork, make sure we have the needed OS support
1278 if (opts.options.fork)
1279 opts.options.fork = os.HAVE_SHARED && os.HAVE_FORK;
1280 // Eager allocation is only possible when forking
1281 if (!opts.options.fork)
1282 opts.options.eager_alloc = false;
1283 gc.lock = GCLock.classinfo;
1285 setStackBottom(rt_stackBottom());
1286 gc.stats = Stats(gc);
1287 if (opts.options.prealloc_npools) {
1288 size_t pages = round_up(opts.options.prealloc_psize, PAGESIZE);
1289 for (size_t i = 0; i < opts.options.prealloc_npools; ++i)
1298 private void *malloc(size_t size, uint attrs, size_t* pm_bitmask)
1302 gc.stats.malloc_started(size, attrs, pm_bitmask);
1304 gc.stats.malloc_finished(p);
1309 if (opts.options.sentinel)
1310 size += SENTINEL_EXTRA;
1312 bool has_pm = has_pointermap(attrs);
1314 size += size_t.sizeof;
1317 // Cache previous binsize lookup - Dave Fladebo.
1318 static size_t lastsize = -1;
1319 static Bins lastbin;
1320 if (size == lastsize)
1324 bin = findBin(size);
1330 size_t bit_i = void;
1331 size_t capacity = void; // to figure out where to store the bitmask
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
1355 if (!gc.free_list[bin] && !allocPage(bin))
1357 newPool(1); // allocate new pool to find a new page
1358 // TODO: hint allocPage() to use the pool we just created
1359 int result = allocPage(bin);
1361 onOutOfMemoryError();
1363 p = gc.free_list[bin];
1365 capacity = binsize[bin];
1367 // Return next item from free list
1368 List* list = cast(List*) p;
1369 assert ((cast(byte*)list) >= list.pool.baseAddr);
1370 assert ((cast(byte*)list) < list.pool.topAddr);
1371 gc.free_list[bin] = list.next;
1373 bit_i = (p - pool.baseAddr) / 16;
1374 assert (pool.freebits.test(bit_i));
1375 pool.freebits.clear(bit_i);
1376 if (!(attrs & BlkAttr.NO_SCAN))
1377 memset(p + size, 0, capacity - size);
1378 if (opts.options.mem_stomp)
1379 memset(p, 0xF0, size);
1383 p = bigAlloc(size, pool);
1385 onOutOfMemoryError();
1386 assert (pool !is null);
1387 size_t npages = round_up(size, PAGESIZE);
1388 capacity = npages * PAGESIZE;
1389 bit_i = (p - pool.baseAddr) / 16;
1392 // Store the bit mask AFTER SENTINEL_POST
1393 // TODO: store it BEFORE, so the bitmask is protected too
1395 auto end_of_blk = cast(size_t**)(p + capacity - size_t.sizeof);
1396 *end_of_blk = pm_bitmask;
1397 size -= size_t.sizeof;
1400 if (opts.options.sentinel) {
1401 size -= SENTINEL_EXTRA;
1402 p = sentinel_add(p);
1403 sentinel_init(p, size);
1407 setAttr(pool, bit_i, attrs);
1408 assert (bin >= B_PAGE || !pool.freebits.test(bit_i));
1418 private void *calloc(size_t size, uint attrs, size_t* pm_bitmask)
1422 void *p = malloc(size, attrs, pm_bitmask);
1431 private void *realloc(void *p, size_t size, uint attrs,
1444 p = malloc(size, attrs, pm_bitmask);
1448 Pool* pool = findPool(p);
1452 // Set or retrieve attributes as appropriate
1453 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1455 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1456 setAttr(pool, bit_i, attrs);
1459 attrs = getAttr(pool, bit_i);
1461 void* blk_base_addr = pool.findBase(p);
1462 size_t blk_size = pool.findSize(p);
1463 bool has_pm = has_pointermap(attrs);
1464 size_t pm_bitmask_size = 0;
1466 pm_bitmask_size = size_t.sizeof;
1467 // Retrieve pointer map bit mask if appropriate
1468 if (pm_bitmask is null) {
1469 auto end_of_blk = cast(size_t**)(blk_base_addr +
1470 blk_size - size_t.sizeof);
1471 pm_bitmask = *end_of_blk;
1475 if (opts.options.sentinel)
1477 sentinel_Invariant(p);
1478 size_t sentinel_stored_size = *sentinel_size(p);
1479 if (sentinel_stored_size != size)
1481 void* p2 = malloc(size, attrs, pm_bitmask);
1482 if (sentinel_stored_size < size)
1483 size = sentinel_stored_size;
1484 cstring.memcpy(p2, p, size);
1490 size += pm_bitmask_size;
1491 if (blk_size >= PAGESIZE && size >= PAGESIZE)
1493 auto psz = blk_size / PAGESIZE;
1494 auto newsz = round_up(size, PAGESIZE);
1498 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
1503 if (opts.options.mem_stomp)
1504 memset(p + size - pm_bitmask_size, 0xF2,
1505 blk_size - size - pm_bitmask_size);
1506 pool.freePages(pagenum + newsz, psz - newsz);
1507 auto new_blk_size = (PAGESIZE * newsz);
1508 // update the size cache, assuming that is very likely the
1509 // size of this block will be queried in the near future
1510 pool.update_cache(p, new_blk_size);
1512 auto end_of_blk = cast(size_t**)(blk_base_addr +
1513 new_blk_size - pm_bitmask_size);
1514 *end_of_blk = pm_bitmask;
1518 else if (pagenum + newsz <= pool.npages)
1520 // Attempt to expand in place
1521 for (size_t i = pagenum + psz; 1;)
1523 if (i == pagenum + newsz)
1525 if (opts.options.mem_stomp)
1526 memset(p + blk_size - pm_bitmask_size,
1527 0xF0, size - blk_size
1529 memset(pool.pagetable + pagenum +
1530 psz, B_PAGEPLUS, newsz - psz);
1531 auto new_blk_size = (PAGESIZE * newsz);
1532 // update the size cache, assuming that is very
1533 // likely the size of this block will be queried in
1535 pool.update_cache(p, new_blk_size);
1537 auto end_of_blk = cast(size_t**)(
1538 blk_base_addr + new_blk_size -
1540 *end_of_blk = pm_bitmask;
1544 if (i == pool.npages)
1548 if (pool.pagetable[i] != B_FREE)
1554 // if new size is bigger or less than half
1555 if (blk_size < size || blk_size > size * 2)
1557 size -= pm_bitmask_size;
1558 blk_size -= pm_bitmask_size;
1559 void* p2 = malloc(size, attrs, pm_bitmask);
1560 if (blk_size < size)
1562 cstring.memcpy(p2, p, size);
1572 * Attempt to in-place enlarge the memory block pointed to by p by at least
1573 * min_size beyond its current capacity, up to a maximum of max_size. This
1574 * does not attempt to move the memory block (like realloc() does).
1577 * 0 if could not extend p,
1578 * total size of entire memory block if successful.
1580 private size_t extend(void* p, size_t minsize, size_t maxsize)
1583 assert( minsize <= maxsize );
1587 if (opts.options.sentinel)
1590 Pool* pool = findPool(p);
1594 // Retrieve attributes
1595 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1596 uint attrs = getAttr(pool, bit_i);
1598 void* blk_base_addr = pool.findBase(p);
1599 size_t blk_size = pool.findSize(p);
1600 bool has_pm = has_pointermap(attrs);
1601 size_t* pm_bitmask = null;
1602 size_t pm_bitmask_size = 0;
1604 pm_bitmask_size = size_t.sizeof;
1605 // Retrieve pointer map bit mask
1606 auto end_of_blk = cast(size_t**)(blk_base_addr +
1607 blk_size - size_t.sizeof);
1608 pm_bitmask = *end_of_blk;
1610 minsize += size_t.sizeof;
1611 maxsize += size_t.sizeof;
1614 if (blk_size < PAGESIZE)
1615 return 0; // cannot extend buckets
1617 auto psz = blk_size / PAGESIZE;
1618 auto minsz = round_up(minsize, PAGESIZE);
1619 auto maxsz = round_up(maxsize, PAGESIZE);
1621 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
1624 for (sz = 0; sz < maxsz; sz++)
1626 auto i = pagenum + psz + sz;
1627 if (i == pool.npages)
1629 if (pool.pagetable[i] != B_FREE)
1639 size_t new_size = (psz + sz) * PAGESIZE;
1641 if (opts.options.mem_stomp)
1642 memset(p + blk_size - pm_bitmask_size, 0xF0,
1643 new_size - blk_size - pm_bitmask_size);
1644 memset(pool.pagetable + pagenum + psz, B_PAGEPLUS, sz);
1647 // update the size cache, assuming that is very likely the size of this
1648 // block will be queried in the near future
1649 pool.update_cache(p, new_size);
1652 new_size -= size_t.sizeof;
1653 auto end_of_blk = cast(size_t**)(blk_base_addr + new_size);
1654 *end_of_blk = pm_bitmask;
1663 private void free(void *p)
1672 // Find which page it is in
1674 if (!pool) // if not one of ours
1676 if (opts.options.sentinel) {
1677 sentinel_Invariant(p);
1678 p = sentinel_sub(p);
1680 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1681 bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1682 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1684 bin = cast(Bins)pool.pagetable[pagenum];
1685 if (bin == B_PAGE) // if large alloc
1690 pool.freebits.set_group(bit_i, PAGESIZE / 16);
1691 while (++n < pool.npages && pool.pagetable[n] == B_PAGEPLUS)
1693 if (opts.options.mem_stomp)
1694 memset(p, 0xF2, npages * PAGESIZE);
1695 pool.freePages(pagenum, npages);
1696 // just in case we were caching this pointer
1697 pool.clear_cache(p);
1702 List* list = cast(List*) p;
1704 if (opts.options.mem_stomp)
1705 memset(p, 0xF2, binsize[bin]);
1707 list.next = gc.free_list[bin];
1709 gc.free_list[bin] = list;
1710 pool.freebits.set(bit_i);
1716 * Determine the allocated size of pointer p. If p is an interior pointer
1717 * or not a gc allocated pointer, return 0.
1719 private size_t sizeOf(void *p)
1723 if (opts.options.sentinel)
1724 p = sentinel_sub(p);
1726 Pool* pool = findPool(p);
1730 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
1731 uint attrs = getAttr(pool, biti);
1733 size_t size = pool.findSize(p);
1734 size_t pm_bitmask_size = 0;
1735 if (has_pointermap(attrs))
1736 pm_bitmask_size = size_t.sizeof;
1738 if (opts.options.sentinel) {
1739 // Check for interior pointer
1741 // 1) size is a power of 2 for less than PAGESIZE values
1742 // 2) base of memory pool is aligned on PAGESIZE boundary
1743 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
1745 return size - SENTINEL_EXTRA - pm_bitmask_size;
1748 if (p == gc.p_cache)
1749 return gc.size_cache;
1751 // Check for interior pointer
1753 // 1) size is a power of 2 for less than PAGESIZE values
1754 // 2) base of memory pool is aligned on PAGESIZE boundary
1755 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
1759 gc.size_cache = size - pm_bitmask_size;
1761 return gc.size_cache;
1767 * Verify that pointer p:
1768 * 1) belongs to this memory pool
1769 * 2) points to the start of an allocated piece of memory
1770 * 3) is not on a free list
1772 private void checkNoSync(void *p)
1776 if (opts.options.sentinel)
1777 sentinel_Invariant(p);
1785 if (opts.options.sentinel)
1786 p = sentinel_sub(p);
1789 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1790 bin = cast(Bins)pool.pagetable[pagenum];
1791 assert(bin <= B_PAGE);
1792 size = binsize[bin];
1793 assert((cast(size_t)p & (size - 1)) == 0);
1799 // Check that p is not on a free list
1800 for (List* list = gc.free_list[bin]; list; list = list.next)
1802 assert(cast(void*)list != p);
1813 private void setStackBottom(void *p)
1815 version (STACKGROWSDOWN)
1817 //p = (void *)((uint *)p + 4);
1818 if (p > gc.stack_bottom)
1820 gc.stack_bottom = p;
1825 //p = (void *)((uint *)p - 4);
1826 if (p < gc.stack_bottom)
1828 gc.stack_bottom = cast(char*)p;
1835 * Retrieve statistics about garbage collection.
1836 * Useful for debugging and tuning.
1838 private GCStats getStats()
1848 for (n = 0; n < gc.pools.length; n++)
1850 Pool* pool = gc.pools[n];
1851 psize += pool.npages * PAGESIZE;
1852 for (size_t j = 0; j < pool.npages; j++)
1854 Bins bin = cast(Bins)pool.pagetable[j];
1857 else if (bin == B_PAGE)
1859 else if (bin < B_PAGE)
1864 for (n = 0; n < B_PAGE; n++)
1866 for (List* list = gc.free_list[n]; list; list = list.next)
1867 flsize += binsize[n];
1870 usize = bsize - flsize;
1872 stats.poolsize = psize;
1873 stats.usedsize = bsize - flsize;
1874 stats.freelistsize = flsize;
1878 /******************* weak-reference support *********************/
1880 private struct WeakPointer
1884 void ondestroy(Object r)
1886 assert(r is reference);
1887 // lock for memory consistency (parallel readers)
1888 // also ensures that weakpointerDestroy can be called while another
1889 // thread is freeing the reference with "delete"
1890 return locked!(void, () {
1897 * Create a weak pointer to the given object.
1898 * Returns a pointer to an opaque struct allocated in C memory.
1900 void* weakpointerCreate( Object r )
1904 // must be allocated in C memory
1905 // 1. to hide the reference from the GC
1906 // 2. the GC doesn't scan delegates added by rt_attachDisposeEvent
1908 auto wp = cast(WeakPointer*)(cstdlib.malloc(WeakPointer.sizeof));
1910 onOutOfMemoryError();
1912 rt_attachDisposeEvent(r, &wp.ondestroy);
1919 * Destroy a weak pointer returned by weakpointerCreate().
1920 * If null is passed, nothing happens.
1922 void weakpointerDestroy( void* p )
1926 auto wp = cast(WeakPointer*)p;
1927 // must be extra careful about the GC or parallel threads
1928 // finalizing the reference at the same time
1929 return locked!(void, () {
1931 rt_detachDisposeEvent(wp.reference, &wp.ondestroy);
1938 * Query a weak pointer and return either the object passed to
1939 * weakpointerCreate, or null if it was free'd in the meantime.
1940 * If null is passed, null is returned.
1942 Object weakpointerGet( void* p )
1946 // NOTE: could avoid the lock by using Fawzi style GC counters but
1947 // that'd require core.sync.Atomic and lots of care about memory
1948 // consistency it's an optional optimization see
1949 // http://dsource.org/projects/tango/browser/trunk/user/tango/core/Lifetime.d?rev=5100#L158
1950 return locked!(Object, () {
1951 return (cast(WeakPointer*)p).reference;
1957 /* ============================ Pool =============================== */
1964 GCBits mark; // entries already scanned, or should not be scanned
1965 GCBits scan; // entries that need to be scanned
1966 GCBits freebits; // entries that are on the free list
1967 GCBits finals; // entries that need finalizer run on them
1968 GCBits noscan; // entries that should not be scanned
1973 /// Cache for findSize()
1977 void clear_cache(void* ptr = null)
1979 if (ptr is null || ptr is this.cached_ptr) {
1980 this.cached_ptr = null;
1981 this.cached_size = 0;
1985 void update_cache(void* ptr, size_t size)
1987 this.cached_ptr = ptr;
1988 this.cached_size = size;
1991 void initialize(size_t npages)
1993 size_t poolsize = npages * PAGESIZE;
1994 assert(poolsize >= POOLSIZE);
1995 baseAddr = cast(byte *) os.alloc(poolsize);
1997 // Some of the code depends on page alignment of memory pools
1998 assert((cast(size_t)baseAddr & (PAGESIZE - 1)) == 0);
2005 topAddr = baseAddr + poolsize;
2007 size_t nbits = cast(size_t)poolsize / 16;
2009 // if the GC will run in parallel in a fork()ed process, we need to
2010 // share the mark bits
2011 os.Vis vis = os.Vis.PRIV;
2012 if (opts.options.fork)
2013 vis = os.Vis.SHARED;
2014 mark.alloc(nbits, vis); // shared between mark and sweep
2015 freebits.alloc(nbits); // not used by the mark phase
2016 scan.alloc(nbits); // only used in the mark phase
2017 finals.alloc(nbits); // not used by the mark phase
2018 noscan.alloc(nbits); // mark phase *MUST* have a snapshot
2020 // all is free when we start
2023 // avoid accidental sweeping of new pools while using eager allocation
2024 if (gc.mark_proc_pid)
2027 pagetable = cast(ubyte*) cstdlib.malloc(npages);
2029 onOutOfMemoryError();
2030 memset(pagetable, B_FREE, npages);
2032 this.npages = npages;
2044 result = os.dealloc(baseAddr, npages * PAGESIZE);
2052 // See Gcx.Dtor() for the rationale of the null check.
2054 cstdlib.free(pagetable);
2056 os.Vis vis = os.Vis.PRIV;
2057 if (opts.options.fork)
2058 vis = os.Vis.SHARED;
2077 //freebits.Invariant();
2078 //finals.Invariant();
2079 //noscan.Invariant();
2083 //if (baseAddr + npages * PAGESIZE != topAddr)
2084 //printf("baseAddr = %p, npages = %d, topAddr = %p\n", baseAddr, npages, topAddr);
2085 assert(baseAddr + npages * PAGESIZE == topAddr);
2088 for (size_t i = 0; i < npages; i++)
2090 Bins bin = cast(Bins)pagetable[i];
2091 assert(bin < B_MAX);
2097 * Allocate n pages from Pool.
2098 * Returns OPFAIL on failure.
2100 size_t allocPages(size_t n)
2106 for (i = 0; i < npages; i++)
2108 if (pagetable[i] == B_FREE)
2121 * Free npages pages starting with pagenum.
2123 void freePages(size_t pagenum, size_t npages)
2125 memset(&pagetable[pagenum], B_FREE, npages);
2130 * Find base address of block containing pointer p.
2131 * Returns null if the pointer doesn't belong to this pool
2133 void* findBase(void *p)
2135 size_t offset = cast(size_t)(p - this.baseAddr);
2136 size_t pagenum = offset / PAGESIZE;
2137 Bins bin = cast(Bins)this.pagetable[pagenum];
2138 // Adjust bit to be at start of allocated memory block
2140 return this.baseAddr + (offset & notbinsize[bin]);
2141 if (bin == B_PAGEPLUS) {
2143 --pagenum, offset -= PAGESIZE;
2144 } while (cast(Bins)this.pagetable[pagenum] == B_PAGEPLUS);
2145 return this.baseAddr + (offset & (offset.max ^ (PAGESIZE-1)));
2147 // we are in a B_FREE page
2153 * Find size of pointer p.
2154 * Returns 0 if p doesn't belong to this pool if if it's block size is less
2157 size_t findSize(void *p)
2159 size_t pagenum = cast(size_t)(p - this.baseAddr) / PAGESIZE;
2160 Bins bin = cast(Bins)this.pagetable[pagenum];
2162 return binsize[bin];
2163 if (this.cached_ptr == p)
2164 return this.cached_size;
2165 size_t i = pagenum + 1;
2166 for (; i < this.npages; i++)
2167 if (this.pagetable[i] != B_PAGEPLUS)
2169 this.cached_ptr = p;
2170 this.cached_size = (i - pagenum) * PAGESIZE;
2171 return this.cached_size;
2176 * Used for sorting pools
2178 int opCmp(in Pool other)
2180 if (baseAddr < other.baseAddr)
2183 return cast(int)(baseAddr > other.baseAddr);
2188 /* ============================ SENTINEL =============================== */
2191 const size_t SENTINEL_PRE = cast(size_t) 0xF4F4F4F4F4F4F4F4UL; // 32 or 64 bits
2192 const ubyte SENTINEL_POST = 0xF5; // 8 bits
2193 const uint SENTINEL_EXTRA = 2 * size_t.sizeof + 1;
2196 size_t* sentinel_size(void *p) { return &(cast(size_t *)p)[-2]; }
2197 size_t* sentinel_pre(void *p) { return &(cast(size_t *)p)[-1]; }
2198 ubyte* sentinel_post(void *p) { return &(cast(ubyte *)p)[*sentinel_size(p)]; }
2201 void sentinel_init(void *p, size_t size)
2203 *sentinel_size(p) = size;
2204 *sentinel_pre(p) = SENTINEL_PRE;
2205 *sentinel_post(p) = SENTINEL_POST;
2209 void sentinel_Invariant(void *p)
2211 if (*sentinel_pre(p) != SENTINEL_PRE ||
2212 *sentinel_post(p) != SENTINEL_POST)
2217 void *sentinel_add(void *p)
2219 return p + 2 * size_t.sizeof;
2223 void *sentinel_sub(void *p)
2225 return p - 2 * size_t.sizeof;
2230 /* ============================ C Public Interface ======================== */
2233 private int _termCleanupLevel=1;
2237 /// sets the cleanup level done by gc
2240 /// 2: fullCollect ignoring stack roots (might crash daemonThreads)
2241 /// result !=0 if the value was invalid
2242 int gc_setTermCleanupLevel(int cLevel)
2244 if (cLevel<0 || cLevel>2) return cLevel;
2245 _termCleanupLevel=cLevel;
2249 /// returns the cleanup level done by gc
2250 int gc_getTermCleanupLevel()
2252 return _termCleanupLevel;
2257 scope (exit) assert (Invariant());
2258 gc = cast(GC*) cstdlib.calloc(1, GC.sizeof);
2261 version (DigitalMars) version(OSX) {
2262 _d_osx_image_init();
2264 // NOTE: The GC must initialize the thread library
2265 // before its first collection.
2271 assert (Invariant());
2272 if (_termCleanupLevel<1) {
2274 } else if (_termCleanupLevel==2){
2275 // a more complete cleanup
2276 // NOTE: There may be daemons threads still running when this routine is
2277 // called. If so, cleaning memory out from under then is a good
2278 // way to make them crash horribly.
2279 // Often this probably doesn't matter much since the app is
2280 // supposed to be shutting down anyway, but for example tests might
2281 // crash (and be considerd failed even if the test was ok).
2282 // thus this is not the default and should be enabled by
2283 // I'm disabling cleanup for now until I can think about it some
2286 // not really a 'collect all' -- still scans static data area, roots,
2288 return locked!(void, () {
2294 // default (safe) clenup
2295 return locked!(void, () {
2303 return locked!(void, () {
2304 assert (Invariant()); scope (exit) assert (Invariant());
2305 assert (gc.disabled > 0);
2312 return locked!(void, () {
2313 assert (Invariant()); scope (exit) assert (Invariant());
2320 return locked!(void, () {
2321 assert (Invariant()); scope (exit) assert (Invariant());
2329 return locked!(void, () {
2330 assert (Invariant()); scope (exit) assert (Invariant());
2335 uint gc_getAttr(void* p)
2339 return locked!(uint, () {
2340 assert (Invariant()); scope (exit) assert (Invariant());
2341 Pool* pool = findPool(p);
2344 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2345 return getAttr(pool, bit_i);
2349 uint gc_setAttr(void* p, uint attrs)
2353 return locked!(uint, () {
2354 assert (Invariant()); scope (exit) assert (Invariant());
2355 Pool* pool = findPool(p);
2358 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2359 uint old_attrs = getAttr(pool, bit_i);
2360 setAttr(pool, bit_i, attrs);
2365 uint gc_clrAttr(void* p, uint attrs)
2369 return locked!(uint, () {
2370 assert (Invariant()); scope (exit) assert (Invariant());
2371 Pool* pool = findPool(p);
2374 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2375 uint old_attrs = getAttr(pool, bit_i);
2376 clrAttr(pool, bit_i, attrs);
2381 void* gc_malloc(size_t size, uint attrs = 0,
2382 PointerMap ptrmap = PointerMap.init)
2386 return locked!(void*, () {
2387 assert (Invariant()); scope (exit) assert (Invariant());
2388 return malloc(size, attrs, ptrmap.bits.ptr);
2392 void* gc_calloc(size_t size, uint attrs = 0,
2393 PointerMap ptrmap = PointerMap.init)
2397 return locked!(void*, () {
2398 assert (Invariant()); scope (exit) assert (Invariant());
2399 return calloc(size, attrs, ptrmap.bits.ptr);
2403 void* gc_realloc(void* p, size_t size, uint attrs = 0,
2404 PointerMap ptrmap = PointerMap.init)
2406 return locked!(void*, () {
2407 assert (Invariant()); scope (exit) assert (Invariant());
2408 return realloc(p, size, attrs, ptrmap.bits.ptr);
2412 size_t gc_extend(void* p, size_t min_size, size_t max_size)
2414 return locked!(size_t, () {
2415 assert (Invariant()); scope (exit) assert (Invariant());
2416 return extend(p, min_size, max_size);
2420 size_t gc_reserve(size_t size)
2424 return locked!(size_t, () {
2425 assert (Invariant()); scope (exit) assert (Invariant());
2426 return reserve(size);
2430 void gc_free(void* p)
2434 return locked!(void, () {
2435 assert (Invariant()); scope (exit) assert (Invariant());
2440 void* gc_addrOf(void* p)
2444 return locked!(void*, () {
2445 assert (Invariant()); scope (exit) assert (Invariant());
2446 Pool* pool = findPool(p);
2449 return pool.findBase(p);
2453 size_t gc_sizeOf(void* p)
2457 return locked!(size_t, () {
2458 assert (Invariant()); scope (exit) assert (Invariant());
2463 BlkInfo gc_query(void* p)
2466 return BlkInfo.init;
2467 return locked!(BlkInfo, () {
2468 assert (Invariant()); scope (exit) assert (Invariant());
2473 // NOTE: This routine is experimental. The stats or function name may change
2474 // before it is made officially available.
2477 return locked!(GCStats, () {
2478 assert (Invariant()); scope (exit) assert (Invariant());
2483 void gc_addRoot(void* p)
2487 return locked!(void, () {
2488 assert (Invariant()); scope (exit) assert (Invariant());
2489 if (gc.roots.append(p) is null)
2490 onOutOfMemoryError();
2494 void gc_addRange(void* p, size_t size)
2496 if (p is null || size == 0)
2498 return locked!(void, () {
2499 assert (Invariant()); scope (exit) assert (Invariant());
2500 if (gc.ranges.append(Range(p, p + size)) is null)
2501 onOutOfMemoryError();
2505 void gc_removeRoot(void* p)
2509 return locked!(void, () {
2510 assert (Invariant()); scope (exit) assert (Invariant());
2511 bool r = gc.roots.remove(p);
2516 void gc_removeRange(void* p)
2520 return locked!(void, () {
2521 assert (Invariant()); scope (exit) assert (Invariant());
2522 bool r = gc.ranges.remove(Range(p, null));
2527 void* gc_weakpointerCreate(Object r)
2529 // weakpointers do their own locking
2530 return weakpointerCreate(r);
2533 void gc_weakpointerDestroy(void* wp)
2535 // weakpointers do their own locking
2536 weakpointerDestroy(wp);
2539 Object gc_weakpointerGet(void* wp)
2541 // weakpointers do their own locking
2542 return weakpointerGet(wp);
2546 // vim: set et sw=4 sts=4 :