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 = PRINTF; // turn on printf's
34 //debug = COLLECT_PRINTF; // turn on printf's
35 //debug = LOGGING; // log allocations / frees
36 //debug = MEMSTOMP; // stomp on memory
37 //debug = SENTINEL; // add underrun/overrrun protection
38 //debug = PTRCHECK; // more pointer checking
39 //debug = PTRCHECK2; // thorough but slow pointer checking
41 /*************** Configuration *********************/
43 version = STACKGROWSDOWN; // growing the stack means subtracting from the stack pointer
44 // (use for Intel X86 CPUs)
45 // else growing the stack means adding to the stack pointer
47 /***************************************************/
57 // BUG: The following import will likely not work, since the gcc
58 // subdirectory is elsewhere. Instead, perhaps the functions
59 // could be declared directly or some other resolution could
61 import gcc.builtins; // for __builtin_unwind_init
76 FINALIZE = 0b0000_0001,
77 NO_SCAN = 0b0000_0010,
78 NO_MOVE = 0b0000_0100,
79 ALL_BITS = 0b1111_1111
82 extern (C) void* rt_stackBottom();
83 extern (C) void* rt_stackTop();
85 extern (C) void rt_finalize( void* p, bool det = true );
87 alias void delegate(Object) DEvent;
88 extern (C) void rt_attachDisposeEvent(Object h, DEvent e);
89 extern (C) bool rt_detachDisposeEvent(Object h, DEvent e);
92 alias void delegate( void*, void* ) scanFn;
94 extern (C) void rt_scanStaticData( scanFn scan );
96 extern (C) bool thread_needLock();
97 extern (C) void thread_suspendAll();
98 extern (C) void thread_resumeAll();
100 extern (C) void thread_scanAll( scanFn fn, void* curStackTop = null );
102 extern (C) void onOutOfMemoryError();
106 OPFAIL = ~cast(size_t)0
114 /* ======================= Leak Detector =========================== */
129 printf(" p = %x, size = %d, parent = %x ", p, size, parent);
132 printf("%s(%u)", file, line);
152 void reserve(size_t nentries)
154 assert(dim <= allocdim);
155 if (allocdim - dim < nentries)
157 allocdim = (dim + nentries) * 2;
158 assert(dim + nentries <= allocdim);
161 data = cast(Log*) .malloc(allocdim * Log.sizeof);
162 if (!data && allocdim)
163 onOutOfMemoryError();
168 newdata = cast(Log*) .malloc(allocdim * Log.sizeof);
169 if (!newdata && allocdim)
170 onOutOfMemoryError();
171 .memcpy(newdata, data, dim * Log.sizeof);
185 void remove(size_t i)
187 .memmove(data + i, data + i + 1, (dim - i) * Log.sizeof);
194 for (size_t i = 0; i < dim; i++)
199 return OPFAIL; // not found
203 void copy(LogArray *from)
205 reserve(from.dim - dim);
206 assert(from.dim <= allocdim);
207 .memcpy(data, from.data, from.dim * Log.sizeof);
214 /* ============================ GC =============================== */
217 class GCLock { } // just a dummy so we can get a global lock
220 const uint GCVERSION = 1; // increment every time we change interface
225 // For passing to debug code
229 uint gcversion = GCVERSION;
231 Gcx *gcx; // implementation
232 static ClassInfo gcLock; // global lock
237 gcLock = GCLock.classinfo;
238 gcx = cast(Gcx*) .calloc(1, Gcx.sizeof);
240 onOutOfMemoryError();
242 setStackBottom(rt_stackBottom());
262 if (!thread_needLock())
264 assert(gcx.disabled > 0);
267 else synchronized (gcLock)
269 assert(gcx.disabled > 0);
280 if (!thread_needLock())
284 else synchronized (gcLock)
294 uint getAttr(void* p)
303 Pool* pool = gcx.findPool(p);
308 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
310 oldb = gcx.getBits(pool, biti);
315 if (!thread_needLock())
319 else synchronized (gcLock)
329 uint setAttr(void* p, uint mask)
338 Pool* pool = gcx.findPool(p);
343 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
345 oldb = gcx.getBits(pool, biti);
346 gcx.setBits(pool, biti, mask);
351 if (!thread_needLock())
355 else synchronized (gcLock)
365 uint clrAttr(void* p, uint mask)
374 Pool* pool = gcx.findPool(p);
379 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
381 oldb = gcx.getBits(pool, biti);
382 gcx.clrBits(pool, biti, mask);
387 if (!thread_needLock())
391 else synchronized (gcLock)
401 void *malloc(size_t size, uint bits = 0)
408 if (!thread_needLock())
410 return mallocNoSync(size, bits);
412 else synchronized (gcLock)
414 return mallocNoSync(size, bits);
422 private void *mallocNoSync(size_t size, uint bits = 0)
429 //debug(PRINTF) printf("GC::malloc(size = %d, gcx = %p)\n", size, gcx);
432 size += SENTINEL_EXTRA;
435 // Cache previous binsize lookup - Dave Fladebo.
436 static size_t lastsize = -1;
438 if (size == lastsize)
442 bin = gcx.findBin(size);
452 if (!gcx.allocPage(bin) && !gcx.disabled) // try to find a new page
454 if (!thread_needLock())
456 /* Then we haven't locked it yet. Be sure
457 * and lock for a collection, since a finalizer
458 * may start a new thread.
460 synchronized (gcLock)
462 gcx.fullcollectshell();
465 else if (!gcx.fullcollectshell()) // collect to find a new page
470 if (!gcx.bucket[bin] && !gcx.allocPage(bin))
473 gcx.newPool(1); // allocate new pool to find a new page
474 result = gcx.allocPage(bin);
476 onOutOfMemoryError();
481 // Return next item from free list
482 gcx.bucket[bin] = (cast(List*)p).next;
483 if( !(bits & BlkAttr.NO_SCAN) )
484 .memset(p + size, 0, binsize[bin] - size);
485 //debug(PRINTF) printf("\tmalloc => %x\n", p);
486 debug (MEMSTOMP) .memset(p, 0xF0, size);
490 p = gcx.bigAlloc(size);
492 onOutOfMemoryError();
494 size -= SENTINEL_EXTRA;
496 sentinel_init(p, size);
497 gcx.log_malloc(p, size);
501 Pool *pool = gcx.findPool(p);
504 gcx.setBits(pool, cast(size_t)(p - pool.baseAddr) / 16, bits);
513 void *calloc(size_t size, uint bits = 0)
520 if (!thread_needLock())
522 return callocNoSync(size, bits);
524 else synchronized (gcLock)
526 return callocNoSync(size, bits);
534 private void *callocNoSync(size_t size, uint bits = 0)
538 //debug(PRINTF) printf("calloc: %x len %d\n", p, len);
539 void *p = mallocNoSync(size, bits);
548 void *realloc(void *p, size_t size, uint bits = 0)
550 if (!thread_needLock())
552 return reallocNoSync(p, size, bits);
554 else synchronized (gcLock)
556 return reallocNoSync(p, size, bits);
564 private void *reallocNoSync(void *p, size_t size, uint bits = 0)
574 p = mallocNoSync(size, bits);
580 //debug(PRINTF) printf("GC::realloc(p = %x, size = %u)\n", p, size);
583 sentinel_Invariant(p);
584 psize = *sentinel_size(p);
589 Pool *pool = gcx.findPool(p);
593 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
597 gcx.clrBits(pool, biti, BlkAttr.ALL_BITS);
598 gcx.setBits(pool, biti, bits);
602 bits = gcx.getBits(pool, biti);
606 p2 = mallocNoSync(size, bits);
609 //debug(PRINTF) printf("\tcopying %d bytes\n",size);
610 .memcpy(p2, p, size);
616 psize = gcx.findSize(p); // find allocated size
617 if (psize >= PAGESIZE && size >= PAGESIZE)
619 auto psz = psize / PAGESIZE;
620 auto newsz = (size + PAGESIZE - 1) / PAGESIZE;
624 auto pool = gcx.findPool(p);
625 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
629 synchronized (gcLock)
631 debug (MEMSTOMP) .memset(p + size, 0xF2, psize - size);
632 pool.freePages(pagenum + newsz, psz - newsz);
636 else if (pagenum + newsz <= pool.npages)
638 // Attempt to expand in place
639 synchronized (gcLock)
641 for (size_t i = pagenum + psz; 1;)
643 if (i == pagenum + newsz)
645 debug (MEMSTOMP) .memset(p + psize, 0xF0, size - psize);
646 .memset(&pool.pagetable[pagenum + psz], B_PAGEPLUS, newsz - psz);
649 if (i == pool.npages)
653 if (pool.pagetable[i] != B_FREE)
660 if (psize < size || // if new size is bigger
661 psize > size * 2) // or less than half
665 Pool *pool = gcx.findPool(p);
669 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
673 gcx.clrBits(pool, biti, BlkAttr.ALL_BITS);
674 gcx.setBits(pool, biti, bits);
678 bits = gcx.getBits(pool, biti);
682 p2 = mallocNoSync(size, bits);
685 //debug(PRINTF) printf("\tcopying %d bytes\n",size);
686 .memcpy(p2, p, size);
696 * Attempt to in-place enlarge the memory block pointed to by p by at least
697 * minbytes beyond its current capacity, up to a maximum of maxsize. This
698 * does not attempt to move the memory block (like realloc() does).
701 * 0 if could not extend p,
702 * total size of entire memory block if successful.
704 size_t extend(void* p, size_t minsize, size_t maxsize)
706 if (!thread_needLock())
708 return extendNoSync(p, minsize, maxsize);
710 else synchronized (gcLock)
712 return extendNoSync(p, minsize, maxsize);
720 private size_t extendNoSync(void* p, size_t minsize, size_t maxsize)
723 assert( minsize <= maxsize );
727 //debug(PRINTF) printf("GC::extend(p = %x, minsize = %u, maxsize = %u)\n", p, minsize, maxsize);
732 auto psize = gcx.findSize(p); // find allocated size
733 if (psize < PAGESIZE)
734 return 0; // cannot extend buckets
736 auto psz = psize / PAGESIZE;
737 auto minsz = (minsize + PAGESIZE - 1) / PAGESIZE;
738 auto maxsz = (maxsize + PAGESIZE - 1) / PAGESIZE;
740 auto pool = gcx.findPool(p);
741 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
744 for (sz = 0; sz < maxsz; sz++)
746 auto i = pagenum + psz + sz;
747 if (i == pool.npages)
749 if (pool.pagetable[i] != B_FREE)
757 debug (MEMSTOMP) .memset(p + psize, 0xF0, (psz + sz) * PAGESIZE - psize);
758 .memset(pool.pagetable + pagenum + psz, B_PAGEPLUS, sz);
761 return (psz + sz) * PAGESIZE;
768 size_t reserve(size_t size)
775 if (!thread_needLock())
777 return reserveNoSync(size);
779 else synchronized (gcLock)
781 return reserveNoSync(size);
789 private size_t reserveNoSync(size_t size)
794 return gcx.reserve(size);
808 if (!thread_needLock())
810 return freeNoSync(p);
812 else synchronized (gcLock)
814 return freeNoSync(p);
822 private void freeNoSync(void *p)
831 // Find which page it is in
832 pool = gcx.findPool(p);
833 if (!pool) // if not one of ours
835 sentinel_Invariant(p);
837 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
838 biti = cast(size_t)(p - pool.baseAddr) / 16;
839 gcx.clrBits(pool, biti, BlkAttr.ALL_BITS);
841 bin = cast(Bins)pool.pagetable[pagenum];
842 if (bin == B_PAGE) // if large alloc
849 while (++n < pool.npages && pool.pagetable[n] == B_PAGEPLUS)
851 debug (MEMSTOMP) .memset(p, 0xF2, npages * PAGESIZE);
852 pool.freePages(pagenum, npages);
855 { // Add to free list
856 List *list = cast(List*)p;
858 debug (MEMSTOMP) .memset(p, 0xF2, binsize[bin]);
860 list.next = gcx.bucket[bin];
861 gcx.bucket[bin] = list;
863 gcx.log_free(sentinel_add(p));
868 * Determine the base address of the block containing p. If p is not a gc
869 * allocated pointer, return null.
871 void* addrOf(void *p)
878 if (!thread_needLock())
880 return addrOfNoSync(p);
882 else synchronized (gcLock)
884 return addrOfNoSync(p);
892 void* addrOfNoSync(void *p)
899 return gcx.findBase(p);
904 * Determine the allocated size of pointer p. If p is an interior pointer
905 * or not a gc allocated pointer, return 0.
907 size_t sizeOf(void *p)
914 if (!thread_needLock())
916 return sizeOfNoSync(p);
918 else synchronized (gcLock)
920 return sizeOfNoSync(p);
928 private size_t sizeOfNoSync(void *p)
935 size_t size = gcx.findSize(p);
937 // Check for interior pointer
939 // 1) size is a power of 2 for less than PAGESIZE values
940 // 2) base of memory pool is aligned on PAGESIZE boundary
941 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
943 return size ? size - SENTINEL_EXTRA : 0;
947 if (p == gcx.p_cache)
948 return gcx.size_cache;
950 size_t size = gcx.findSize(p);
952 // Check for interior pointer
954 // 1) size is a power of 2 for less than PAGESIZE values
955 // 2) base of memory pool is aligned on PAGESIZE boundary
956 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
961 gcx.size_cache = size;
970 * Determine the base address of the block containing p. If p is not a gc
971 * allocated pointer, return null.
973 BlkInfo query(void *p)
981 if (!thread_needLock())
983 return queryNoSync(p);
985 else synchronized (gcLock)
987 return queryNoSync(p);
995 BlkInfo queryNoSync(void *p)
999 return gcx.getInfo(p);
1004 * Verify that pointer p:
1005 * 1) belongs to this memory pool
1006 * 2) points to the start of an allocated piece of memory
1007 * 3) is not on a free list
1016 if (!thread_needLock())
1020 else synchronized (gcLock)
1030 private void checkNoSync(void *p)
1034 sentinel_Invariant(p);
1042 p = sentinel_sub(p);
1043 pool = gcx.findPool(p);
1045 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1046 bin = cast(Bins)pool.pagetable[pagenum];
1047 assert(bin <= B_PAGE);
1048 size = binsize[bin];
1049 assert((cast(size_t)p & (size - 1)) == 0);
1055 // Check that p is not on a free list
1058 for (list = gcx.bucket[bin]; list; list = list.next)
1060 assert(cast(void*)list != p);
1071 private void setStackBottom(void *p)
1073 version (STACKGROWSDOWN)
1075 //p = (void *)((uint *)p + 4);
1076 if (p > gcx.stackBottom)
1078 //debug(PRINTF) printf("setStackBottom(%x)\n", p);
1079 gcx.stackBottom = p;
1084 //p = (void *)((uint *)p - 4);
1085 if (p < gcx.stackBottom)
1087 //debug(PRINTF) printf("setStackBottom(%x)\n", p);
1088 gcx.stackBottom = cast(char*)p;
1095 * add p to list of roots
1097 void addRoot(void *p)
1104 if (!thread_needLock())
1108 else synchronized (gcLock)
1116 * remove p from list of roots
1118 void removeRoot(void *p)
1125 if (!thread_needLock())
1129 else synchronized (gcLock)
1137 * add range to scan for roots
1139 void addRange(void *p, size_t sz)
1146 //debug(PRINTF) printf("+GC.addRange(pbot = x%x, ptop = x%x)\n", pbot, ptop);
1147 if (!thread_needLock())
1149 gcx.addRange(p, p + sz);
1151 else synchronized (gcLock)
1153 gcx.addRange(p, p + sz);
1155 //debug(PRINTF) printf("-GC.addRange()\n");
1162 void removeRange(void *p)
1169 if (!thread_needLock())
1173 else synchronized (gcLock)
1181 * do full garbage collection
1185 debug(PRINTF) printf("GC.fullCollect()\n");
1187 if (!thread_needLock())
1189 gcx.fullcollectshell();
1191 else synchronized (gcLock)
1193 gcx.fullcollectshell();
1201 debug(PRINTF) printf("poolsize = %x, usedsize = %x, freelistsize = %x\n",
1202 stats.poolsize, stats.usedsize, stats.freelistsize);
1210 * do full garbage collection ignoring roots
1212 void fullCollectNoStack()
1214 if (!thread_needLock())
1217 gcx.fullcollectshell();
1220 else synchronized (gcLock)
1223 gcx.fullcollectshell();
1230 * minimize free space usage
1234 if (!thread_needLock())
1238 else synchronized (gcLock)
1246 * Retrieve statistics about garbage collection.
1247 * Useful for debugging and tuning.
1249 void getStats(out GCStats stats)
1251 if (!thread_needLock())
1253 getStatsNoSync(stats);
1255 else synchronized (gcLock)
1257 getStatsNoSync(stats);
1265 private void getStatsNoSync(out GCStats stats)
1274 //debug(PRINTF) printf("getStats()\n");
1275 .memset(&stats, 0, GCStats.sizeof);
1277 for (n = 0; n < gcx.npools; n++)
1278 { Pool *pool = gcx.pooltable[n];
1280 psize += pool.npages * PAGESIZE;
1281 for (size_t j = 0; j < pool.npages; j++)
1283 Bins bin = cast(Bins)pool.pagetable[j];
1286 else if (bin == B_PAGE)
1288 else if (bin < B_PAGE)
1293 for (n = 0; n < B_PAGE; n++)
1295 //debug(PRINTF) printf("bin %d\n", n);
1296 for (List *list = gcx.bucket[n]; list; list = list.next)
1298 //debug(PRINTF) printf("\tlist %x\n", list);
1299 flsize += binsize[n];
1303 usize = bsize - flsize;
1305 stats.poolsize = psize;
1306 stats.usedsize = bsize - flsize;
1307 stats.freelistsize = flsize;
1310 /******************* weak-reference support *********************/
1312 // call locked if necessary
1313 private T locked(T)(in T delegate() code)
1315 if (thread_needLock)
1316 synchronized(gcLock) return code();
1321 private struct WeakPointer
1325 void ondestroy(Object r)
1327 assert(r is reference);
1328 // lock for memory consistency (parallel readers)
1329 // also ensures that weakpointerDestroy can be called while another
1330 // thread is freeing the reference with "delete"
1331 locked!(void)({ reference = null; });
1336 * Create a weak pointer to the given object.
1337 * Returns a pointer to an opaque struct allocated in C memory.
1339 void* weakpointerCreate( Object r )
1343 // must be allocated in C memory
1344 // 1. to hide the reference from the GC
1345 // 2. the GC doesn't scan delegates added by rt_attachDisposeEvent
1347 auto wp = cast(WeakPointer*)(libc.malloc(WeakPointer.sizeof));
1349 onOutOfMemoryError();
1351 rt_attachDisposeEvent(r, &wp.ondestroy);
1358 * Destroy a weak pointer returned by weakpointerCreate().
1359 * If null is passed, nothing happens.
1361 void weakpointerDestroy( void* p )
1365 auto wp = cast(WeakPointer*)p;
1366 // must be extra careful about the GC or parallel threads
1367 // finalizing the reference at the same time
1370 rt_detachDisposeEvent(wp.reference, &wp.ondestroy);
1377 * Query a weak pointer and return either the object passed to
1378 * weakpointerCreate, or null if it was free'd in the meantime.
1379 * If null is passed, null is returned.
1381 Object weakpointerGet( void* p )
1385 // NOTE: could avoid the lock by using Fawzi style GC counters but
1386 // that'd require core.sync.Atomic and lots of care about memory
1387 // consistency it's an optional optimization see
1388 // http://dsource.org/projects/tango/browser/trunk/user/tango/core/Lifetime.d?rev=5100#L158
1389 return locked!(Object)({
1390 return (cast(WeakPointer*)p).reference;
1397 /* ============================ Gcx =============================== */
1401 POOLSIZE = (4096*256),
1415 B_PAGE, // start of large alloc
1416 B_PAGEPLUS, // continuation of large alloc
1417 B_FREE, // free page
1438 const uint binsize[B_MAX] = [ 16,32,64,128,256,512,1024,2048,4096 ];
1439 const uint notbinsize[B_MAX] = [ ~(16u-1),~(32u-1),~(64u-1),~(128u-1),~(256u-1),
1440 ~(512u-1),~(1024u-1),~(2048u-1),~(4096u-1) ];
1442 /* ============================ Gcx =============================== */
1459 uint noStack; // !=0 means don't scan stack
1460 uint log; // turn on logging
1464 int disabled; // turn off collections if >0
1466 byte *minAddr; // min(baseAddr)
1467 byte *maxAddr; // max(topAddr)
1472 List *bucket[B_MAX]; // free list for each size
1478 (cast(byte*)this)[0 .. Gcx.sizeof] = 0;
1479 stackBottom = cast(char*)&dummy;
1481 //printf("gcx = %p, self = %x\n", this, self);
1490 for (size_t i = 0; i < npools; i++)
1491 { Pool *pool = pooltable[i];
1507 void Invariant() { }
1514 //printf("Gcx.invariant(): this = %p\n", this);
1517 for (i = 0; i < npools; i++)
1518 { Pool *pool = pooltable[i];
1523 assert(minAddr == pool.baseAddr);
1527 assert(pool.opCmp(pooltable[i + 1]) < 0);
1529 else if (i + 1 == npools)
1531 assert(maxAddr == pool.topAddr);
1537 assert(rootdim != 0);
1538 assert(nroots <= rootdim);
1543 assert(rangedim != 0);
1544 assert(nranges <= rangedim);
1546 for (i = 0; i < nranges; i++)
1548 assert(ranges[i].pbot);
1549 assert(ranges[i].ptop);
1550 assert(ranges[i].pbot <= ranges[i].ptop);
1554 for (i = 0; i < B_PAGE; i++)
1556 for (List *list = bucket[i]; list; list = list.next)
1567 void addRoot(void *p)
1569 if (nroots == rootdim)
1571 size_t newdim = rootdim * 2 + 16;
1574 newroots = cast(void**) .malloc(newdim * newroots[0].sizeof);
1576 onOutOfMemoryError();
1578 { .memcpy(newroots, roots, nroots * newroots[0].sizeof);
1592 void removeRoot(void *p)
1594 for (size_t i = nroots; i--;)
1599 .memmove(roots + i, roots + i + 1, (nroots - i) * roots[0].sizeof);
1610 void addRange(void *pbot, void *ptop)
1612 debug (PRINTF) printf("%x.Gcx::addRange(%x, %x), nranges = %d\n", this,
1613 pbot, ptop, nranges);
1614 if (nranges == rangedim)
1616 size_t newdim = rangedim * 2 + 16;
1619 newranges = cast(Range*) .malloc(newdim * newranges[0].sizeof);
1621 onOutOfMemoryError();
1623 { .memcpy(newranges, ranges, nranges * newranges[0].sizeof);
1629 ranges[nranges].pbot = pbot;
1630 ranges[nranges].ptop = ptop;
1638 void removeRange(void *pbot)
1640 debug (PRINTF) printf("%x.Gcx.removeRange(%x), nranges = %d\n", this,
1642 for (size_t i = nranges; i--;)
1644 if (ranges[i].pbot == pbot)
1647 .memmove(ranges + i, ranges + i + 1, (nranges - i) * ranges[0].sizeof);
1651 debug(PRINTF) printf("Wrong thread\n");
1653 // This is a fatal error, but ignore it.
1654 // The problem is that we can get a Close() call on a thread
1655 // other than the one the range was allocated on.
1661 * Find Pool that pointer is in.
1662 * Return null if not in a Pool.
1663 * Assume pooltable[] is sorted.
1665 Pool *findPool(void *p)
1667 if (p >= minAddr && p < maxAddr)
1671 return pooltable[0];
1674 for (size_t i = 0; i < npools; i++)
1677 pool = pooltable[i];
1678 if (p < pool.topAddr)
1679 { if (pool.baseAddr <= p)
1690 * Find base address of block containing pointer p.
1691 * Returns null if not a gc'd pointer
1693 void* findBase(void *p)
1700 size_t offset = cast(size_t)(p - pool.baseAddr);
1701 size_t pn = offset / PAGESIZE;
1702 Bins bin = cast(Bins)pool.pagetable[pn];
1704 // Adjust bit to be at start of allocated memory block
1707 return pool.baseAddr + (offset & notbinsize[bin]);
1709 else if (bin == B_PAGEPLUS)
1712 { --pn, offset -= PAGESIZE;
1713 } while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
1715 return pool.baseAddr + (offset & (offset.max ^ (PAGESIZE-1)));
1719 // we are in a B_FREE page
1728 * Find size of pointer p.
1729 * Returns 0 if not a gc'd pointer
1731 size_t findSize(void *p)
1742 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1743 bin = cast(Bins)pool.pagetable[pagenum];
1744 size = binsize[bin];
1750 pt = &pool.pagetable[0];
1751 for (i = pagenum + 1; i < pool.npages; i++)
1753 if (pt[i] != B_PAGEPLUS)
1756 size = (i - pagenum) * PAGESIZE;
1766 BlkInfo getInfo(void* p)
1774 size_t offset = cast(size_t)(p - pool.baseAddr);
1775 size_t pn = offset / PAGESIZE;
1776 Bins bin = cast(Bins)pool.pagetable[pn];
1778 ////////////////////////////////////////////////////////////////////
1780 ////////////////////////////////////////////////////////////////////
1784 info.base = pool.baseAddr + (offset & notbinsize[bin]);
1786 else if (bin == B_PAGEPLUS)
1789 { --pn, offset -= PAGESIZE;
1790 } while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
1792 info.base = pool.baseAddr + (offset & (offset.max ^ (PAGESIZE-1)));
1794 // fix bin for use by size calc below
1795 bin = cast(Bins)pool.pagetable[pn];
1798 ////////////////////////////////////////////////////////////////////
1800 ////////////////////////////////////////////////////////////////////
1802 info.size = binsize[bin];
1808 pt = &pool.pagetable[0];
1809 for (i = pn + 1; i < pool.npages; i++)
1811 if (pt[i] != B_PAGEPLUS)
1814 info.size = (i - pn) * PAGESIZE;
1817 ////////////////////////////////////////////////////////////////////
1819 ////////////////////////////////////////////////////////////////////
1821 info.attr = getBits(pool, cast(size_t)(offset / 16));
1828 * Compute bin for size.
1830 static Bins findBin(size_t size)
1839 else if (size <= 32)
1874 * Allocate a new pool of at least size bytes.
1875 * Sort it into pooltable[].
1876 * Mark all memory in the pool as B_FREE.
1877 * Return the actual number of bytes reserved or 0 on error.
1879 size_t reserve(size_t size)
1881 size_t npages = (size + PAGESIZE - 1) / PAGESIZE;
1882 Pool* pool = newPool(npages);
1886 return pool.npages * PAGESIZE;
1891 * Minimizes physical memory usage by returning free pools to the OS.
1899 for (n = 0; n < npools; n++)
1901 pool = pooltable[n];
1902 for (pn = 0; pn < pool.npages; pn++)
1904 if (cast(Bins)pool.pagetable[pn] != B_FREE)
1907 if (pn < pool.npages)
1914 .memmove(pooltable + n,
1916 (--npools - n) * (Pool*).sizeof);
1917 minAddr = pooltable[0].baseAddr;
1918 maxAddr = pooltable[npools - 1].topAddr;
1924 * Allocate a chunk of memory that is larger than a page.
1925 * Return null if out of memory.
1927 void *bigAlloc(size_t size)
1937 npages = (size + PAGESIZE - 1) / PAGESIZE;
1941 // This code could use some refinement when repeatedly
1942 // allocating very large arrays.
1944 for (n = 0; n < npools; n++)
1946 pool = pooltable[n];
1947 pn = pool.allocPages(npages);
1961 freedpages = fullcollectshell();
1962 if (freedpages >= npools * ((POOLSIZE / PAGESIZE) / 4))
1966 // Release empty pools to prevent bloat
1968 // Allocate new pool
1969 pool = newPool(npages);
1974 pn = pool.allocPages(npages);
1975 assert(pn != OPFAIL);
1978 // Release empty pools to prevent bloat
1980 // Allocate new pool
1981 pool = newPool(npages);
1984 pn = pool.allocPages(npages);
1985 assert(pn != OPFAIL);
1995 pool.pagetable[pn] = B_PAGE;
1997 .memset(&pool.pagetable[pn + 1], B_PAGEPLUS, npages - 1);
1998 p = pool.baseAddr + pn * PAGESIZE;
1999 .memset(cast(char *)p + size, 0, npages * PAGESIZE - size);
2000 debug (MEMSTOMP) .memset(p, 0xF1, size);
2001 //debug(PRINTF) printf("\tp = %x\n", p);
2005 return null; // let mallocNoSync handle the error
2010 * Allocate a new pool with at least npages in it.
2011 * Sort it into pooltable[].
2012 * Return null if failed.
2014 Pool *newPool(size_t npages)
2017 Pool** newpooltable;
2021 //debug(PRINTF) printf("************Gcx::newPool(npages = %d)****************\n", npages);
2023 // Minimum of POOLSIZE
2024 if (npages < POOLSIZE/PAGESIZE)
2025 npages = POOLSIZE/PAGESIZE;
2026 else if (npages > POOLSIZE/PAGESIZE)
2027 { // Give us 150% of requested size, so there's room to extend
2028 auto n = npages + (npages >> 1);
2029 if (n < size_t.max/PAGESIZE)
2033 // Allocate successively larger pools up to 8 megs
2039 n = 8; // cap pool size at 8 megs
2040 n *= (POOLSIZE / PAGESIZE);
2045 pool = cast(Pool *) .calloc(1, Pool.sizeof);
2048 pool.initialize(npages);
2052 newnpools = npools + 1;
2053 newpooltable = cast(Pool **) .realloc(pooltable, newnpools * (Pool *).sizeof);
2057 // Sort pool into newpooltable[]
2058 for (i = 0; i < npools; i++)
2060 if (pool.opCmp(newpooltable[i]) < 0)
2063 .memmove(newpooltable + i + 1, newpooltable + i, (npools - i) * (Pool *).sizeof);
2064 newpooltable[i] = pool;
2066 pooltable = newpooltable;
2069 minAddr = pooltable[0].baseAddr;
2070 maxAddr = pooltable[npools - 1].topAddr;
2082 * Allocate a page of bin's.
2086 int allocPage(Bins bin)
2094 //debug(PRINTF) printf("Gcx::allocPage(bin = %d)\n", bin);
2095 for (n = 0; n < npools; n++)
2097 pool = pooltable[n];
2098 pn = pool.allocPages(1);
2105 pool.pagetable[pn] = cast(ubyte)bin;
2107 // Convert page to free list
2108 size_t size = binsize[bin];
2109 List **b = &bucket[bin];
2111 p = pool.baseAddr + pn * PAGESIZE;
2112 ptop = p + PAGESIZE;
2113 for (; p < ptop; p += size)
2115 (cast(List *)p).next = *b;
2123 * Search a range of memory values and mark any pointers into the GC pool.
2125 void mark(void *pbot, void *ptop)
2127 void **p1 = cast(void **)pbot;
2128 void **p2 = cast(void **)ptop;
2132 //printf("marking range: %p -> %p\n", pbot, ptop);
2133 for (; p1 < p2; p1++)
2136 byte *p = cast(byte *)(*p1);
2138 //if (log) debug(PRINTF) printf("\tmark %x\n", p);
2139 if (p >= minAddr && p < maxAddr)
2141 if ((cast(size_t)p & ~(PAGESIZE-1)) == pcache)
2147 size_t offset = cast(size_t)(p - pool.baseAddr);
2149 size_t pn = offset / PAGESIZE;
2150 Bins bin = cast(Bins)pool.pagetable[pn];
2152 //debug(PRINTF) printf("\t\tfound pool %x, base=%x, pn = %d, bin = %d, biti = x%x\n", pool, pool.baseAddr, pn, bin, biti);
2154 // Adjust bit to be at start of allocated memory block
2157 biti = (offset & notbinsize[bin]) >> 4;
2158 //debug(PRINTF) printf("\t\tbiti = x%x\n", biti);
2160 else if (bin == B_PAGEPLUS)
2164 } while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
2165 biti = pn * (PAGESIZE / 16);
2169 // Don't mark bits in B_FREE pages
2173 if (bin >= B_PAGE) // Cache B_PAGE and B_PAGEPLUS lookups
2174 pcache = cast(size_t)p & ~(PAGESIZE-1);
2176 //debug(PRINTF) printf("\t\tmark(x%x) = %d\n", biti, pool.mark.test(biti));
2177 if (!pool.mark.test(biti))
2179 //if (log) debug(PRINTF) printf("\t\tmarking %x\n", p);
2180 pool.mark.set(biti);
2181 if (!pool.noscan.test(biti))
2183 pool.scan.set(biti);
2186 log_parent(sentinel_add(pool.baseAddr + biti * 16), sentinel_add(pbot));
2191 anychanges |= changes;
2196 * Return number of full pages free'd.
2198 size_t fullcollectshell()
2200 // The purpose of the 'shell' is to ensure all the registers
2201 // get put on the stack so they'll be scanned
2206 __builtin_unwind_init();
2213 uint eax,ecx,edx,ebx,ebp,esi,edi;
2226 else version (X86_64)
2228 ulong rax,rbx,rcx,rdx,rbp,rsi,rdi,r8,r9,r10,r11,r12,r13,r14,r15;
2231 movq rax[RBP], RAX ;
2232 movq rbx[RBP], RBX ;
2233 movq rcx[RBP], RCX ;
2234 movq rdx[RBP], RDX ;
2235 movq rbp[RBP], RBP ;
2236 movq rsi[RBP], RSI ;
2237 movq rdi[RBP], RDI ;
2240 movq r10[RBP], R10 ;
2241 movq r11[RBP], R11 ;
2242 movq r12[RBP], R12 ;
2243 movq r13[RBP], R13 ;
2244 movq r14[RBP], R14 ;
2245 movq r15[RBP], R15 ;
2251 static assert( false, "Architecture not supported." );
2262 result = fullcollect(sp);
2285 size_t fullcollect(void *stackTop)
2290 debug(COLLECT_PRINTF) printf("Gcx.fullcollect()\n");
2292 thread_suspendAll();
2298 for (n = 0; n < npools; n++)
2300 pool = pooltable[n];
2303 pool.freebits.zero();
2306 // Mark each free entry, so it doesn't get scanned
2307 for (n = 0; n < B_PAGE; n++)
2309 for (List *list = bucket[n]; list; list = list.next)
2311 pool = findPool(list);
2313 pool.freebits.set(cast(size_t)(cast(byte*)list - pool.baseAddr) / 16);
2317 for (n = 0; n < npools; n++)
2319 pool = pooltable[n];
2320 pool.mark.copy(&pool.freebits);
2323 rt_scanStaticData( &mark );
2327 // Scan stacks and registers for each paused thread
2328 thread_scanAll( &mark, stackTop );
2332 debug(COLLECT_PRINTF) printf("scan roots[]\n");
2333 mark(roots, roots + nroots);
2336 debug(COLLECT_PRINTF) printf("scan ranges[]\n");
2338 for (n = 0; n < nranges; n++)
2340 debug(COLLECT_PRINTF) printf("\t%x .. %x\n", ranges[n].pbot, ranges[n].ptop);
2341 mark(ranges[n].pbot, ranges[n].ptop);
2345 debug(COLLECT_PRINTF) printf("\tscan heap\n");
2349 for (n = 0; n < npools; n++)
2355 pool = pooltable[n];
2357 bbase = pool.scan.base();
2358 btop = bbase + pool.scan.nwords;
2359 for (b = bbase; b < btop;)
2373 o = pool.baseAddr + (b - bbase) * 32 * 16;
2374 if (!(bitm & 0xFFFF))
2379 for (; bitm; o += 16, bitm >>= 1)
2384 pn = cast(size_t)(o - pool.baseAddr) / PAGESIZE;
2385 bin = cast(Bins)pool.pagetable[pn];
2388 mark(o, o + binsize[bin]);
2390 else if (bin == B_PAGE || bin == B_PAGEPLUS)
2392 if (bin == B_PAGEPLUS)
2394 while (pool.pagetable[pn - 1] != B_PAGE)
2398 while (pn + u < pool.npages && pool.pagetable[pn + u] == B_PAGEPLUS)
2400 mark(o, o + u * PAGESIZE);
2409 // Free up everything not marked
2410 debug(COLLECT_PRINTF) printf("\tfree'ing\n");
2411 size_t freedpages = 0;
2413 for (n = 0; n < npools; n++)
2417 pool = pooltable[n];
2418 bbase = pool.mark.base();
2419 for (pn = 0; pn < pool.npages; pn++, bbase += PAGESIZE / (32 * 16))
2421 Bins bin = cast(Bins)pool.pagetable[pn];
2428 auto size = binsize[bin];
2430 p = pool.baseAddr + pn * PAGESIZE;
2431 ptop = p + PAGESIZE;
2432 biti = pn * (PAGESIZE/16);
2433 bitstride = size / 16;
2435 version(none) // BUG: doesn't work because freebits() must also be cleared
2437 // If free'd entire page
2438 if (bbase[0] == 0 && bbase[1] == 0 && bbase[2] == 0 && bbase[3] == 0 &&
2439 bbase[4] == 0 && bbase[5] == 0 && bbase[6] == 0 && bbase[7] == 0)
2441 for (; p < ptop; p += size, biti += bitstride)
2443 if (pool.finals.nbits && pool.finals.testClear(biti))
2444 rt_finalize(cast(List *)sentinel_add(p), false/*noStack > 0*/);
2445 gcx.clrBits(pool, biti, BlkAttr.ALL_BITS);
2447 List *list = cast(List *)p;
2448 //debug(PRINTF) printf("\tcollecting %x\n", list);
2449 log_free(sentinel_add(list));
2451 debug (MEMSTOMP) .memset(p, 0xF3, size);
2453 pool.pagetable[pn] = B_FREE;
2455 //debug(PRINTF) printf("freeing entire page %d\n", pn);
2459 for (; p < ptop; p += size, biti += bitstride)
2461 if (!pool.mark.test(biti))
2463 sentinel_Invariant(sentinel_add(p));
2465 pool.freebits.set(biti);
2466 if (pool.finals.nbits && pool.finals.testClear(biti))
2467 rt_finalize(cast(List *)sentinel_add(p), false/*noStack > 0*/);
2468 clrBits(pool, biti, BlkAttr.ALL_BITS);
2470 List *list = cast(List *)p;
2471 debug(PRINTF) printf("\tcollecting %x\n", list);
2472 log_free(sentinel_add(list));
2474 debug (MEMSTOMP) .memset(p, 0xF3, size);
2480 else if (bin == B_PAGE)
2481 { size_t biti = pn * (PAGESIZE / 16);
2483 if (!pool.mark.test(biti))
2484 { byte *p = pool.baseAddr + pn * PAGESIZE;
2486 sentinel_Invariant(sentinel_add(p));
2487 if (pool.finals.nbits && pool.finals.testClear(biti))
2488 rt_finalize(sentinel_add(p), false/*noStack > 0*/);
2489 clrBits(pool, biti, BlkAttr.ALL_BITS);
2491 debug(COLLECT_PRINTF) printf("\tcollecting big %x\n", p);
2492 log_free(sentinel_add(p));
2493 pool.pagetable[pn] = B_FREE;
2495 debug (MEMSTOMP) .memset(p, 0xF3, PAGESIZE);
2496 while (pn + 1 < pool.npages && pool.pagetable[pn + 1] == B_PAGEPLUS)
2499 pool.pagetable[pn] = B_FREE;
2504 .memset(p, 0xF3, PAGESIZE);
2515 // Free complete pages, rebuild free list
2516 debug(COLLECT_PRINTF) printf("\tfree complete pages\n");
2517 size_t recoveredpages = 0;
2518 for (n = 0; n < npools; n++)
2521 pool = pooltable[n];
2522 for (pn = 0; pn < pool.npages; pn++)
2524 Bins bin = cast(Bins)pool.pagetable[pn];
2530 size_t size = binsize[bin];
2531 size_t bitstride = size / 16;
2532 size_t bitbase = pn * (PAGESIZE / 16);
2533 size_t bittop = bitbase + (PAGESIZE / 16);
2537 for (biti = bitbase; biti < bittop; biti += bitstride)
2538 { if (!pool.freebits.test(biti))
2541 pool.pagetable[pn] = B_FREE;
2546 p = pool.baseAddr + pn * PAGESIZE;
2547 for (u = 0; u < PAGESIZE; u += size)
2548 { biti = bitbase + u / 16;
2549 if (pool.freebits.test(biti))
2552 list = cast(List *)(p + u);
2553 if (list.next != bucket[bin]) // avoid unnecessary writes
2554 list.next = bucket[bin];
2562 debug(COLLECT_PRINTF) printf("recovered pages = %d\n", recoveredpages);
2563 debug(COLLECT_PRINTF) printf("\tfree'd %u bytes, %u pages from %u pools\n", freed, freedpages, npools);
2565 return freedpages + recoveredpages;
2572 uint getBits(Pool* pool, size_t biti)
2581 if (pool.finals.nbits &&
2582 pool.finals.test(biti))
2583 bits |= BlkAttr.FINALIZE;
2584 if (pool.noscan.test(biti))
2585 bits |= BlkAttr.NO_SCAN;
2586 // if (pool.nomove.nbits &&
2587 // pool.nomove.test(biti))
2588 // bits |= BlkAttr.NO_MOVE;
2596 void setBits(Pool* pool, size_t biti, uint mask)
2603 if (mask & BlkAttr.FINALIZE)
2605 if (!pool.finals.nbits)
2606 pool.finals.alloc(pool.mark.nbits);
2607 pool.finals.set(biti);
2609 if (mask & BlkAttr.NO_SCAN)
2611 pool.noscan.set(biti);
2613 // if (mask & BlkAttr.NO_MOVE)
2615 // if (!pool.nomove.nbits)
2616 // pool.nomove.alloc(pool.mark.nbits);
2617 // pool.nomove.set(biti);
2625 void clrBits(Pool* pool, size_t biti, uint mask)
2632 if (mask & BlkAttr.FINALIZE && pool.finals.nbits)
2633 pool.finals.clear(biti);
2634 if (mask & BlkAttr.NO_SCAN)
2635 pool.noscan.clear(biti);
2636 // if (mask & BlkAttr.NO_MOVE && pool.nomove.nbits)
2637 // pool.nomove.clear(biti);
2641 /***** Leak Detector ******/
2652 //debug(PRINTF) printf("+log_init()\n");
2653 current.reserve(1000);
2655 //debug(PRINTF) printf("-log_init()\n");
2659 void log_malloc(void *p, size_t size)
2661 //debug(PRINTF) printf("+log_malloc(p = %x, size = %d)\n", p, size);
2674 //debug(PRINTF) printf("-log_malloc()\n");
2678 void log_free(void *p)
2680 //debug(PRINTF) printf("+log_free(%x)\n", p);
2683 i = current.find(p);
2686 debug(PRINTF) printf("free'ing unallocated memory %x\n", p);
2690 //debug(PRINTF) printf("-log_free()\n");
2696 //debug(PRINTF) printf("+log_collect()\n");
2697 // Print everything in current that is not in prev
2699 debug(PRINTF) printf("New pointers this cycle: --------------------------------\n");
2701 for (size_t i = 0; i < current.dim; i++)
2705 j = prev.find(current.data[i].p);
2707 current.data[i].print();
2712 debug(PRINTF) printf("All roots this cycle: --------------------------------\n");
2713 for (size_t i = 0; i < current.dim; i++)
2718 p = current.data[i].p;
2719 if (!findPool(current.data[i].parent))
2721 j = prev.find(current.data[i].p);
2723 debug(PRINTF) printf("N");
2725 debug(PRINTF) printf(" ");;
2726 current.data[i].print();
2730 debug(PRINTF) printf("Used = %d-------------------------------------------------\n", used);
2731 prev.copy(¤t);
2733 debug(PRINTF) printf("-log_collect()\n");
2737 void log_parent(void *p, void *parent)
2739 //debug(PRINTF) printf("+log_parent()\n");
2742 i = current.find(p);
2745 debug(PRINTF) printf("parent'ing unallocated memory %x, parent = %x\n", p, parent);
2749 size_t offset = cast(size_t)(p - pool.baseAddr);
2751 size_t pn = offset / PAGESIZE;
2752 Bins bin = cast(Bins)pool.pagetable[pn];
2753 biti = (offset & notbinsize[bin]);
2754 debug(PRINTF) printf("\tbin = %d, offset = x%x, biti = x%x\n", bin, offset, biti);
2758 current.data[i].parent = parent;
2760 //debug(PRINTF) printf("-log_parent()\n");
2767 void log_malloc(void *p, size_t size) { }
2768 void log_free(void *p) { }
2769 void log_collect() { }
2770 void log_parent(void *p, void *parent) { }
2775 /* ============================ Pool =============================== */
2782 GCBits mark; // entries already scanned, or should not be scanned
2783 GCBits scan; // entries that need to be scanned
2784 GCBits freebits; // entries that are on the free list
2785 GCBits finals; // entries that need finalizer run on them
2786 GCBits noscan; // entries that should not be scanned
2792 void initialize(size_t npages)
2796 //debug(PRINTF) printf("Pool::Pool(%u)\n", npages);
2797 poolsize = npages * PAGESIZE;
2798 assert(poolsize >= POOLSIZE);
2799 baseAddr = cast(byte *)os_mem_map(poolsize);
2801 // Some of the code depends on page alignment of memory pools
2802 assert((cast(size_t)baseAddr & (PAGESIZE - 1)) == 0);
2806 //debug(PRINTF) printf("GC fail: poolsize = x%x, errno = %d\n", poolsize, errno);
2807 //debug(PRINTF) printf("message = '%s'\n", sys_errlist[errno]);
2813 topAddr = baseAddr + poolsize;
2815 mark.alloc(cast(size_t)poolsize / 16);
2816 scan.alloc(cast(size_t)poolsize / 16);
2817 freebits.alloc(cast(size_t)poolsize / 16);
2818 noscan.alloc(cast(size_t)poolsize / 16);
2820 pagetable = cast(ubyte*) .malloc(npages);
2822 onOutOfMemoryError();
2823 .memset(pagetable, B_FREE, npages);
2825 this.npages = npages;
2837 result = os_mem_unmap(baseAddr, npages * PAGESIZE);
2856 void Invariant() { }
2863 //freebits.Invariant();
2864 //finals.Invariant();
2865 //noscan.Invariant();
2869 //if (baseAddr + npages * PAGESIZE != topAddr)
2870 //printf("baseAddr = %p, npages = %d, topAddr = %p\n", baseAddr, npages, topAddr);
2871 assert(baseAddr + npages * PAGESIZE == topAddr);
2874 for (size_t i = 0; i < npages; i++)
2875 { Bins bin = cast(Bins)pagetable[i];
2877 assert(bin < B_MAX);
2883 * Allocate n pages from Pool.
2884 * Returns OPFAIL on failure.
2886 size_t allocPages(size_t n)
2891 //debug(PRINTF) printf("Pool::allocPages(n = %d)\n", n);
2893 for (i = 0; i < npages; i++)
2895 if (pagetable[i] == B_FREE)
2898 { //debug(PRINTF) printf("\texisting pn = %d\n", i - n + 1);
2910 * Free npages pages starting with pagenum.
2912 void freePages(size_t pagenum, size_t npages)
2914 .memset(&pagetable[pagenum], B_FREE, npages);
2919 * Used for sorting pooltable[]
2923 if (baseAddr < p2.baseAddr)
2926 return cast(int)(baseAddr > p2.baseAddr);
2931 /* ============================ SENTINEL =============================== */
2936 const size_t SENTINEL_PRE = cast(size_t) 0xF4F4F4F4F4F4F4F4UL; // 32 or 64 bits
2937 const ubyte SENTINEL_POST = 0xF5; // 8 bits
2938 const uint SENTINEL_EXTRA = 2 * size_t.sizeof + 1;
2941 size_t* sentinel_size(void *p) { return &(cast(size_t *)p)[-2]; }
2942 size_t* sentinel_pre(void *p) { return &(cast(size_t *)p)[-1]; }
2943 ubyte* sentinel_post(void *p) { return &(cast(ubyte *)p)[*sentinel_size(p)]; }
2946 void sentinel_init(void *p, size_t size)
2948 *sentinel_size(p) = size;
2949 *sentinel_pre(p) = SENTINEL_PRE;
2950 *sentinel_post(p) = SENTINEL_POST;
2954 void sentinel_Invariant(void *p)
2956 assert(*sentinel_pre(p) == SENTINEL_PRE);
2957 assert(*sentinel_post(p) == SENTINEL_POST);
2961 void *sentinel_add(void *p)
2963 return p + 2 * size_t.sizeof;
2967 void *sentinel_sub(void *p)
2969 return p - 2 * size_t.sizeof;
2974 const uint SENTINEL_EXTRA = 0;
2977 void sentinel_init(void *p, size_t size)
2982 void sentinel_Invariant(void *p)
2987 void *sentinel_add(void *p)
2993 void *sentinel_sub(void *p)