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;
55 * This is a small optimization that proved it's usefulness. For small chunks
56 * or memory memset() seems to be slower (probably because of the call) that
57 * simply doing a simple loop to set the memory.
59 void memset(void* dst, int c, size_t n)
61 // This number (32) has been determined empirically
63 cstring.memset(dst, c, n);
66 auto p = cast(ubyte*)(dst);
73 // BUG: The following import will likely not work, since the gcc
74 // subdirectory is elsewhere. Instead, perhaps the functions
75 // could be declared directly or some other resolution could
77 static import gcc.builtins; // for __builtin_unwind_int
87 package enum BlkAttr : uint
89 FINALIZE = 0b0000_0001,
90 NO_SCAN = 0b0000_0010,
91 NO_MOVE = 0b0000_0100,
92 ALL_BITS = 0b1111_1111
95 package bool has_pointermap(uint attrs)
97 return !opts.options.conservative && !(attrs & BlkAttr.NO_SCAN);
102 alias void delegate(Object) DEvent;
103 alias void delegate( void*, void* ) scanFn;
104 enum { OPFAIL = ~cast(size_t)0 }
108 version (DigitalMars) version(OSX)
109 oid _d_osx_image_init();
111 void* rt_stackBottom();
113 void rt_finalize( void* p, bool det = true );
114 void rt_attachDisposeEvent(Object h, DEvent e);
115 bool rt_detachDisposeEvent(Object h, DEvent e);
116 void rt_scanStaticData( scanFn scan );
119 bool thread_needLock();
120 void thread_suspendAll();
121 void thread_resumeAll();
122 void thread_scanAll( scanFn fn, void* curStackTop = null );
124 void onOutOfMemoryError();
132 POOLSIZE = (4096*256),
146 B_PAGE, // start of large alloc
147 B_PAGEPLUS, // continuation of large alloc
167 int opCmp(in Range other)
169 if (pbot < other.pbot)
172 return cast(int)(pbot > other.pbot);
177 const uint binsize[B_MAX] = [ 16,32,64,128,256,512,1024,2048,4096 ];
178 const uint notbinsize[B_MAX] = [ ~(16u-1),~(32u-1),~(64u-1),~(128u-1),~(256u-1),
179 ~(512u-1),~(1024u-1),~(2048u-1),~(4096u-1) ];
182 /* ============================ GC =============================== */
185 class GCLock {} // just a dummy so we can get a global lock
196 // !=0 means don't scan stack
201 /// Turn off collections if > 0
204 /// min(pool.baseAddr)
206 /// max(pool.topAddr)
209 /// Free list for each size
210 List*[B_MAX] free_list;
212 dynarray.DynArray!(void*) roots;
213 dynarray.DynArray!(Range) ranges;
214 dynarray.DynArray!(Pool*) pools;
219 // call locked if necessary
220 private T locked(T, alias Code)()
222 if (thread_needLock())
223 synchronized (gc.lock) return Code();
232 assert (gc !is null);
234 for (size_t i = 0; i < gc.pools.length; i++) {
235 Pool* pool = gc.pools[i];
238 assert(gc.min_addr == pool.baseAddr);
239 if (i + 1 < gc.pools.length)
240 assert(*pool < *gc.pools[i + 1]);
241 else if (i + 1 == gc.pools.length)
242 assert(gc.max_addr == pool.topAddr);
245 gc.roots.Invariant();
246 gc.ranges.Invariant();
248 for (size_t i = 0; i < gc.ranges.length; i++) {
249 assert(gc.ranges[i].pbot);
250 assert(gc.ranges[i].ptop);
251 assert(gc.ranges[i].pbot <= gc.ranges[i].ptop);
254 for (size_t i = 0; i < B_PAGE; i++) {
255 for (List *list = gc.free_list[i]; list; list = list.next) {
256 assert (list.pool !is null);
257 auto p = cast(byte*) list;
258 assert (p >= list.pool.baseAddr);
259 assert (p < list.pool.topAddr);
268 * Find Pool that pointer is in.
269 * Return null if not in a Pool.
270 * Assume pools is sorted.
272 Pool* findPool(void* p)
274 if (p < gc.min_addr || p >= gc.max_addr)
276 if (gc.pools.length == 0)
278 if (gc.pools.length == 1)
280 /// The pooltable[] is sorted by address, so do a binary search
282 size_t high = gc.pools.length - 1;
283 while (low <= high) {
284 size_t mid = (low + high) / 2;
285 auto pool = gc.pools[mid];
286 if (p < pool.baseAddr)
288 else if (p >= pool.topAddr)
299 * Determine the base address of the block containing p. If p is not a gc
300 * allocated pointer, return null.
302 BlkInfo getInfo(void* p)
305 Pool* pool = findPool(p);
309 info.base = pool.findBase(p);
310 if (info.base is null)
312 info.size = pool.findSize(info.base);
313 info.attr = getAttr(pool, cast(size_t)(info.base - pool.baseAddr) / 16u);
314 if (has_pointermap(info.attr)) {
315 info.size -= size_t.sizeof; // PointerMap bitmask
316 // Points to the PointerMap bitmask pointer, not user data
317 if (p >= (info.base + info.size)) {
321 if (opts.options.sentinel) {
322 info.base = sentinel_add(info.base);
323 // points to sentinel data, not user data
324 if (p < info.base || p >= sentinel_post(info.base))
326 info.size -= SENTINEL_EXTRA;
333 * Compute bin for size.
335 Bins findBin(size_t size)
379 * Allocate a new pool of at least size bytes.
380 * Sort it into pools.
381 * Mark all memory in the pool as B_FREE.
382 * Return the actual number of bytes reserved or 0 on error.
384 size_t reserve(size_t size)
387 size_t npages = (size + PAGESIZE - 1) / PAGESIZE;
388 Pool* pool = newPool(npages);
392 return pool.npages * PAGESIZE;
397 * Minimizes physical memory usage by returning free pools to the OS.
405 for (n = 0; n < gc.pools.length; n++)
408 for (pn = 0; pn < pool.npages; pn++)
410 if (cast(Bins)pool.pagetable[pn] != B_FREE)
413 if (pn < pool.npages)
417 gc.pools.remove_at(n);
420 gc.min_addr = gc.pools[0].baseAddr;
421 gc.max_addr = gc.pools[gc.pools.length - 1].topAddr;
426 * Allocate a chunk of memory that is larger than a page.
427 * Return null if out of memory.
429 void* bigAlloc(size_t size, out Pool* pool)
438 npages = (size + PAGESIZE - 1) / PAGESIZE;
442 // This code could use some refinement when repeatedly
443 // allocating very large arrays.
445 for (n = 0; n < gc.pools.length; n++)
448 pn = pool.allocPages(npages);
463 freedpages = fullcollectshell();
464 if (freedpages >= gc.pools.length * ((POOLSIZE / PAGESIZE) / 4))
469 // Release empty pools to prevent bloat
472 pool = newPool(npages);
478 pn = pool.allocPages(npages);
479 assert(pn != OPFAIL);
482 // Release empty pools to prevent bloat
485 pool = newPool(npages);
488 pn = pool.allocPages(npages);
489 assert(pn != OPFAIL);
499 pool.pagetable[pn] = B_PAGE;
501 memset(&pool.pagetable[pn + 1], B_PAGEPLUS, npages - 1);
502 p = pool.baseAddr + pn * PAGESIZE;
503 memset(cast(char *)p + size, 0, npages * PAGESIZE - size);
504 if (opts.options.mem_stomp)
505 memset(p, 0xF1, size);
509 return null; // let mallocNoSync handle the error
514 * Allocate a new pool with at least npages in it.
515 * Sort it into pools.
516 * Return null if failed.
518 Pool *newPool(size_t npages)
520 // Minimum of POOLSIZE
521 if (npages < POOLSIZE/PAGESIZE)
522 npages = POOLSIZE/PAGESIZE;
523 else if (npages > POOLSIZE/PAGESIZE)
525 // Give us 150% of requested size, so there's room to extend
526 auto n = npages + (npages >> 1);
527 if (n < size_t.max/PAGESIZE)
531 // Allocate successively larger pools up to 8 megs
534 size_t n = gc.pools.length;
536 n = 8; // cap pool size at 8 megs
537 n *= (POOLSIZE / PAGESIZE);
542 auto pool = cast(Pool*) cstdlib.calloc(1, Pool.sizeof);
545 pool.initialize(npages);
552 auto inserted_pool = *gc.pools.insert_sorted!("*a < *b")(pool);
553 if (inserted_pool is null) {
557 assert (inserted_pool is pool);
558 gc.min_addr = gc.pools[0].baseAddr;
559 gc.max_addr = gc.pools[gc.pools.length - 1].topAddr;
565 * Allocate a page of bin's.
569 int allocPage(Bins bin)
577 for (n = 0; n < gc.pools.length; n++)
580 pn = pool.allocPages(1);
587 pool.pagetable[pn] = cast(ubyte)bin;
589 // Convert page to free list
590 size_t size = binsize[bin];
591 auto list_head = &gc.free_list[bin];
593 p = pool.baseAddr + pn * PAGESIZE;
595 for (; p < ptop; p += size)
597 List* l = cast(List *) p;
607 * Search a range of memory values and mark any pointers into the GC pool using
608 * type information (bitmask of pointer locations).
610 void mark_range(void *pbot, void *ptop, size_t* pm_bitmask)
612 // TODO: make our own assert because assert uses the GC
613 assert (pbot <= ptop);
615 const BITS_PER_WORD = size_t.sizeof * 8;
617 void **p1 = cast(void **)pbot;
618 void **p2 = cast(void **)ptop;
620 bool changes = false;
622 size_t type_size = pm_bitmask[0];
623 size_t* pm_bits = pm_bitmask + 1;
624 bool has_type_info = type_size != 1 || pm_bits[0] != 1 || pm_bits[1] != 0;
626 //printf("marking range: %p -> %p\n", pbot, ptop);
627 for (; p1 + type_size <= p2; p1 += type_size) {
628 for (size_t n = 0; n < type_size; n++) {
629 // scan bit set for this word
631 !(pm_bits[n / BITS_PER_WORD] & (1 << (n % BITS_PER_WORD))))
636 if (p < gc.min_addr || p >= gc.max_addr)
639 if ((cast(size_t)p & ~(PAGESIZE-1)) == pcache)
642 Pool* pool = findPool(p);
645 size_t offset = cast(size_t)(p - pool.baseAddr);
647 size_t pn = offset / PAGESIZE;
648 Bins bin = cast(Bins)pool.pagetable[pn];
650 // Cache B_PAGE, B_PAGEPLUS and B_FREE lookups
652 pcache = cast(size_t)p & ~(PAGESIZE-1);
654 // Adjust bit to be at start of allocated memory block
656 bit_i = (offset & notbinsize[bin]) / 16;
657 else if (bin == B_PAGEPLUS)
663 while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
664 bit_i = pn * (PAGESIZE / 16);
666 else // Don't mark bits in B_FREE pages
669 if (!pool.mark.test(bit_i))
671 pool.mark.set(bit_i);
672 if (!pool.noscan.test(bit_i))
674 pool.scan.set(bit_i);
682 gc.any_changes = true;
686 * Return number of full pages free'd.
688 size_t fullcollectshell()
690 gc.stats.collection_started();
692 gc.stats.collection_finished();
694 // The purpose of the 'shell' is to ensure all the registers
695 // get put on the stack so they'll be scanned
700 gcc.builtins.__builtin_unwind_init();
707 uint eax,ecx,edx,ebx,ebp,esi,edi;
720 else version (X86_64)
722 ulong rax,rbx,rcx,rdx,rbp,rsi,rdi,r8,r9,r10,r11,r12,r13,r14,r15;
745 static assert( false, "Architecture not supported." );
756 result = fullcollect(sp);
779 size_t fullcollect(void *stackTop)
781 debug(COLLECT_PRINTF) printf("Gcx.fullcollect()\n");
783 // we always need to stop the world to make threads save the CPU registers
784 // in the stack and prepare themselves for thread_scanAll()
786 gc.stats.world_stopped();
788 if (opts.options.fork) {
789 os.pid_t child_pid = os.fork();
790 assert (child_pid != -1); // don't accept errors in non-release mode
792 case -1: // if fork() fails, fallback to stop-the-world
793 opts.options.fork = false;
795 case 0: // child process (i.e. the collectors mark phase)
798 break; // bogus, will never reach here
799 default: // parent process (i.e. the mutator)
800 // start the world again and wait for the mark phase to finish
802 gc.stats.world_started();
804 os.pid_t wait_pid = os.waitpid(child_pid, &status, 0);
805 assert (wait_pid == child_pid);
811 // if we reach here, we are using the standard stop-the-world collection
814 gc.stats.world_started();
823 void mark(void *stackTop)
825 debug(COLLECT_PRINTF) printf("\tmark()\n");
830 gc.any_changes = false;
831 for (size_t n = 0; n < gc.pools.length; n++)
833 Pool* pool = gc.pools[n];
836 pool.freebits.zero();
839 // Mark each free entry, so it doesn't get scanned
840 for (size_t n = 0; n < B_PAGE; n++)
842 for (List *list = gc.free_list[n]; list; list = list.next)
844 Pool* pool = list.pool;
845 auto ptr = cast(byte*) list;
847 assert (pool.baseAddr <= ptr);
848 assert (ptr < pool.topAddr);
849 size_t bit_i = cast(size_t)(ptr - pool.baseAddr) / 16;
850 pool.freebits.set(bit_i);
854 for (size_t n = 0; n < gc.pools.length; n++)
856 Pool* pool = gc.pools[n];
857 pool.mark.copy(&pool.freebits);
860 /// Marks a range of memory in conservative mode.
861 void mark_conservative_range(void* pbot, void* ptop)
863 mark_range(pbot, ptop, PointerMap.init.bits.ptr);
866 rt_scanStaticData(&mark_conservative_range);
870 // Scan stacks and registers for each paused thread
871 thread_scanAll(&mark_conservative_range, stackTop);
875 debug(COLLECT_PRINTF) printf("scan roots[]\n");
876 mark_conservative_range(gc.roots.ptr, gc.roots.ptr + gc.roots.length);
879 debug(COLLECT_PRINTF) printf("scan ranges[]\n");
880 for (size_t n = 0; n < gc.ranges.length; n++)
882 debug(COLLECT_PRINTF) printf("\t%x .. %x\n", gc.ranges[n].pbot, gc.ranges[n].ptop);
883 mark_conservative_range(gc.ranges[n].pbot, gc.ranges[n].ptop);
886 debug(COLLECT_PRINTF) printf("\tscan heap\n");
887 while (gc.any_changes)
889 gc.any_changes = false;
890 for (size_t n = 0; n < gc.pools.length; n++)
896 Pool* pool = gc.pools[n];
898 bbase = pool.scan.base();
899 btop = bbase + pool.scan.nwords;
900 for (b = bbase; b < btop;)
916 o = pool.baseAddr + (b - bbase) * 32 * 16;
917 if (!(bitm & 0xFFFF))
922 for (; bitm; o += 16, bitm >>= 1)
927 pn = cast(size_t)(o - pool.baseAddr) / PAGESIZE;
928 bin = cast(Bins)pool.pagetable[pn];
930 if (opts.options.conservative)
931 mark_conservative_range(o, o + binsize[bin]);
933 auto end_of_blk = cast(size_t**)(o +
934 binsize[bin] - size_t.sizeof);
935 size_t* pm_bitmask = *end_of_blk;
936 mark_range(o, end_of_blk, pm_bitmask);
939 else if (bin == B_PAGE || bin == B_PAGEPLUS)
941 if (bin == B_PAGEPLUS)
943 while (pool.pagetable[pn - 1] != B_PAGE)
947 while (pn + u < pool.npages &&
948 pool.pagetable[pn + u] == B_PAGEPLUS)
951 size_t blk_size = u * PAGESIZE;
952 if (opts.options.conservative)
953 mark_conservative_range(o, o + blk_size);
955 auto end_of_blk = cast(size_t**)(o + blk_size -
957 size_t* pm_bitmask = *end_of_blk;
958 mark_range(o, end_of_blk, pm_bitmask);
973 // Free up everything not marked
974 debug(COLLECT_PRINTF) printf("\tsweep\n");
975 size_t freedpages = 0;
977 for (size_t n = 0; n < gc.pools.length; n++)
979 Pool* pool = gc.pools[n];
981 uint* bbase = pool.mark.base();
983 for (pn = 0; pn < pool.npages; pn++, bbase += PAGESIZE / (32 * 16))
985 Bins bin = cast(Bins)pool.pagetable[pn];
989 auto size = binsize[bin];
990 byte* p = pool.baseAddr + pn * PAGESIZE;
991 byte* ptop = p + PAGESIZE;
992 size_t bit_i = pn * (PAGESIZE/16);
993 size_t bit_stride = size / 16;
995 version(none) // BUG: doesn't work because freebits() must also be cleared
997 // If free'd entire page
998 if (bbase[0] == 0 && bbase[1] == 0 && bbase[2] == 0 &&
999 bbase[3] == 0 && bbase[4] == 0 && bbase[5] == 0 &&
1000 bbase[6] == 0 && bbase[7] == 0)
1002 for (; p < ptop; p += size, bit_i += bit_stride)
1004 if (pool.finals.nbits && pool.finals.testClear(bit_i)) {
1005 if (opts.options.sentinel)
1006 rt_finalize(sentinel_add(p), false/*gc.no_stack > 0*/);
1008 rt_finalize(p, false/*gc.no_stack > 0*/);
1010 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1012 if (opts.options.mem_stomp)
1013 memset(p, 0xF3, size);
1015 pool.pagetable[pn] = B_FREE;
1020 for (; p < ptop; p += size, bit_i += bit_stride)
1022 if (!pool.mark.test(bit_i))
1024 if (opts.options.sentinel)
1025 sentinel_Invariant(sentinel_add(p));
1027 pool.freebits.set(bit_i);
1028 if (pool.finals.nbits && pool.finals.testClear(bit_i)) {
1029 if (opts.options.sentinel)
1030 rt_finalize(sentinel_add(p), false/*gc.no_stack > 0*/);
1032 rt_finalize(p, false/*gc.no_stack > 0*/);
1034 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1036 if (opts.options.mem_stomp)
1037 memset(p, 0xF3, size);
1043 else if (bin == B_PAGE)
1045 size_t bit_i = pn * (PAGESIZE / 16);
1046 if (!pool.mark.test(bit_i))
1048 byte *p = pool.baseAddr + pn * PAGESIZE;
1049 if (opts.options.sentinel)
1050 sentinel_Invariant(sentinel_add(p));
1051 if (pool.finals.nbits && pool.finals.testClear(bit_i)) {
1052 if (opts.options.sentinel)
1053 rt_finalize(sentinel_add(p), false/*gc.no_stack > 0*/);
1055 rt_finalize(p, false/*gc.no_stack > 0*/);
1057 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1059 debug(COLLECT_PRINTF) printf("\tcollecting big %x\n", p);
1060 pool.pagetable[pn] = B_FREE;
1062 if (opts.options.mem_stomp)
1063 memset(p, 0xF3, PAGESIZE);
1064 while (pn + 1 < pool.npages && pool.pagetable[pn + 1] == B_PAGEPLUS)
1067 pool.pagetable[pn] = B_FREE;
1070 if (opts.options.mem_stomp)
1073 memset(p, 0xF3, PAGESIZE);
1082 gc.free_list[] = null;
1084 // Free complete pages, rebuild free list
1085 debug(COLLECT_PRINTF) printf("\tfree complete pages\n");
1086 size_t recoveredpages = 0;
1087 for (size_t n = 0; n < gc.pools.length; n++)
1089 Pool* pool = gc.pools[n];
1090 for (size_t pn = 0; pn < pool.npages; pn++)
1092 Bins bin = cast(Bins)pool.pagetable[pn];
1098 size_t size = binsize[bin];
1099 size_t bit_stride = size / 16;
1100 size_t bit_base = pn * (PAGESIZE / 16);
1101 size_t bit_top = bit_base + (PAGESIZE / 16);
1105 for (; bit_i < bit_top; bit_i += bit_stride)
1107 if (!pool.freebits.test(bit_i))
1110 pool.pagetable[pn] = B_FREE;
1115 p = pool.baseAddr + pn * PAGESIZE;
1116 for (u = 0; u < PAGESIZE; u += size)
1118 bit_i = bit_base + u / 16;
1119 if (pool.freebits.test(bit_i))
1121 assert ((p+u) >= pool.baseAddr);
1122 assert ((p+u) < pool.topAddr);
1123 List* list = cast(List*) (p + u);
1124 // avoid unnecesary writes (it really saves time)
1125 if (list.next != gc.free_list[bin])
1126 list.next = gc.free_list[bin];
1127 if (list.pool != pool)
1129 gc.free_list[bin] = list;
1136 debug(COLLECT_PRINTF) printf("recovered pages = %d\n", recoveredpages);
1137 debug(COLLECT_PRINTF) printf("\tfree'd %u bytes, %u pages from %u pools\n", freed, freedpages, gc.pools.length);
1139 return freedpages + recoveredpages;
1146 uint getAttr(Pool* pool, size_t bit_i)
1155 if (pool.finals.nbits &&
1156 pool.finals.test(bit_i))
1157 attrs |= BlkAttr.FINALIZE;
1158 if (pool.noscan.test(bit_i))
1159 attrs |= BlkAttr.NO_SCAN;
1160 // if (pool.nomove.nbits &&
1161 // pool.nomove.test(bit_i))
1162 // attrs |= BlkAttr.NO_MOVE;
1170 void setAttr(Pool* pool, size_t bit_i, uint mask)
1177 if (mask & BlkAttr.FINALIZE)
1179 if (!pool.finals.nbits)
1180 pool.finals.alloc(pool.mark.nbits);
1181 pool.finals.set(bit_i);
1183 if (mask & BlkAttr.NO_SCAN)
1185 pool.noscan.set(bit_i);
1187 // if (mask & BlkAttr.NO_MOVE)
1189 // if (!pool.nomove.nbits)
1190 // pool.nomove.alloc(pool.mark.nbits);
1191 // pool.nomove.set(bit_i);
1199 void clrAttr(Pool* pool, size_t bit_i, uint mask)
1206 if (mask & BlkAttr.FINALIZE && pool.finals.nbits)
1207 pool.finals.clear(bit_i);
1208 if (mask & BlkAttr.NO_SCAN)
1209 pool.noscan.clear(bit_i);
1210 // if (mask & BlkAttr.NO_MOVE && pool.nomove.nbits)
1211 // pool.nomove.clear(bit_i);
1219 gc.stack_bottom = cast(char*)&dummy;
1220 opts.parse(cstdlib.getenv("D_GC_OPTS"));
1221 // If we are going to fork, make sure we have the needed OS support
1222 if (opts.options.fork)
1223 opts.options.fork = os.HAVE_SHARED && os.HAVE_FORK;
1224 gc.lock = GCLock.classinfo;
1226 setStackBottom(rt_stackBottom());
1227 gc.stats = Stats(gc);
1234 private void *malloc(size_t size, uint attrs, size_t* pm_bitmask)
1238 gc.stats.malloc_started(size, attrs, pm_bitmask);
1240 gc.stats.malloc_finished(p);
1245 if (opts.options.sentinel)
1246 size += SENTINEL_EXTRA;
1248 bool has_pm = has_pointermap(attrs);
1250 size += size_t.sizeof;
1253 // Cache previous binsize lookup - Dave Fladebo.
1254 static size_t lastsize = -1;
1255 static Bins lastbin;
1256 if (size == lastsize)
1260 bin = findBin(size);
1266 size_t capacity = void; // to figure out where to store the bitmask
1269 p = gc.free_list[bin];
1272 if (!allocPage(bin) && !gc.disabled) // try to find a new page
1274 if (!thread_needLock())
1276 /* Then we haven't locked it yet. Be sure
1277 * and gc.lock for a collection, since a finalizer
1278 * may start a new thread.
1280 synchronized (gc.lock)
1285 else if (!fullcollectshell()) // collect to find a new page
1290 if (!gc.free_list[bin] && !allocPage(bin))
1292 newPool(1); // allocate new pool to find a new page
1293 // TODO: hint allocPage() to use the pool we just created
1294 int result = allocPage(bin);
1296 onOutOfMemoryError();
1298 p = gc.free_list[bin];
1300 capacity = binsize[bin];
1302 // Return next item from free list
1303 List* list = cast(List*) p;
1304 assert ((cast(byte*)list) >= list.pool.baseAddr);
1305 assert ((cast(byte*)list) < list.pool.topAddr);
1306 gc.free_list[bin] = list.next;
1308 if (!(attrs & BlkAttr.NO_SCAN))
1309 memset(p + size, 0, capacity - size);
1310 if (opts.options.mem_stomp)
1311 memset(p, 0xF0, size);
1315 p = bigAlloc(size, pool);
1317 onOutOfMemoryError();
1318 assert (pool !is null);
1319 // Round the size up to the number of pages needed to store it
1320 size_t npages = (size + PAGESIZE - 1) / PAGESIZE;
1321 capacity = npages * PAGESIZE;
1324 // Store the bit mask AFTER SENTINEL_POST
1325 // TODO: store it BEFORE, so the bitmask is protected too
1327 auto end_of_blk = cast(size_t**)(p + capacity - size_t.sizeof);
1328 *end_of_blk = pm_bitmask;
1329 size -= size_t.sizeof;
1332 if (opts.options.sentinel) {
1333 size -= SENTINEL_EXTRA;
1334 p = sentinel_add(p);
1335 sentinel_init(p, size);
1339 setAttr(pool, cast(size_t)(p - pool.baseAddr) / 16, attrs);
1348 private void *calloc(size_t size, uint attrs, size_t* pm_bitmask)
1352 void *p = malloc(size, attrs, pm_bitmask);
1361 private void *realloc(void *p, size_t size, uint attrs,
1374 p = malloc(size, attrs, pm_bitmask);
1378 Pool* pool = findPool(p);
1382 // Set or retrieve attributes as appropriate
1383 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1385 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1386 setAttr(pool, bit_i, attrs);
1389 attrs = getAttr(pool, bit_i);
1391 void* blk_base_addr = pool.findBase(p);
1392 size_t blk_size = pool.findSize(p);
1393 bool has_pm = has_pointermap(attrs);
1394 size_t pm_bitmask_size = 0;
1396 pm_bitmask_size = size_t.sizeof;
1397 // Retrieve pointer map bit mask if appropriate
1398 if (pm_bitmask is null) {
1399 auto end_of_blk = cast(size_t**)(blk_base_addr +
1400 blk_size - size_t.sizeof);
1401 pm_bitmask = *end_of_blk;
1405 if (opts.options.sentinel)
1407 sentinel_Invariant(p);
1408 size_t sentinel_stored_size = *sentinel_size(p);
1409 if (sentinel_stored_size != size)
1411 void* p2 = malloc(size, attrs, pm_bitmask);
1412 if (sentinel_stored_size < size)
1413 size = sentinel_stored_size;
1414 cstring.memcpy(p2, p, size);
1420 size += pm_bitmask_size;
1421 if (blk_size >= PAGESIZE && size >= PAGESIZE)
1423 auto psz = blk_size / PAGESIZE;
1424 auto newsz = (size + PAGESIZE - 1) / PAGESIZE;
1428 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
1433 if (opts.options.mem_stomp)
1434 memset(p + size - pm_bitmask_size, 0xF2,
1435 blk_size - size - pm_bitmask_size);
1436 pool.freePages(pagenum + newsz, psz - newsz);
1437 auto new_blk_size = (PAGESIZE * newsz);
1438 // update the size cache, assuming that is very likely the
1439 // size of this block will be queried in the near future
1440 pool.update_cache(p, new_blk_size);
1442 auto end_of_blk = cast(size_t**)(blk_base_addr +
1443 new_blk_size - pm_bitmask_size);
1444 *end_of_blk = pm_bitmask;
1448 else if (pagenum + newsz <= pool.npages)
1450 // Attempt to expand in place
1451 for (size_t i = pagenum + psz; 1;)
1453 if (i == pagenum + newsz)
1455 if (opts.options.mem_stomp)
1456 memset(p + blk_size - pm_bitmask_size,
1457 0xF0, size - blk_size
1459 memset(pool.pagetable + pagenum +
1460 psz, B_PAGEPLUS, newsz - psz);
1461 auto new_blk_size = (PAGESIZE * newsz);
1462 // update the size cache, assuming that is very
1463 // likely the size of this block will be queried in
1465 pool.update_cache(p, new_blk_size);
1467 auto end_of_blk = cast(size_t**)(
1468 blk_base_addr + new_blk_size -
1470 *end_of_blk = pm_bitmask;
1474 if (i == pool.npages)
1478 if (pool.pagetable[i] != B_FREE)
1484 // if new size is bigger or less than half
1485 if (blk_size < size || blk_size > size * 2)
1487 size -= pm_bitmask_size;
1488 blk_size -= pm_bitmask_size;
1489 void* p2 = malloc(size, attrs, pm_bitmask);
1490 if (blk_size < size)
1492 cstring.memcpy(p2, p, size);
1502 * Attempt to in-place enlarge the memory block pointed to by p by at least
1503 * min_size beyond its current capacity, up to a maximum of max_size. This
1504 * does not attempt to move the memory block (like realloc() does).
1507 * 0 if could not extend p,
1508 * total size of entire memory block if successful.
1510 private size_t extend(void* p, size_t minsize, size_t maxsize)
1513 assert( minsize <= maxsize );
1517 if (opts.options.sentinel)
1520 Pool* pool = findPool(p);
1524 // Retrieve attributes
1525 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1526 uint attrs = getAttr(pool, bit_i);
1528 void* blk_base_addr = pool.findBase(p);
1529 size_t blk_size = pool.findSize(p);
1530 bool has_pm = has_pointermap(attrs);
1531 size_t* pm_bitmask = null;
1532 size_t pm_bitmask_size = 0;
1534 pm_bitmask_size = size_t.sizeof;
1535 // Retrieve pointer map bit mask
1536 auto end_of_blk = cast(size_t**)(blk_base_addr +
1537 blk_size - size_t.sizeof);
1538 pm_bitmask = *end_of_blk;
1540 minsize += size_t.sizeof;
1541 maxsize += size_t.sizeof;
1544 if (blk_size < PAGESIZE)
1545 return 0; // cannot extend buckets
1547 auto psz = blk_size / PAGESIZE;
1548 auto minsz = (minsize + PAGESIZE - 1) / PAGESIZE;
1549 auto maxsz = (maxsize + PAGESIZE - 1) / PAGESIZE;
1551 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
1554 for (sz = 0; sz < maxsz; sz++)
1556 auto i = pagenum + psz + sz;
1557 if (i == pool.npages)
1559 if (pool.pagetable[i] != B_FREE)
1569 size_t new_size = (psz + sz) * PAGESIZE;
1571 if (opts.options.mem_stomp)
1572 memset(p + blk_size - pm_bitmask_size, 0xF0,
1573 new_size - blk_size - pm_bitmask_size);
1574 memset(pool.pagetable + pagenum + psz, B_PAGEPLUS, sz);
1577 // update the size cache, assuming that is very likely the size of this
1578 // block will be queried in the near future
1579 pool.update_cache(p, new_size);
1582 new_size -= size_t.sizeof;
1583 auto end_of_blk = cast(size_t**)(blk_base_addr + new_size);
1584 *end_of_blk = pm_bitmask;
1593 private void free(void *p)
1602 // Find which page it is in
1604 if (!pool) // if not one of ours
1606 if (opts.options.sentinel) {
1607 sentinel_Invariant(p);
1608 p = sentinel_sub(p);
1610 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1611 bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1612 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1614 bin = cast(Bins)pool.pagetable[pagenum];
1615 if (bin == B_PAGE) // if large alloc
1620 while (++n < pool.npages && pool.pagetable[n] == B_PAGEPLUS)
1622 if (opts.options.mem_stomp)
1623 memset(p, 0xF2, npages * PAGESIZE);
1624 pool.freePages(pagenum, npages);
1625 // just in case we were caching this pointer
1626 pool.clear_cache(p);
1631 List* list = cast(List*) p;
1633 if (opts.options.mem_stomp)
1634 memset(p, 0xF2, binsize[bin]);
1636 list.next = gc.free_list[bin];
1638 gc.free_list[bin] = list;
1644 * Determine the allocated size of pointer p. If p is an interior pointer
1645 * or not a gc allocated pointer, return 0.
1647 private size_t sizeOf(void *p)
1651 if (opts.options.sentinel)
1652 p = sentinel_sub(p);
1654 Pool* pool = findPool(p);
1658 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
1659 uint attrs = getAttr(pool, biti);
1661 size_t size = pool.findSize(p);
1662 size_t pm_bitmask_size = 0;
1663 if (has_pointermap(attrs))
1664 pm_bitmask_size = size_t.sizeof;
1666 if (opts.options.sentinel) {
1667 // Check for interior pointer
1669 // 1) size is a power of 2 for less than PAGESIZE values
1670 // 2) base of memory pool is aligned on PAGESIZE boundary
1671 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
1673 return size - SENTINEL_EXTRA - pm_bitmask_size;
1676 if (p == gc.p_cache)
1677 return gc.size_cache;
1679 // Check for interior pointer
1681 // 1) size is a power of 2 for less than PAGESIZE values
1682 // 2) base of memory pool is aligned on PAGESIZE boundary
1683 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
1687 gc.size_cache = size - pm_bitmask_size;
1689 return gc.size_cache;
1695 * Verify that pointer p:
1696 * 1) belongs to this memory pool
1697 * 2) points to the start of an allocated piece of memory
1698 * 3) is not on a free list
1700 private void checkNoSync(void *p)
1704 if (opts.options.sentinel)
1705 sentinel_Invariant(p);
1713 if (opts.options.sentinel)
1714 p = sentinel_sub(p);
1717 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1718 bin = cast(Bins)pool.pagetable[pagenum];
1719 assert(bin <= B_PAGE);
1720 size = binsize[bin];
1721 assert((cast(size_t)p & (size - 1)) == 0);
1727 // Check that p is not on a free list
1728 for (List* list = gc.free_list[bin]; list; list = list.next)
1730 assert(cast(void*)list != p);
1741 private void setStackBottom(void *p)
1743 version (STACKGROWSDOWN)
1745 //p = (void *)((uint *)p + 4);
1746 if (p > gc.stack_bottom)
1748 gc.stack_bottom = p;
1753 //p = (void *)((uint *)p - 4);
1754 if (p < gc.stack_bottom)
1756 gc.stack_bottom = cast(char*)p;
1763 * Retrieve statistics about garbage collection.
1764 * Useful for debugging and tuning.
1766 private GCStats getStats()
1776 for (n = 0; n < gc.pools.length; n++)
1778 Pool* pool = gc.pools[n];
1779 psize += pool.npages * PAGESIZE;
1780 for (size_t j = 0; j < pool.npages; j++)
1782 Bins bin = cast(Bins)pool.pagetable[j];
1785 else if (bin == B_PAGE)
1787 else if (bin < B_PAGE)
1792 for (n = 0; n < B_PAGE; n++)
1794 for (List* list = gc.free_list[n]; list; list = list.next)
1795 flsize += binsize[n];
1798 usize = bsize - flsize;
1800 stats.poolsize = psize;
1801 stats.usedsize = bsize - flsize;
1802 stats.freelistsize = flsize;
1806 /******************* weak-reference support *********************/
1808 private struct WeakPointer
1812 void ondestroy(Object r)
1814 assert(r is reference);
1815 // lock for memory consistency (parallel readers)
1816 // also ensures that weakpointerDestroy can be called while another
1817 // thread is freeing the reference with "delete"
1818 return locked!(void, () {
1825 * Create a weak pointer to the given object.
1826 * Returns a pointer to an opaque struct allocated in C memory.
1828 void* weakpointerCreate( Object r )
1832 // must be allocated in C memory
1833 // 1. to hide the reference from the GC
1834 // 2. the GC doesn't scan delegates added by rt_attachDisposeEvent
1836 auto wp = cast(WeakPointer*)(cstdlib.malloc(WeakPointer.sizeof));
1838 onOutOfMemoryError();
1840 rt_attachDisposeEvent(r, &wp.ondestroy);
1847 * Destroy a weak pointer returned by weakpointerCreate().
1848 * If null is passed, nothing happens.
1850 void weakpointerDestroy( void* p )
1854 auto wp = cast(WeakPointer*)p;
1855 // must be extra careful about the GC or parallel threads
1856 // finalizing the reference at the same time
1857 return locked!(void, () {
1859 rt_detachDisposeEvent(wp.reference, &wp.ondestroy);
1866 * Query a weak pointer and return either the object passed to
1867 * weakpointerCreate, or null if it was free'd in the meantime.
1868 * If null is passed, null is returned.
1870 Object weakpointerGet( void* p )
1874 // NOTE: could avoid the lock by using Fawzi style GC counters but
1875 // that'd require core.sync.Atomic and lots of care about memory
1876 // consistency it's an optional optimization see
1877 // http://dsource.org/projects/tango/browser/trunk/user/tango/core/Lifetime.d?rev=5100#L158
1878 return locked!(Object, () {
1879 return (cast(WeakPointer*)p).reference;
1885 /* ============================ Pool =============================== */
1892 GCBits mark; // entries already scanned, or should not be scanned
1893 GCBits scan; // entries that need to be scanned
1894 GCBits freebits; // entries that are on the free list
1895 GCBits finals; // entries that need finalizer run on them
1896 GCBits noscan; // entries that should not be scanned
1901 /// Cache for findSize()
1905 void clear_cache(void* ptr = null)
1907 if (ptr is null || ptr is this.cached_ptr) {
1908 this.cached_ptr = null;
1909 this.cached_size = 0;
1913 void update_cache(void* ptr, size_t size)
1915 this.cached_ptr = ptr;
1916 this.cached_size = size;
1919 void initialize(size_t npages)
1921 size_t poolsize = npages * PAGESIZE;
1922 assert(poolsize >= POOLSIZE);
1923 baseAddr = cast(byte *) os.alloc(poolsize);
1925 // Some of the code depends on page alignment of memory pools
1926 assert((cast(size_t)baseAddr & (PAGESIZE - 1)) == 0);
1933 topAddr = baseAddr + poolsize;
1935 size_t nbits = cast(size_t)poolsize / 16;
1937 // if the GC will run in parallel in a fork()ed process, we need to
1938 // share the mark bits
1939 os.Vis vis = os.Vis.PRIV;
1940 if (opts.options.fork)
1941 vis = os.Vis.SHARED;
1942 mark.alloc(nbits, vis); // shared between mark and sweep
1943 freebits.alloc(nbits, vis); // ditto
1944 scan.alloc(nbits); // only used in the mark phase
1945 finals.alloc(nbits); // mark phase *MUST* have a snapshot
1946 noscan.alloc(nbits); // ditto
1948 pagetable = cast(ubyte*) cstdlib.malloc(npages);
1950 onOutOfMemoryError();
1951 memset(pagetable, B_FREE, npages);
1953 this.npages = npages;
1965 result = os.dealloc(baseAddr, npages * PAGESIZE);
1973 // See Gcx.Dtor() for the rationale of the null check.
1975 cstdlib.free(pagetable);
1977 os.Vis vis = os.Vis.PRIV;
1978 if (opts.options.fork)
1979 vis = os.Vis.SHARED;
1998 //freebits.Invariant();
1999 //finals.Invariant();
2000 //noscan.Invariant();
2004 //if (baseAddr + npages * PAGESIZE != topAddr)
2005 //printf("baseAddr = %p, npages = %d, topAddr = %p\n", baseAddr, npages, topAddr);
2006 assert(baseAddr + npages * PAGESIZE == topAddr);
2009 for (size_t i = 0; i < npages; i++)
2011 Bins bin = cast(Bins)pagetable[i];
2012 assert(bin < B_MAX);
2018 * Allocate n pages from Pool.
2019 * Returns OPFAIL on failure.
2021 size_t allocPages(size_t n)
2027 for (i = 0; i < npages; i++)
2029 if (pagetable[i] == B_FREE)
2042 * Free npages pages starting with pagenum.
2044 void freePages(size_t pagenum, size_t npages)
2046 memset(&pagetable[pagenum], B_FREE, npages);
2051 * Find base address of block containing pointer p.
2052 * Returns null if the pointer doesn't belong to this pool
2054 void* findBase(void *p)
2056 size_t offset = cast(size_t)(p - this.baseAddr);
2057 size_t pagenum = offset / PAGESIZE;
2058 Bins bin = cast(Bins)this.pagetable[pagenum];
2059 // Adjust bit to be at start of allocated memory block
2061 return this.baseAddr + (offset & notbinsize[bin]);
2062 if (bin == B_PAGEPLUS) {
2064 --pagenum, offset -= PAGESIZE;
2065 } while (cast(Bins)this.pagetable[pagenum] == B_PAGEPLUS);
2066 return this.baseAddr + (offset & (offset.max ^ (PAGESIZE-1)));
2068 // we are in a B_FREE page
2074 * Find size of pointer p.
2075 * Returns 0 if p doesn't belong to this pool if if it's block size is less
2078 size_t findSize(void *p)
2080 size_t pagenum = cast(size_t)(p - this.baseAddr) / PAGESIZE;
2081 Bins bin = cast(Bins)this.pagetable[pagenum];
2083 return binsize[bin];
2084 if (this.cached_ptr == p)
2085 return this.cached_size;
2086 size_t i = pagenum + 1;
2087 for (; i < this.npages; i++)
2088 if (this.pagetable[i] != B_PAGEPLUS)
2090 this.cached_ptr = p;
2091 this.cached_size = (i - pagenum) * PAGESIZE;
2092 return this.cached_size;
2097 * Used for sorting pools
2099 int opCmp(in Pool other)
2101 if (baseAddr < other.baseAddr)
2104 return cast(int)(baseAddr > other.baseAddr);
2109 /* ============================ SENTINEL =============================== */
2112 const size_t SENTINEL_PRE = cast(size_t) 0xF4F4F4F4F4F4F4F4UL; // 32 or 64 bits
2113 const ubyte SENTINEL_POST = 0xF5; // 8 bits
2114 const uint SENTINEL_EXTRA = 2 * size_t.sizeof + 1;
2117 size_t* sentinel_size(void *p) { return &(cast(size_t *)p)[-2]; }
2118 size_t* sentinel_pre(void *p) { return &(cast(size_t *)p)[-1]; }
2119 ubyte* sentinel_post(void *p) { return &(cast(ubyte *)p)[*sentinel_size(p)]; }
2122 void sentinel_init(void *p, size_t size)
2124 *sentinel_size(p) = size;
2125 *sentinel_pre(p) = SENTINEL_PRE;
2126 *sentinel_post(p) = SENTINEL_POST;
2130 void sentinel_Invariant(void *p)
2132 if (*sentinel_pre(p) != SENTINEL_PRE ||
2133 *sentinel_post(p) != SENTINEL_POST)
2138 void *sentinel_add(void *p)
2140 return p + 2 * size_t.sizeof;
2144 void *sentinel_sub(void *p)
2146 return p - 2 * size_t.sizeof;
2151 /* ============================ C Public Interface ======================== */
2154 private int _termCleanupLevel=1;
2158 /// sets the cleanup level done by gc
2161 /// 2: fullCollect ignoring stack roots (might crash daemonThreads)
2162 /// result !=0 if the value was invalid
2163 int gc_setTermCleanupLevel(int cLevel)
2165 if (cLevel<0 || cLevel>2) return cLevel;
2166 _termCleanupLevel=cLevel;
2170 /// returns the cleanup level done by gc
2171 int gc_getTermCleanupLevel()
2173 return _termCleanupLevel;
2178 scope (exit) assert (Invariant());
2179 gc = cast(GC*) cstdlib.calloc(1, GC.sizeof);
2182 version (DigitalMars) version(OSX) {
2183 _d_osx_image_init();
2185 // NOTE: The GC must initialize the thread library
2186 // before its first collection.
2192 assert (Invariant());
2193 if (_termCleanupLevel<1) {
2195 } else if (_termCleanupLevel==2){
2196 // a more complete cleanup
2197 // NOTE: There may be daemons threads still running when this routine is
2198 // called. If so, cleaning memory out from under then is a good
2199 // way to make them crash horribly.
2200 // Often this probably doesn't matter much since the app is
2201 // supposed to be shutting down anyway, but for example tests might
2202 // crash (and be considerd failed even if the test was ok).
2203 // thus this is not the default and should be enabled by
2204 // I'm disabling cleanup for now until I can think about it some
2207 // not really a 'collect all' -- still scans static data area, roots,
2209 return locked!(void, () {
2215 // default (safe) clenup
2216 return locked!(void, () {
2224 return locked!(void, () {
2225 assert (Invariant()); scope (exit) assert (Invariant());
2226 assert (gc.disabled > 0);
2233 return locked!(void, () {
2234 assert (Invariant()); scope (exit) assert (Invariant());
2241 return locked!(void, () {
2242 assert (Invariant()); scope (exit) assert (Invariant());
2250 return locked!(void, () {
2251 assert (Invariant()); scope (exit) assert (Invariant());
2256 uint gc_getAttr(void* p)
2260 return locked!(uint, () {
2261 assert (Invariant()); scope (exit) assert (Invariant());
2262 Pool* pool = findPool(p);
2265 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2266 return getAttr(pool, bit_i);
2270 uint gc_setAttr(void* p, uint attrs)
2274 return locked!(uint, () {
2275 assert (Invariant()); scope (exit) assert (Invariant());
2276 Pool* pool = findPool(p);
2279 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2280 uint old_attrs = getAttr(pool, bit_i);
2281 setAttr(pool, bit_i, attrs);
2286 uint gc_clrAttr(void* p, uint attrs)
2290 return locked!(uint, () {
2291 assert (Invariant()); scope (exit) assert (Invariant());
2292 Pool* pool = findPool(p);
2295 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2296 uint old_attrs = getAttr(pool, bit_i);
2297 clrAttr(pool, bit_i, attrs);
2302 void* gc_malloc(size_t size, uint attrs = 0,
2303 PointerMap ptrmap = PointerMap.init)
2307 return locked!(void*, () {
2308 assert (Invariant()); scope (exit) assert (Invariant());
2309 return malloc(size, attrs, ptrmap.bits.ptr);
2313 void* gc_calloc(size_t size, uint attrs = 0,
2314 PointerMap ptrmap = PointerMap.init)
2318 return locked!(void*, () {
2319 assert (Invariant()); scope (exit) assert (Invariant());
2320 return calloc(size, attrs, ptrmap.bits.ptr);
2324 void* gc_realloc(void* p, size_t size, uint attrs = 0,
2325 PointerMap ptrmap = PointerMap.init)
2327 return locked!(void*, () {
2328 assert (Invariant()); scope (exit) assert (Invariant());
2329 return realloc(p, size, attrs, ptrmap.bits.ptr);
2333 size_t gc_extend(void* p, size_t min_size, size_t max_size)
2335 return locked!(size_t, () {
2336 assert (Invariant()); scope (exit) assert (Invariant());
2337 return extend(p, min_size, max_size);
2341 size_t gc_reserve(size_t size)
2345 return locked!(size_t, () {
2346 assert (Invariant()); scope (exit) assert (Invariant());
2347 return reserve(size);
2351 void gc_free(void* p)
2355 return locked!(void, () {
2356 assert (Invariant()); scope (exit) assert (Invariant());
2361 void* gc_addrOf(void* p)
2365 return locked!(void*, () {
2366 assert (Invariant()); scope (exit) assert (Invariant());
2367 Pool* pool = findPool(p);
2370 return pool.findBase(p);
2374 size_t gc_sizeOf(void* p)
2378 return locked!(size_t, () {
2379 assert (Invariant()); scope (exit) assert (Invariant());
2384 BlkInfo gc_query(void* p)
2387 return BlkInfo.init;
2388 return locked!(BlkInfo, () {
2389 assert (Invariant()); scope (exit) assert (Invariant());
2394 // NOTE: This routine is experimental. The stats or function name may change
2395 // before it is made officially available.
2398 return locked!(GCStats, () {
2399 assert (Invariant()); scope (exit) assert (Invariant());
2404 void gc_addRoot(void* p)
2408 return locked!(void, () {
2409 assert (Invariant()); scope (exit) assert (Invariant());
2410 if (gc.roots.append(p) is null)
2411 onOutOfMemoryError();
2415 void gc_addRange(void* p, size_t size)
2417 if (p is null || size == 0)
2419 return locked!(void, () {
2420 assert (Invariant()); scope (exit) assert (Invariant());
2421 if (gc.ranges.append(Range(p, p + size)) is null)
2422 onOutOfMemoryError();
2426 void gc_removeRoot(void* p)
2430 return locked!(void, () {
2431 assert (Invariant()); scope (exit) assert (Invariant());
2432 bool r = gc.roots.remove(p);
2437 void gc_removeRange(void* p)
2441 return locked!(void, () {
2442 assert (Invariant()); scope (exit) assert (Invariant());
2443 bool r = gc.ranges.remove(Range(p, null));
2448 void* gc_weakpointerCreate(Object r)
2450 // weakpointers do their own locking
2451 return weakpointerCreate(r);
2454 void gc_weakpointerDestroy(void* wp)
2456 // weakpointers do their own locking
2457 weakpointerDestroy(wp);
2460 Object gc_weakpointerGet(void* wp)
2462 // weakpointers do their own locking
2463 return weakpointerGet(wp);
2467 // vim: set et sw=4 sts=4 :