1 /* -----------------------------------------------------------------------------
2 * $Id: Stable.c,v 1.17 2001/08/14 13:40:09 sewardj Exp $
4 * (c) The GHC Team, 1998-1999
6 * Stable names and stable pointers.
8 * ---------------------------------------------------------------------------*/
10 #include "PosixSource.h"
13 #include "StablePriv.h"
19 /* Comment from ADR's implementation in old RTS:
21 This files (together with @ghc/runtime/storage/PerformIO.lhc@ and a
22 small change in @HpOverflow.lc@) consists of the changes in the
23 runtime system required to implement "Stable Pointers". But we're
24 getting a bit ahead of ourselves --- what is a stable pointer and what
27 When Haskell calls C, it normally just passes over primitive integers,
28 floats, bools, strings, etc. This doesn't cause any problems at all
29 for garbage collection because the act of passing them makes a copy
30 from the heap, stack or wherever they are onto the C-world stack.
31 However, if we were to pass a heap object such as a (Haskell) @String@
32 and a garbage collection occured before we finished using it, we'd run
33 into problems since the heap object might have been moved or even
36 So, if a C call is able to cause a garbage collection or we want to
37 store a pointer to a heap object between C calls, we must be careful
38 when passing heap objects. Our solution is to keep a table of all
39 objects we've given to the C-world and to make sure that the garbage
40 collector collects these objects --- updating the table as required to
41 make sure we can still find the object.
44 Of course, all this rather begs the question: why would we want to
47 One very good reason is to preserve laziness across the language
48 interface. Rather than evaluating an integer or a string because it
49 {\em might\/} be required by the C function, we can wait until the C
50 function actually wants the value and then force an evaluation.
52 Another very good reason (the motivating reason!) is that the C code
53 might want to execute an object of sort $IO ()$ for the side-effects
54 it will produce. For example, this is used when interfacing to an X
55 widgets library to allow a direct implementation of callbacks.
58 The @makeStablePointer :: a -> IO (StablePtr a)@ function
59 converts a value into a stable pointer. It is part of the @PrimIO@
60 monad, because we want to be sure we don't allocate one twice by
61 accident, and then only free one of the copies.
64 makeStablePtr# :: a -> State# RealWorld -> (# RealWorld, a #)
65 freeStablePtr# :: StablePtr# a -> State# RealWorld -> State# RealWorld
66 deRefStablePtr# :: StablePtr# a -> State# RealWorld ->
67 (# State# RealWorld, a #)
70 There may be additional functions on the C side to allow evaluation,
71 application, etc of a stable pointer.
73 When Haskell calls C, it normally just passes over primitive integers,
74 floats, bools, strings, etc. This doesn't cause any problems at all
75 for garbage collection because the act of passing them makes a copy
76 from the heap, stack or wherever they are onto the C-world stack.
77 However, if we were to pass a heap object such as a (Haskell) @String@
78 and a garbage collection occured before we finished using it, we'd run
79 into problems since the heap object might have been moved or even
82 So, if a C call is able to cause a garbage collection or we want to
83 store a pointer to a heap object between C calls, we must be careful
84 when passing heap objects. Our solution is to keep a table of all
85 objects we've given to the C-world and to make sure that the garbage
86 collector collects these objects --- updating the table as required to
87 make sure we can still find the object.
90 snEntry *stable_ptr_table;
91 snEntry *stable_ptr_free;
93 unsigned int SPT_size;
95 /* This hash table maps Haskell objects to stable names, so that every
96 * call to lookupStableName on a given object will return the same
101 * A plain stable name entry has a zero reference count, which means
102 * the entry will dissappear when the object it points to is
103 * unreachable. For stable pointers, we need an entry that sticks
104 * around and keeps the object it points to alive, so each stable name
105 * entry has an associated reference count.
107 * A stable pointer has a weighted reference count N attached to it
108 * (actually in its upper 5 bits), which represents the weight
109 * 2^(N-1). The stable name entry keeps a 32-bit reference count, which
110 * represents any weight between 1 and 2^32 (represented as zero).
111 * When the weight is 2^32, the stable name table owns "all" of the
112 * stable pointers to this object, and the entry can be garbage
113 * collected if the object isn't reachable.
115 * A new stable pointer is given the weight log2(W/2), where W is the
116 * weight stored in the table entry. The new weight in the table is W
119 * A stable pointer can be "split" into two stable pointers, by
120 * dividing the weight by 2 and giving each pointer half.
121 * When freeing a stable pointer, the weight of the pointer is added
122 * to the weight stored in the table entry.
125 HashTable *addrToStableHash;
127 #define INIT_SPT_SIZE 64
130 initFreeList(snEntry *table, nat n, snEntry *free)
134 for (p = table + n - 1; p >= table; p--) {
141 stable_ptr_free = table;
145 initStablePtrTable(void)
147 /* the table will be allocated the first time makeStablePtr is
149 stable_ptr_table = NULL;
150 stable_ptr_free = NULL;
151 addrToStableHash = NULL;
156 * get at the real stuff...remove indirections.
158 * ToDo: move to a better home.
162 removeIndirections(StgClosure* p)
166 while (get_itbl(q)->type == IND ||
167 get_itbl(q)->type == IND_STATIC ||
168 get_itbl(q)->type == IND_OLDGEN ||
169 get_itbl(q)->type == IND_PERM ||
170 get_itbl(q)->type == IND_OLDGEN_PERM ) {
171 q = ((StgInd *)q)->indirectee;
177 lookupStableName(StgPtr p)
181 if (stable_ptr_free == NULL) {
182 enlargeStablePtrTable();
185 /* removing indirections increases the likelihood
186 * of finding a match in the stable name hash table.
188 p = (StgPtr)removeIndirections((StgClosure*)p);
190 (void *)sn = lookupHashTable(addrToStableHash,(W_)p);
193 ASSERT(stable_ptr_table[sn].addr == p);
194 IF_DEBUG(stable,fprintf(stderr,"cached stable name %d at %p\n",sn,p));
197 sn = stable_ptr_free - stable_ptr_table;
198 (P_)stable_ptr_free = stable_ptr_free->addr;
199 stable_ptr_table[sn].weight = 0;
200 stable_ptr_table[sn].addr = p;
201 stable_ptr_table[sn].sn_obj = NULL;
202 /* IF_DEBUG(stable,fprintf(stderr,"new stable name %d at
205 /* add the new stable name to the hash table */
206 insertHashTable(addrToStableHash, (W_)p, (void *)sn);
213 freeStableName(snEntry *sn)
215 ASSERT(sn->sn_obj == NULL);
216 if (sn->addr != NULL) {
217 removeHashTable(addrToStableHash, (W_)sn->addr, NULL);
219 sn->addr = (P_)stable_ptr_free;
220 stable_ptr_free = sn;
224 getStablePtr(StgPtr p)
226 StgWord sn = lookupStableName(p);
228 weight = stable_ptr_table[sn].weight;
230 weight = (StgWord)1 << (BITS_IN(StgWord)-1);
231 stable_ptr_table[sn].weight = weight;
232 return (StgStablePtr)(sn + (BITS_IN(StgWord) << STABLEPTR_WEIGHT_SHIFT));
234 else if (weight == 1) {
235 barf("getStablePtr: too light");
239 /* find log2(weight) */
240 for (n = 0; weight != 1; n++) {
243 stable_ptr_table[sn].weight -= 1 << n;
244 return (StgStablePtr)(sn + ((n+1) << STABLEPTR_WEIGHT_SHIFT));
249 enlargeStablePtrTable(void)
251 nat old_SPT_size = SPT_size;
255 SPT_size = INIT_SPT_SIZE;
256 stable_ptr_table = stgMallocWords(SPT_size * sizeof(snEntry),
257 "initStablePtrTable");
259 /* we don't use index 0 in the stable name table, because that
260 * would conflict with the hash table lookup operations which
261 * return NULL if an entry isn't found in the hash table.
263 initFreeList(stable_ptr_table+1,INIT_SPT_SIZE-1,NULL);
264 addrToStableHash = allocHashTable();
267 // 2nd and subsequent times
270 stgReallocWords(stable_ptr_table, SPT_size * sizeof(snEntry),
271 "enlargeStablePtrTable");
273 initFreeList(stable_ptr_table + old_SPT_size, old_SPT_size, NULL);
277 /* -----------------------------------------------------------------------------
278 * Treat stable pointers as roots for the garbage collector.
280 * A stable pointer is any stable name entry with a weight > 0. We'll
281 * take the opportunity to zero the "keep" flags at the same time.
282 * -------------------------------------------------------------------------- */
285 markStablePtrTable(evac_fn evac)
287 snEntry *p, *end_stable_ptr_table;
290 end_stable_ptr_table = &stable_ptr_table[SPT_size];
292 // Mark all the stable *pointers* (not stable names).
293 // _starting_ at index 1; index 0 is unused.
294 for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
297 // Internal pointers are free slots. If q == NULL, it's a
298 // stable name where the object has been GC'd, but the
299 // StableName object (sn_obj) is still alive.
300 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
302 // save the current addr away: we need to be able to tell
303 // whether the objects moved in order to be able to update
304 // the hash table later.
307 // if the weight is non-zero, treat addr as a root
308 if (p->weight != 0) {
309 evac((StgClosure **)&p->addr);
315 /* -----------------------------------------------------------------------------
316 * Thread the stable pointer table for compacting GC.
318 * Here we must call the supplied evac function for each pointer into
319 * the heap from the stable pointer table, because the compacting
320 * collector may move the object it points to.
321 * -------------------------------------------------------------------------- */
324 threadStablePtrTable( evac_fn evac )
326 snEntry *p, *end_stable_ptr_table;
329 end_stable_ptr_table = &stable_ptr_table[SPT_size];
331 for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
333 if (p->sn_obj != NULL) {
334 evac((StgClosure **)&p->sn_obj);
338 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
339 evac((StgClosure **)&p->addr);
344 /* -----------------------------------------------------------------------------
345 * Garbage collect any dead entries in the stable pointer table.
349 * - a weight of zero (i.e. 2^32)
352 * Both of these conditions must be true in order to re-use the stable
353 * name table entry. We can re-use stable name table entries for live
354 * heap objects, as long as the program has no StableName objects that
355 * refer to the entry.
356 * -------------------------------------------------------------------------- */
359 gcStablePtrTable( void )
361 snEntry *p, *end_stable_ptr_table;
364 end_stable_ptr_table = &stable_ptr_table[SPT_size];
366 // NOTE: _starting_ at index 1; index 0 is unused.
367 for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
369 // Update the pointer to the StableName object, if there is one
370 if (p->sn_obj != NULL) {
371 p->sn_obj = isAlive(p->sn_obj);
374 // Internal pointers are free slots. If q == NULL, it's a
375 // stable name where the object has been GC'd, but the
376 // StableName object (sn_obj) is still alive.
378 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
381 if (p->weight == 0) {
382 if (p->sn_obj == NULL) {
383 // StableName object is dead
385 IF_DEBUG(stable, fprintf(stderr,"GC'd Stable name %d\n",
386 p - stable_ptr_table));
390 (StgClosure *)p->addr = isAlive((StgClosure *)p->addr);
391 IF_DEBUG(stable, fprintf(stderr,"Stable name %d still alive at %p, weight %d\n", p - stable_ptr_table, p->addr, p->weight));
398 /* -----------------------------------------------------------------------------
399 * Update the StablePtr/StableName hash table
401 * The boolean argument 'full' indicates that a major collection is
402 * being done, so we might as well throw away the hash table and build
403 * a new one. For a minor collection, we just re-hash the elements
405 * -------------------------------------------------------------------------- */
408 updateStablePtrTable(rtsBool full)
410 snEntry *p, *end_stable_ptr_table;
412 if (full && addrToStableHash != NULL) {
413 freeHashTable(addrToStableHash,NULL);
414 addrToStableHash = allocHashTable();
417 end_stable_ptr_table = &stable_ptr_table[SPT_size];
419 // NOTE: _starting_ at index 1; index 0 is unused.
420 for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
422 if (p->addr == NULL) {
423 if (p->old != NULL) {
424 // The target has been garbage collected. Remove its
425 // entry from the hash table.
426 removeHashTable(addrToStableHash, (W_)p->old, NULL);
430 else if (p->addr < (P_)stable_ptr_table
431 || p->addr >= (P_)end_stable_ptr_table) {
432 // Target still alive, Re-hash this stable name
434 insertHashTable(addrToStableHash, (W_)p->addr,
435 (void *)(p - stable_ptr_table));
436 } else if (p->addr != p->old) {
437 removeHashTable(addrToStableHash, (W_)p->old, NULL);
438 insertHashTable(addrToStableHash, (W_)p->addr,
439 (void *)(p - stable_ptr_table));