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 alloc = rt.gc.cdgc.alloc;
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
166 int opCmp(in Range other)
168 if (pbot < other.pbot)
171 return cast(int)(pbot > other.pbot);
176 const uint binsize[B_MAX] = [ 16,32,64,128,256,512,1024,2048,4096 ];
177 const uint notbinsize[B_MAX] = [ ~(16u-1),~(32u-1),~(64u-1),~(128u-1),~(256u-1),
178 ~(512u-1),~(1024u-1),~(2048u-1),~(4096u-1) ];
181 /* ============================ GC =============================== */
184 class GCLock {} // just a dummy so we can get a global lock
195 // !=0 means don't scan stack
200 /// Turn off collections if > 0
203 /// min(pool.baseAddr)
205 /// max(pool.topAddr)
208 /// Free list for each size
209 List*[B_MAX] free_list;
211 dynarray.DynArray!(void*) roots;
212 dynarray.DynArray!(Range) ranges;
213 dynarray.DynArray!(Pool) pools;
218 // call locked if necessary
219 private T locked(T, alias Code)()
221 if (thread_needLock())
222 synchronized (gc.lock) return Code();
231 assert (gc !is null);
233 for (size_t i = 0; i < gc.pools.length; i++) {
234 Pool* pool = gc.pools[i];
237 assert(gc.min_addr == pool.baseAddr);
238 if (i + 1 < gc.pools.length)
239 assert(*pool < gc.pools[i + 1]);
240 else if (i + 1 == gc.pools.length)
241 assert(gc.max_addr == pool.topAddr);
244 gc.roots.Invariant();
245 gc.ranges.Invariant();
247 for (size_t i = 0; i < gc.ranges.length; i++) {
248 assert(gc.ranges[i].pbot);
249 assert(gc.ranges[i].ptop);
250 assert(gc.ranges[i].pbot <= gc.ranges[i].ptop);
253 for (size_t i = 0; i < B_PAGE; i++)
254 for (List *list = gc.free_list[i]; list; list = list.next)
263 * Find Pool that pointer is in.
264 * Return null if not in a Pool.
265 * Assume pools is sorted.
267 Pool *findPool(void *p)
269 if (p >= gc.min_addr && p < gc.max_addr)
271 if (gc.pools.length == 1)
276 for (size_t i = 0; i < gc.pools.length; i++)
278 Pool* pool = gc.pools[i];
279 if (p < pool.topAddr)
281 if (pool.baseAddr <= p)
292 * Determine the base address of the block containing p. If p is not a gc
293 * allocated pointer, return null.
295 BlkInfo getInfo(void* p)
298 Pool* pool = findPool(p);
302 info.base = pool.findBase(p);
303 info.size = pool.findSize(info.base);
304 info.attr = getAttr(pool, cast(size_t)(info.base - pool.baseAddr) / 16u);
305 if (has_pointermap(info.attr)) {
306 info.size -= size_t.sizeof; // PointerMap bitmask
307 // Points to the PointerMap bitmask pointer, not user data
308 if (p >= (info.base + info.size)) {
312 if (opts.options.sentinel) {
313 info.base = sentinel_add(info.base);
314 // points to sentinel data, not user data
315 if (p < info.base || p >= sentinel_post(info.base))
317 info.size -= SENTINEL_EXTRA;
324 * Compute bin for size.
326 static Bins findBin(size_t size)
370 * Allocate a new pool of at least size bytes.
371 * Sort it into pools.
372 * Mark all memory in the pool as B_FREE.
373 * Return the actual number of bytes reserved or 0 on error.
375 size_t reserve(size_t size)
378 size_t npages = (size + PAGESIZE - 1) / PAGESIZE;
379 Pool* pool = newPool(npages);
383 return pool.npages * PAGESIZE;
388 * Minimizes physical memory usage by returning free pools to the OS.
396 for (n = 0; n < gc.pools.length; n++)
399 for (pn = 0; pn < pool.npages; pn++)
401 if (cast(Bins)pool.pagetable[pn] != B_FREE)
404 if (pn < pool.npages)
407 gc.pools.remove_at(n);
410 gc.min_addr = gc.pools[0].baseAddr;
411 gc.max_addr = gc.pools[gc.pools.length - 1].topAddr;
416 * Allocate a chunk of memory that is larger than a page.
417 * Return null if out of memory.
419 void *bigAlloc(size_t size)
429 npages = (size + PAGESIZE - 1) / PAGESIZE;
433 // This code could use some refinement when repeatedly
434 // allocating very large arrays.
436 for (n = 0; n < gc.pools.length; n++)
439 pn = pool.allocPages(npages);
454 freedpages = fullcollectshell();
455 if (freedpages >= gc.pools.length * ((POOLSIZE / PAGESIZE) / 4))
460 // Release empty pools to prevent bloat
463 pool = newPool(npages);
469 pn = pool.allocPages(npages);
470 assert(pn != OPFAIL);
473 // Release empty pools to prevent bloat
476 pool = newPool(npages);
479 pn = pool.allocPages(npages);
480 assert(pn != OPFAIL);
490 pool.pagetable[pn] = B_PAGE;
492 memset(&pool.pagetable[pn + 1], B_PAGEPLUS, npages - 1);
493 p = pool.baseAddr + pn * PAGESIZE;
494 memset(cast(char *)p + size, 0, npages * PAGESIZE - size);
495 if (opts.options.mem_stomp)
496 memset(p, 0xF1, size);
500 return null; // let mallocNoSync handle the error
505 * Allocate a new pool with at least npages in it.
506 * Sort it into pools.
507 * Return null if failed.
509 Pool *newPool(size_t npages)
511 // Minimum of POOLSIZE
512 if (npages < POOLSIZE/PAGESIZE)
513 npages = POOLSIZE/PAGESIZE;
514 else if (npages > POOLSIZE/PAGESIZE)
516 // Give us 150% of requested size, so there's room to extend
517 auto n = npages + (npages >> 1);
518 if (n < size_t.max/PAGESIZE)
522 // Allocate successively larger pools up to 8 megs
525 size_t n = gc.pools.length;
527 n = 8; // cap pool size at 8 megs
528 n *= (POOLSIZE / PAGESIZE);
534 p.initialize(npages);
541 Pool* pool = gc.pools.insert_sorted(p);
544 gc.min_addr = gc.pools[0].baseAddr;
545 gc.max_addr = gc.pools[gc.pools.length - 1].topAddr;
552 * Allocate a page of bin's.
556 int allocPage(Bins bin)
564 for (n = 0; n < gc.pools.length; n++)
567 pn = pool.allocPages(1);
574 pool.pagetable[pn] = cast(ubyte)bin;
576 // Convert page to free list
577 size_t size = binsize[bin];
578 List **b = &gc.free_list[bin];
580 p = pool.baseAddr + pn * PAGESIZE;
582 for (; p < ptop; p += size)
584 (cast(List *)p).next = *b;
592 * Marks a range of memory using the conservative bit mask. Used for
593 * the stack, for the data segment, and additional memory ranges.
595 void mark_conservative(void* pbot, void* ptop)
597 mark(pbot, ptop, PointerMap.init.bits.ptr);
602 * Search a range of memory values and mark any pointers into the GC pool.
604 void mark(void *pbot, void *ptop, size_t* pm_bitmask)
606 // TODO: make our own assert because assert uses the GC
607 assert (pbot <= ptop);
609 const BITS_PER_WORD = size_t.sizeof * 8;
611 void **p1 = cast(void **)pbot;
612 void **p2 = cast(void **)ptop;
616 size_t type_size = pm_bitmask[0];
617 size_t* pm_bits = pm_bitmask + 1;
618 bool has_type_info = type_size != 1 || pm_bits[0] != 1 || pm_bits[1] != 0;
620 //printf("marking range: %p -> %p\n", pbot, ptop);
621 for (; p1 + type_size <= p2; p1 += type_size) {
624 while (n < type_size && pm_bits[n / BITS_PER_WORD] == 0)
626 if (n < type_size && (pm_bits[n / BITS_PER_WORD] &
627 ((1 << (BITS_PER_WORD / 2)) - 1)) == 0)
628 n += BITS_PER_WORD / 2;
629 else if (n < type_size && (pm_bits[n / BITS_PER_WORD] &
630 ((1 << (BITS_PER_WORD / 4)) - 1)) == 0)
631 n += BITS_PER_WORD / 4;
633 for (; n < type_size; n++) {
634 // scan bit set for this word
636 !(pm_bits[n / BITS_PER_WORD] & (1 << (n % BITS_PER_WORD))))
641 if (p < gc.min_addr || p >= gc.max_addr)
644 if ((cast(size_t)p & ~(PAGESIZE-1)) == pcache)
647 Pool* pool = findPool(p);
650 size_t offset = cast(size_t)(p - pool.baseAddr);
652 size_t pn = offset / PAGESIZE;
653 Bins bin = cast(Bins)pool.pagetable[pn];
655 // Adjust bit to be at start of allocated memory block
657 bit_i = (offset & notbinsize[bin]) >> 4;
658 else if (bin == B_PAGEPLUS)
664 while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
665 bit_i = pn * (PAGESIZE / 16);
669 // Don't mark bits in B_FREE pages
673 if (bin >= B_PAGE) // Cache B_PAGE and B_PAGEPLUS lookups
674 pcache = cast(size_t)p & ~(PAGESIZE-1);
676 if (!pool.mark.test(bit_i))
678 pool.mark.set(bit_i);
679 if (!pool.noscan.test(bit_i))
681 pool.scan.set(bit_i);
689 gc.any_changes = true;
693 * Return number of full pages free'd.
695 size_t fullcollectshell()
697 gc.stats.collection_started();
699 gc.stats.collection_finished();
701 // The purpose of the 'shell' is to ensure all the registers
702 // get put on the stack so they'll be scanned
707 gcc.builtins.__builtin_unwind_init();
714 uint eax,ecx,edx,ebx,ebp,esi,edi;
727 else version (X86_64)
729 ulong rax,rbx,rcx,rdx,rbp,rsi,rdi,r8,r9,r10,r11,r12,r13,r14,r15;
752 static assert( false, "Architecture not supported." );
763 result = fullcollect(sp);
786 size_t fullcollect(void *stackTop)
791 debug(COLLECT_PRINTF) printf("Gcx.fullcollect()\n");
794 gc.stats.world_stopped();
799 gc.any_changes = false;
800 for (n = 0; n < gc.pools.length; n++)
805 pool.freebits.zero();
808 // Mark each free entry, so it doesn't get scanned
809 for (n = 0; n < B_PAGE; n++)
811 for (List *list = gc.free_list[n]; list; list = list.next)
813 pool = findPool(list);
815 pool.freebits.set(cast(size_t)(cast(byte*)list - pool.baseAddr) / 16);
819 for (n = 0; n < gc.pools.length; n++)
822 pool.mark.copy(&pool.freebits);
825 void mark_conservative_dg(void* pbot, void* ptop)
827 mark_conservative(pbot, ptop);
830 rt_scanStaticData(&mark_conservative_dg);
834 // Scan stacks and registers for each paused thread
835 thread_scanAll(&mark_conservative_dg, stackTop);
839 debug(COLLECT_PRINTF) printf("scan roots[]\n");
840 mark_conservative(gc.roots.ptr, gc.roots.ptr + gc.roots.length);
843 debug(COLLECT_PRINTF) printf("scan ranges[]\n");
844 for (n = 0; n < gc.ranges.length; n++)
846 debug(COLLECT_PRINTF) printf("\t%x .. %x\n", gc.ranges[n].pbot, gc.ranges[n].ptop);
847 mark_conservative(gc.ranges[n].pbot, gc.ranges[n].ptop);
850 debug(COLLECT_PRINTF) printf("\tscan heap\n");
851 while (gc.any_changes)
853 gc.any_changes = false;
854 for (n = 0; n < gc.pools.length; n++)
862 bbase = pool.scan.base();
863 btop = bbase + pool.scan.nwords;
864 for (b = bbase; b < btop;)
880 o = pool.baseAddr + (b - bbase) * 32 * 16;
881 if (!(bitm & 0xFFFF))
886 for (; bitm; o += 16, bitm >>= 1)
891 pn = cast(size_t)(o - pool.baseAddr) / PAGESIZE;
892 bin = cast(Bins)pool.pagetable[pn];
894 if (opts.options.conservative)
895 mark_conservative(o, o + binsize[bin]);
897 auto end_of_blk = cast(size_t**)(o +
898 binsize[bin] - size_t.sizeof);
899 size_t* pm_bitmask = *end_of_blk;
900 mark(o, end_of_blk, pm_bitmask);
903 else if (bin == B_PAGE || bin == B_PAGEPLUS)
905 if (bin == B_PAGEPLUS)
907 while (pool.pagetable[pn - 1] != B_PAGE)
911 while (pn + u < pool.npages &&
912 pool.pagetable[pn + u] == B_PAGEPLUS)
915 size_t blk_size = u * PAGESIZE;
916 if (opts.options.conservative)
917 mark_conservative(o, o + blk_size);
919 auto end_of_blk = cast(size_t**)(o + blk_size -
921 size_t* pm_bitmask = *end_of_blk;
922 mark(o, end_of_blk, pm_bitmask);
931 gc.stats.world_started();
933 // Free up everything not marked
934 debug(COLLECT_PRINTF) printf("\tfree'ing\n");
935 size_t freedpages = 0;
937 for (n = 0; n < gc.pools.length; n++)
940 uint* bbase = pool.mark.base();
942 for (pn = 0; pn < pool.npages; pn++, bbase += PAGESIZE / (32 * 16))
944 Bins bin = cast(Bins)pool.pagetable[pn];
948 auto size = binsize[bin];
949 byte* p = pool.baseAddr + pn * PAGESIZE;
950 byte* ptop = p + PAGESIZE;
951 size_t bit_i = pn * (PAGESIZE/16);
952 size_t bit_stride = size / 16;
954 version(none) // BUG: doesn't work because freebits() must also be cleared
956 // If free'd entire page
957 if (bbase[0] == 0 && bbase[1] == 0 && bbase[2] == 0 &&
958 bbase[3] == 0 && bbase[4] == 0 && bbase[5] == 0 &&
959 bbase[6] == 0 && bbase[7] == 0)
961 for (; p < ptop; p += size, bit_i += bit_stride)
963 if (pool.finals.nbits && pool.finals.testClear(bit_i)) {
964 if (opts.options.sentinel)
965 rt_finalize(cast(List *)sentinel_add(p), false/*gc.no_stack > 0*/);
967 rt_finalize(cast(List *)p, false/*gc.no_stack > 0*/);
969 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
971 List *list = cast(List *)p;
973 if (opts.options.mem_stomp)
974 memset(p, 0xF3, size);
976 pool.pagetable[pn] = B_FREE;
981 for (; p < ptop; p += size, bit_i += bit_stride)
983 if (!pool.mark.test(bit_i))
985 if (opts.options.sentinel)
986 sentinel_Invariant(sentinel_add(p));
988 pool.freebits.set(bit_i);
989 if (pool.finals.nbits && pool.finals.testClear(bit_i)) {
990 if (opts.options.sentinel)
991 rt_finalize(cast(List *)sentinel_add(p), false/*gc.no_stack > 0*/);
993 rt_finalize(cast(List *)p, false/*gc.no_stack > 0*/);
995 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
997 List *list = cast(List *)p;
999 if (opts.options.mem_stomp)
1000 memset(p, 0xF3, size);
1006 else if (bin == B_PAGE)
1008 size_t bit_i = pn * (PAGESIZE / 16);
1009 if (!pool.mark.test(bit_i))
1011 byte *p = pool.baseAddr + pn * PAGESIZE;
1012 if (opts.options.sentinel)
1013 sentinel_Invariant(sentinel_add(p));
1014 if (pool.finals.nbits && pool.finals.testClear(bit_i)) {
1015 if (opts.options.sentinel)
1016 rt_finalize(sentinel_add(p), false/*gc.no_stack > 0*/);
1018 rt_finalize(p, false/*gc.no_stack > 0*/);
1020 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1022 debug(COLLECT_PRINTF) printf("\tcollecting big %x\n", p);
1023 pool.pagetable[pn] = B_FREE;
1025 if (opts.options.mem_stomp)
1026 memset(p, 0xF3, PAGESIZE);
1027 while (pn + 1 < pool.npages && pool.pagetable[pn + 1] == B_PAGEPLUS)
1030 pool.pagetable[pn] = B_FREE;
1033 if (opts.options.mem_stomp)
1036 memset(p, 0xF3, PAGESIZE);
1045 gc.free_list[] = null;
1047 // Free complete pages, rebuild free list
1048 debug(COLLECT_PRINTF) printf("\tfree complete pages\n");
1049 size_t recoveredpages = 0;
1050 for (n = 0; n < gc.pools.length; n++)
1053 for (size_t pn = 0; pn < pool.npages; pn++)
1055 Bins bin = cast(Bins)pool.pagetable[pn];
1061 size_t size = binsize[bin];
1062 size_t bit_stride = size / 16;
1063 size_t bit_base = pn * (PAGESIZE / 16);
1064 size_t bit_top = bit_base + (PAGESIZE / 16);
1068 for (; bit_i < bit_top; bit_i += bit_stride)
1070 if (!pool.freebits.test(bit_i))
1073 pool.pagetable[pn] = B_FREE;
1078 p = pool.baseAddr + pn * PAGESIZE;
1079 for (u = 0; u < PAGESIZE; u += size)
1081 bit_i = bit_base + u / 16;
1082 if (pool.freebits.test(bit_i))
1084 List *list = cast(List *)(p + u);
1085 // avoid unnecessary writes
1086 if (list.next != gc.free_list[bin])
1087 list.next = gc.free_list[bin];
1088 gc.free_list[bin] = list;
1095 debug(COLLECT_PRINTF) printf("recovered pages = %d\n", recoveredpages);
1096 debug(COLLECT_PRINTF) printf("\tfree'd %u bytes, %u pages from %u pools\n", freed, freedpages, gc.pools.length);
1098 return freedpages + recoveredpages;
1105 uint getAttr(Pool* pool, size_t bit_i)
1114 if (pool.finals.nbits &&
1115 pool.finals.test(bit_i))
1116 attrs |= BlkAttr.FINALIZE;
1117 if (pool.noscan.test(bit_i))
1118 attrs |= BlkAttr.NO_SCAN;
1119 // if (pool.nomove.nbits &&
1120 // pool.nomove.test(bit_i))
1121 // attrs |= BlkAttr.NO_MOVE;
1129 void setAttr(Pool* pool, size_t bit_i, uint mask)
1136 if (mask & BlkAttr.FINALIZE)
1138 if (!pool.finals.nbits)
1139 pool.finals.alloc(pool.mark.nbits);
1140 pool.finals.set(bit_i);
1142 if (mask & BlkAttr.NO_SCAN)
1144 pool.noscan.set(bit_i);
1146 // if (mask & BlkAttr.NO_MOVE)
1148 // if (!pool.nomove.nbits)
1149 // pool.nomove.alloc(pool.mark.nbits);
1150 // pool.nomove.set(bit_i);
1158 void clrAttr(Pool* pool, size_t bit_i, uint mask)
1165 if (mask & BlkAttr.FINALIZE && pool.finals.nbits)
1166 pool.finals.clear(bit_i);
1167 if (mask & BlkAttr.NO_SCAN)
1168 pool.noscan.clear(bit_i);
1169 // if (mask & BlkAttr.NO_MOVE && pool.nomove.nbits)
1170 // pool.nomove.clear(bit_i);
1178 gc.stack_bottom = cast(char*)&dummy;
1179 opts.parse(cstdlib.getenv("D_GC_OPTS"));
1180 gc.lock = GCLock.classinfo;
1182 setStackBottom(rt_stackBottom());
1183 gc.stats = Stats(gc);
1190 private void *malloc(size_t size, uint attrs, size_t* pm_bitmask)
1194 gc.stats.malloc_started(size, attrs, pm_bitmask);
1196 gc.stats.malloc_finished(p);
1201 if (opts.options.sentinel)
1202 size += SENTINEL_EXTRA;
1204 bool has_pm = has_pointermap(attrs);
1206 size += size_t.sizeof;
1209 // Cache previous binsize lookup - Dave Fladebo.
1210 static size_t lastsize = -1;
1211 static Bins lastbin;
1212 if (size == lastsize)
1216 bin = findBin(size);
1221 size_t capacity; // to figure out where to store the bitmask
1224 p = gc.free_list[bin];
1227 if (!allocPage(bin) && !gc.disabled) // try to find a new page
1229 if (!thread_needLock())
1231 /* Then we haven't locked it yet. Be sure
1232 * and gc.lock for a collection, since a finalizer
1233 * may start a new thread.
1235 synchronized (gc.lock)
1240 else if (!fullcollectshell()) // collect to find a new page
1245 if (!gc.free_list[bin] && !allocPage(bin))
1247 newPool(1); // allocate new pool to find a new page
1248 int result = allocPage(bin);
1250 onOutOfMemoryError();
1252 p = gc.free_list[bin];
1254 capacity = binsize[bin];
1256 // Return next item from free list
1257 gc.free_list[bin] = (cast(List*)p).next;
1258 if (!(attrs & BlkAttr.NO_SCAN))
1259 memset(p + size, 0, capacity - size);
1260 if (opts.options.mem_stomp)
1261 memset(p, 0xF0, size);
1267 onOutOfMemoryError();
1268 // Round the size up to the number of pages needed to store it
1269 size_t npages = (size + PAGESIZE - 1) / PAGESIZE;
1270 capacity = npages * PAGESIZE;
1273 // Store the bit mask AFTER SENTINEL_POST
1274 // TODO: store it BEFORE, so the bitmask is protected too
1276 auto end_of_blk = cast(size_t**)(p + capacity - size_t.sizeof);
1277 *end_of_blk = pm_bitmask;
1278 size -= size_t.sizeof;
1281 if (opts.options.sentinel) {
1282 size -= SENTINEL_EXTRA;
1283 p = sentinel_add(p);
1284 sentinel_init(p, size);
1289 Pool *pool = findPool(p);
1292 setAttr(pool, cast(size_t)(p - pool.baseAddr) / 16, attrs);
1301 private void *calloc(size_t size, uint attrs, size_t* pm_bitmask)
1305 void *p = malloc(size, attrs, pm_bitmask);
1314 private void *realloc(void *p, size_t size, uint attrs,
1327 p = malloc(size, attrs, pm_bitmask);
1331 Pool* pool = findPool(p);
1335 // Set or retrieve attributes as appropriate
1336 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1338 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1339 setAttr(pool, bit_i, attrs);
1342 attrs = getAttr(pool, bit_i);
1344 void* blk_base_addr = pool.findBase(p);
1345 size_t blk_size = pool.findSize(p);
1346 bool has_pm = has_pointermap(attrs);
1347 size_t pm_bitmask_size = 0;
1349 pm_bitmask_size = size_t.sizeof;
1350 // Retrieve pointer map bit mask if appropriate
1351 if (pm_bitmask is null) {
1352 auto end_of_blk = cast(size_t**)(blk_base_addr +
1353 blk_size - size_t.sizeof);
1354 pm_bitmask = *end_of_blk;
1358 if (opts.options.sentinel)
1360 sentinel_Invariant(p);
1361 size_t sentinel_stored_size = *sentinel_size(p);
1362 if (sentinel_stored_size != size)
1364 void* p2 = malloc(size, attrs, pm_bitmask);
1365 if (sentinel_stored_size < size)
1366 size = sentinel_stored_size;
1367 cstring.memcpy(p2, p, size);
1373 size += pm_bitmask_size;
1374 if (blk_size >= PAGESIZE && size >= PAGESIZE)
1376 auto psz = blk_size / PAGESIZE;
1377 auto newsz = (size + PAGESIZE - 1) / PAGESIZE;
1381 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
1386 if (opts.options.mem_stomp)
1387 memset(p + size - pm_bitmask_size, 0xF2,
1388 blk_size - size - pm_bitmask_size);
1389 pool.freePages(pagenum + newsz, psz - newsz);
1391 auto end_of_blk = cast(size_t**)(
1392 blk_base_addr + (PAGESIZE * newsz) -
1394 *end_of_blk = pm_bitmask;
1398 else if (pagenum + newsz <= pool.npages)
1400 // Attempt to expand in place
1401 for (size_t i = pagenum + psz; 1;)
1403 if (i == pagenum + newsz)
1405 if (opts.options.mem_stomp)
1406 memset(p + blk_size - pm_bitmask_size,
1407 0xF0, size - blk_size
1409 memset(pool.pagetable + pagenum +
1410 psz, B_PAGEPLUS, newsz - psz);
1412 auto end_of_blk = cast(size_t**)(
1414 (PAGESIZE * newsz) -
1416 *end_of_blk = pm_bitmask;
1420 if (i == pool.npages)
1424 if (pool.pagetable[i] != B_FREE)
1430 // if new size is bigger or less than half
1431 if (blk_size < size || blk_size > size * 2)
1433 size -= pm_bitmask_size;
1434 blk_size -= pm_bitmask_size;
1435 void* p2 = malloc(size, attrs, pm_bitmask);
1436 if (blk_size < size)
1438 cstring.memcpy(p2, p, size);
1448 * Attempt to in-place enlarge the memory block pointed to by p by at least
1449 * min_size beyond its current capacity, up to a maximum of max_size. This
1450 * does not attempt to move the memory block (like realloc() does).
1453 * 0 if could not extend p,
1454 * total size of entire memory block if successful.
1456 private size_t extend(void* p, size_t minsize, size_t maxsize)
1459 assert( minsize <= maxsize );
1463 if (opts.options.sentinel)
1466 Pool* pool = findPool(p);
1470 // Retrieve attributes
1471 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1472 uint attrs = getAttr(pool, bit_i);
1474 void* blk_base_addr = pool.findBase(p);
1475 size_t blk_size = pool.findSize(p);
1476 bool has_pm = has_pointermap(attrs);
1477 size_t* pm_bitmask = null;
1478 size_t pm_bitmask_size = 0;
1480 pm_bitmask_size = size_t.sizeof;
1481 // Retrieve pointer map bit mask
1482 auto end_of_blk = cast(size_t**)(blk_base_addr +
1483 blk_size - size_t.sizeof);
1484 pm_bitmask = *end_of_blk;
1486 minsize += size_t.sizeof;
1487 maxsize += size_t.sizeof;
1490 if (blk_size < PAGESIZE)
1491 return 0; // cannot extend buckets
1493 auto psz = blk_size / PAGESIZE;
1494 auto minsz = (minsize + PAGESIZE - 1) / PAGESIZE;
1495 auto maxsz = (maxsize + PAGESIZE - 1) / PAGESIZE;
1497 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
1500 for (sz = 0; sz < maxsz; sz++)
1502 auto i = pagenum + psz + sz;
1503 if (i == pool.npages)
1505 if (pool.pagetable[i] != B_FREE)
1515 size_t new_size = (psz + sz) * PAGESIZE;
1517 if (opts.options.mem_stomp)
1518 memset(p + blk_size - pm_bitmask_size, 0xF0,
1519 new_size - blk_size - pm_bitmask_size);
1520 memset(pool.pagetable + pagenum + psz, B_PAGEPLUS, sz);
1525 new_size -= size_t.sizeof;
1526 auto end_of_blk = cast(size_t**)(blk_base_addr + new_size);
1527 *end_of_blk = pm_bitmask;
1536 private void free(void *p)
1545 // Find which page it is in
1547 if (!pool) // if not one of ours
1549 if (opts.options.sentinel) {
1550 sentinel_Invariant(p);
1551 p = sentinel_sub(p);
1553 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1554 bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1555 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1557 bin = cast(Bins)pool.pagetable[pagenum];
1558 if (bin == B_PAGE) // if large alloc
1563 while (++n < pool.npages && pool.pagetable[n] == B_PAGEPLUS)
1565 if (opts.options.mem_stomp)
1566 memset(p, 0xF2, npages * PAGESIZE);
1567 pool.freePages(pagenum, npages);
1572 List *list = cast(List*)p;
1574 if (opts.options.mem_stomp)
1575 memset(p, 0xF2, binsize[bin]);
1577 list.next = gc.free_list[bin];
1578 gc.free_list[bin] = list;
1584 * Determine the allocated size of pointer p. If p is an interior pointer
1585 * or not a gc allocated pointer, return 0.
1587 private size_t sizeOf(void *p)
1591 if (opts.options.sentinel)
1592 p = sentinel_sub(p);
1594 Pool* pool = findPool(p);
1598 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
1599 uint attrs = getAttr(pool, biti);
1601 size_t size = pool.findSize(p);
1602 size_t pm_bitmask_size = 0;
1603 if (has_pointermap(attrs))
1604 pm_bitmask_size = size_t.sizeof;
1606 if (opts.options.sentinel) {
1607 // Check for interior pointer
1609 // 1) size is a power of 2 for less than PAGESIZE values
1610 // 2) base of memory pool is aligned on PAGESIZE boundary
1611 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
1613 return size - SENTINEL_EXTRA - pm_bitmask_size;
1616 if (p == gc.p_cache)
1617 return gc.size_cache;
1619 // Check for interior pointer
1621 // 1) size is a power of 2 for less than PAGESIZE values
1622 // 2) base of memory pool is aligned on PAGESIZE boundary
1623 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
1627 gc.size_cache = size - pm_bitmask_size;
1629 return gc.size_cache;
1635 * Verify that pointer p:
1636 * 1) belongs to this memory pool
1637 * 2) points to the start of an allocated piece of memory
1638 * 3) is not on a free list
1640 private void checkNoSync(void *p)
1644 if (opts.options.sentinel)
1645 sentinel_Invariant(p);
1653 if (opts.options.sentinel)
1654 p = sentinel_sub(p);
1657 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1658 bin = cast(Bins)pool.pagetable[pagenum];
1659 assert(bin <= B_PAGE);
1660 size = binsize[bin];
1661 assert((cast(size_t)p & (size - 1)) == 0);
1667 // Check that p is not on a free list
1670 for (list = gc.free_list[bin]; list; list = list.next)
1672 assert(cast(void*)list != p);
1683 private void setStackBottom(void *p)
1685 version (STACKGROWSDOWN)
1687 //p = (void *)((uint *)p + 4);
1688 if (p > gc.stack_bottom)
1690 gc.stack_bottom = p;
1695 //p = (void *)((uint *)p - 4);
1696 if (p < gc.stack_bottom)
1698 gc.stack_bottom = cast(char*)p;
1705 * Retrieve statistics about garbage collection.
1706 * Useful for debugging and tuning.
1708 private GCStats getStats()
1718 for (n = 0; n < gc.pools.length; n++)
1720 Pool* pool = gc.pools[n];
1721 psize += pool.npages * PAGESIZE;
1722 for (size_t j = 0; j < pool.npages; j++)
1724 Bins bin = cast(Bins)pool.pagetable[j];
1727 else if (bin == B_PAGE)
1729 else if (bin < B_PAGE)
1734 for (n = 0; n < B_PAGE; n++)
1736 for (List *list = gc.free_list[n]; list; list = list.next)
1737 flsize += binsize[n];
1740 usize = bsize - flsize;
1742 stats.poolsize = psize;
1743 stats.usedsize = bsize - flsize;
1744 stats.freelistsize = flsize;
1748 /******************* weak-reference support *********************/
1750 private struct WeakPointer
1754 void ondestroy(Object r)
1756 assert(r is reference);
1757 // lock for memory consistency (parallel readers)
1758 // also ensures that weakpointerDestroy can be called while another
1759 // thread is freeing the reference with "delete"
1760 return locked!(void, () {
1767 * Create a weak pointer to the given object.
1768 * Returns a pointer to an opaque struct allocated in C memory.
1770 void* weakpointerCreate( Object r )
1774 // must be allocated in C memory
1775 // 1. to hide the reference from the GC
1776 // 2. the GC doesn't scan delegates added by rt_attachDisposeEvent
1778 auto wp = cast(WeakPointer*)(cstdlib.malloc(WeakPointer.sizeof));
1780 onOutOfMemoryError();
1782 rt_attachDisposeEvent(r, &wp.ondestroy);
1789 * Destroy a weak pointer returned by weakpointerCreate().
1790 * If null is passed, nothing happens.
1792 void weakpointerDestroy( void* p )
1796 auto wp = cast(WeakPointer*)p;
1797 // must be extra careful about the GC or parallel threads
1798 // finalizing the reference at the same time
1799 return locked!(void, () {
1801 rt_detachDisposeEvent(wp.reference, &wp.ondestroy);
1808 * Query a weak pointer and return either the object passed to
1809 * weakpointerCreate, or null if it was free'd in the meantime.
1810 * If null is passed, null is returned.
1812 Object weakpointerGet( void* p )
1816 // NOTE: could avoid the lock by using Fawzi style GC counters but
1817 // that'd require core.sync.Atomic and lots of care about memory
1818 // consistency it's an optional optimization see
1819 // http://dsource.org/projects/tango/browser/trunk/user/tango/core/Lifetime.d?rev=5100#L158
1820 return locked!(Object, () {
1821 return (cast(WeakPointer*)p).reference;
1827 /* ============================ Pool =============================== */
1834 GCBits mark; // entries already scanned, or should not be scanned
1835 GCBits scan; // entries that need to be scanned
1836 GCBits freebits; // entries that are on the free list
1837 GCBits finals; // entries that need finalizer run on them
1838 GCBits noscan; // entries that should not be scanned
1844 void initialize(size_t npages)
1846 size_t poolsize = npages * PAGESIZE;
1847 assert(poolsize >= POOLSIZE);
1848 baseAddr = cast(byte *) alloc.os_mem_map(poolsize);
1850 // Some of the code depends on page alignment of memory pools
1851 assert((cast(size_t)baseAddr & (PAGESIZE - 1)) == 0);
1859 topAddr = baseAddr + poolsize;
1861 mark.alloc(cast(size_t)poolsize / 16);
1862 scan.alloc(cast(size_t)poolsize / 16);
1863 freebits.alloc(cast(size_t)poolsize / 16);
1864 noscan.alloc(cast(size_t)poolsize / 16);
1866 pagetable = cast(ubyte*) cstdlib.malloc(npages);
1868 onOutOfMemoryError();
1869 memset(pagetable, B_FREE, npages);
1871 this.npages = npages;
1883 result = alloc.os_mem_unmap(baseAddr, npages * PAGESIZE);
1891 // See Gcx.Dtor() for the rationale of the null check.
1893 cstdlib.free(pagetable);
1913 //freebits.Invariant();
1914 //finals.Invariant();
1915 //noscan.Invariant();
1919 //if (baseAddr + npages * PAGESIZE != topAddr)
1920 //printf("baseAddr = %p, npages = %d, topAddr = %p\n", baseAddr, npages, topAddr);
1921 assert(baseAddr + npages * PAGESIZE == topAddr);
1924 for (size_t i = 0; i < npages; i++)
1926 Bins bin = cast(Bins)pagetable[i];
1927 assert(bin < B_MAX);
1933 * Allocate n pages from Pool.
1934 * Returns OPFAIL on failure.
1936 size_t allocPages(size_t n)
1942 for (i = 0; i < npages; i++)
1944 if (pagetable[i] == B_FREE)
1957 * Free npages pages starting with pagenum.
1959 void freePages(size_t pagenum, size_t npages)
1961 memset(&pagetable[pagenum], B_FREE, npages);
1966 * Find base address of block containing pointer p.
1967 * Returns null if the pointer doesn't belong to this pool
1969 void* findBase(void *p)
1971 size_t offset = cast(size_t)(p - this.baseAddr);
1972 size_t pagenum = offset / PAGESIZE;
1973 Bins bin = cast(Bins)this.pagetable[pagenum];
1974 // Adjust bit to be at start of allocated memory block
1976 return this.baseAddr + (offset & notbinsize[bin]);
1977 if (bin == B_PAGEPLUS) {
1979 --pagenum, offset -= PAGESIZE;
1980 } while (cast(Bins)this.pagetable[pagenum] == B_PAGEPLUS);
1981 return this.baseAddr + (offset & (offset.max ^ (PAGESIZE-1)));
1983 // we are in a B_FREE page
1989 * Find size of pointer p.
1990 * Returns 0 if p doesn't belong to this pool if if it's block size is less
1993 size_t findSize(void *p)
1995 size_t pagenum = cast(size_t)(p - this.baseAddr) / PAGESIZE;
1996 Bins bin = cast(Bins)this.pagetable[pagenum];
1998 return binsize[bin];
1999 for (size_t i = pagenum + 1; i < this.npages; i++)
2000 if (this.pagetable[i] != B_PAGEPLUS)
2001 return (i - pagenum) * PAGESIZE;
2002 return (this.npages - pagenum) * PAGESIZE;
2007 * Used for sorting pools
2009 int opCmp(in Pool other)
2011 if (baseAddr < other.baseAddr)
2014 return cast(int)(baseAddr > other.baseAddr);
2019 /* ============================ SENTINEL =============================== */
2022 const size_t SENTINEL_PRE = cast(size_t) 0xF4F4F4F4F4F4F4F4UL; // 32 or 64 bits
2023 const ubyte SENTINEL_POST = 0xF5; // 8 bits
2024 const uint SENTINEL_EXTRA = 2 * size_t.sizeof + 1;
2027 size_t* sentinel_size(void *p) { return &(cast(size_t *)p)[-2]; }
2028 size_t* sentinel_pre(void *p) { return &(cast(size_t *)p)[-1]; }
2029 ubyte* sentinel_post(void *p) { return &(cast(ubyte *)p)[*sentinel_size(p)]; }
2032 void sentinel_init(void *p, size_t size)
2034 *sentinel_size(p) = size;
2035 *sentinel_pre(p) = SENTINEL_PRE;
2036 *sentinel_post(p) = SENTINEL_POST;
2040 void sentinel_Invariant(void *p)
2042 assert(*sentinel_pre(p) == SENTINEL_PRE);
2043 assert(*sentinel_post(p) == SENTINEL_POST);
2047 void *sentinel_add(void *p)
2049 return p + 2 * size_t.sizeof;
2053 void *sentinel_sub(void *p)
2055 return p - 2 * size_t.sizeof;
2060 /* ============================ C Public Interface ======================== */
2063 private int _termCleanupLevel=1;
2067 /// sets the cleanup level done by gc
2070 /// 2: fullCollect ignoring stack roots (might crash daemonThreads)
2071 /// result !=0 if the value was invalid
2072 int gc_setTermCleanupLevel(int cLevel)
2074 if (cLevel<0 || cLevel>2) return cLevel;
2075 _termCleanupLevel=cLevel;
2079 /// returns the cleanup level done by gc
2080 int gc_getTermCleanupLevel()
2082 return _termCleanupLevel;
2087 scope (exit) assert (Invariant());
2088 gc = cast(GC*) cstdlib.calloc(1, GC.sizeof);
2091 version (DigitalMars) version(OSX) {
2092 _d_osx_image_init();
2094 // NOTE: The GC must initialize the thread library
2095 // before its first collection.
2101 assert (Invariant());
2102 if (_termCleanupLevel<1) {
2104 } else if (_termCleanupLevel==2){
2105 // a more complete cleanup
2106 // NOTE: There may be daemons threads still running when this routine is
2107 // called. If so, cleaning memory out from under then is a good
2108 // way to make them crash horribly.
2109 // Often this probably doesn't matter much since the app is
2110 // supposed to be shutting down anyway, but for example tests might
2111 // crash (and be considerd failed even if the test was ok).
2112 // thus this is not the default and should be enabled by
2113 // I'm disabling cleanup for now until I can think about it some
2116 // not really a 'collect all' -- still scans static data area, roots,
2118 return locked!(void, () {
2124 // default (safe) clenup
2125 return locked!(void, () {
2133 return locked!(void, () {
2134 assert (Invariant()); scope (exit) assert (Invariant());
2135 assert (gc.disabled > 0);
2142 return locked!(void, () {
2143 assert (Invariant()); scope (exit) assert (Invariant());
2150 return locked!(void, () {
2151 assert (Invariant()); scope (exit) assert (Invariant());
2159 return locked!(void, () {
2160 assert (Invariant()); scope (exit) assert (Invariant());
2165 uint gc_getAttr(void* p)
2169 return locked!(uint, () {
2170 assert (Invariant()); scope (exit) assert (Invariant());
2171 Pool* pool = findPool(p);
2174 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2175 return getAttr(pool, bit_i);
2179 uint gc_setAttr(void* p, uint attrs)
2183 return locked!(uint, () {
2184 assert (Invariant()); scope (exit) assert (Invariant());
2185 Pool* pool = findPool(p);
2188 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2189 uint old_attrs = getAttr(pool, bit_i);
2190 setAttr(pool, bit_i, attrs);
2195 uint gc_clrAttr(void* p, uint attrs)
2199 return locked!(uint, () {
2200 assert (Invariant()); scope (exit) assert (Invariant());
2201 Pool* pool = findPool(p);
2204 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2205 uint old_attrs = getAttr(pool, bit_i);
2206 clrAttr(pool, bit_i, attrs);
2211 void* gc_malloc(size_t size, uint attrs = 0,
2212 PointerMap ptrmap = PointerMap.init)
2216 return locked!(void*, () {
2217 assert (Invariant()); scope (exit) assert (Invariant());
2218 return malloc(size, attrs, ptrmap.bits.ptr);
2222 void* gc_calloc(size_t size, uint attrs = 0,
2223 PointerMap ptrmap = PointerMap.init)
2227 return locked!(void*, () {
2228 assert (Invariant()); scope (exit) assert (Invariant());
2229 return calloc(size, attrs, ptrmap.bits.ptr);
2233 void* gc_realloc(void* p, size_t size, uint attrs = 0,
2234 PointerMap ptrmap = PointerMap.init)
2236 return locked!(void*, () {
2237 assert (Invariant()); scope (exit) assert (Invariant());
2238 return realloc(p, size, attrs, ptrmap.bits.ptr);
2242 size_t gc_extend(void* p, size_t min_size, size_t max_size)
2244 return locked!(size_t, () {
2245 assert (Invariant()); scope (exit) assert (Invariant());
2246 return extend(p, min_size, max_size);
2250 size_t gc_reserve(size_t size)
2254 return locked!(size_t, () {
2255 assert (Invariant()); scope (exit) assert (Invariant());
2256 return reserve(size);
2260 void gc_free(void* p)
2264 return locked!(void, () {
2265 assert (Invariant()); scope (exit) assert (Invariant());
2270 void* gc_addrOf(void* p)
2274 return locked!(void*, () {
2275 assert (Invariant()); scope (exit) assert (Invariant());
2276 Pool* pool = findPool(p);
2279 return pool.findBase(p);
2283 size_t gc_sizeOf(void* p)
2287 return locked!(size_t, () {
2288 assert (Invariant()); scope (exit) assert (Invariant());
2293 BlkInfo gc_query(void* p)
2296 return BlkInfo.init;
2297 return locked!(BlkInfo, () {
2298 assert (Invariant()); scope (exit) assert (Invariant());
2303 // NOTE: This routine is experimental. The stats or function name may change
2304 // before it is made officially available.
2307 return locked!(GCStats, () {
2308 assert (Invariant()); scope (exit) assert (Invariant());
2313 void gc_addRoot(void* p)
2317 return locked!(void, () {
2318 assert (Invariant()); scope (exit) assert (Invariant());
2319 if (gc.roots.append(p) is null)
2320 onOutOfMemoryError();
2324 void gc_addRange(void* p, size_t size)
2326 if (p is null || size == 0)
2328 return locked!(void, () {
2329 assert (Invariant()); scope (exit) assert (Invariant());
2330 if (gc.ranges.append(Range(p, p + size)) is null)
2331 onOutOfMemoryError();
2335 void gc_removeRoot(void* p)
2339 return locked!(void, () {
2340 assert (Invariant()); scope (exit) assert (Invariant());
2341 bool r = gc.roots.remove(p);
2346 void gc_removeRange(void* p)
2350 return locked!(void, () {
2351 assert (Invariant()); scope (exit) assert (Invariant());
2352 bool r = gc.ranges.remove(Range(p, null));
2357 void* gc_weakpointerCreate(Object r)
2359 // weakpointers do their own locking
2360 return weakpointerCreate(r);
2363 void gc_weakpointerDestroy(void* wp)
2365 // weakpointers do their own locking
2366 weakpointerDestroy(wp);
2369 Object gc_weakpointerGet(void* wp)
2371 // weakpointers do their own locking
2372 return weakpointerGet(wp);
2376 // vim: set et sw=4 sts=4 :