1 /* -----------------------------------------------------------------------------
2 * $Id: Stable.c,v 1.25 2003/03/31 19:19:34 sof Exp $
4 * (c) The GHC Team, 1998-2002
6 * Stable names and stable pointers.
8 * ---------------------------------------------------------------------------*/
10 // Make static versions of inline functions in Stable.h:
13 #include "PosixSource.h"
16 #include "StablePriv.h"
22 /* Comment from ADR's implementation in old RTS:
24 This files (together with @ghc/runtime/storage/PerformIO.lhc@ and a
25 small change in @HpOverflow.lc@) consists of the changes in the
26 runtime system required to implement "Stable Pointers". But we're
27 getting a bit ahead of ourselves --- what is a stable pointer and what
30 When Haskell calls C, it normally just passes over primitive integers,
31 floats, bools, strings, etc. This doesn't cause any problems at all
32 for garbage collection because the act of passing them makes a copy
33 from the heap, stack or wherever they are onto the C-world stack.
34 However, if we were to pass a heap object such as a (Haskell) @String@
35 and a garbage collection occured before we finished using it, we'd run
36 into problems since the heap object might have been moved or even
39 So, if a C call is able to cause a garbage collection or we want to
40 store a pointer to a heap object between C calls, we must be careful
41 when passing heap objects. Our solution is to keep a table of all
42 objects we've given to the C-world and to make sure that the garbage
43 collector collects these objects --- updating the table as required to
44 make sure we can still find the object.
47 Of course, all this rather begs the question: why would we want to
50 One very good reason is to preserve laziness across the language
51 interface. Rather than evaluating an integer or a string because it
52 {\em might\/} be required by the C function, we can wait until the C
53 function actually wants the value and then force an evaluation.
55 Another very good reason (the motivating reason!) is that the C code
56 might want to execute an object of sort $IO ()$ for the side-effects
57 it will produce. For example, this is used when interfacing to an X
58 widgets library to allow a direct implementation of callbacks.
61 The @makeStablePointer :: a -> IO (StablePtr a)@ function
62 converts a value into a stable pointer. It is part of the @PrimIO@
63 monad, because we want to be sure we don't allocate one twice by
64 accident, and then only free one of the copies.
67 makeStablePtr# :: a -> State# RealWorld -> (# RealWorld, a #)
68 freeStablePtr# :: StablePtr# a -> State# RealWorld -> State# RealWorld
69 deRefStablePtr# :: StablePtr# a -> State# RealWorld ->
70 (# State# RealWorld, a #)
73 There may be additional functions on the C side to allow evaluation,
74 application, etc of a stable pointer.
76 When Haskell calls C, it normally just passes over primitive integers,
77 floats, bools, strings, etc. This doesn't cause any problems at all
78 for garbage collection because the act of passing them makes a copy
79 from the heap, stack or wherever they are onto the C-world stack.
80 However, if we were to pass a heap object such as a (Haskell) @String@
81 and a garbage collection occured before we finished using it, we'd run
82 into problems since the heap object might have been moved or even
85 So, if a C call is able to cause a garbage collection or we want to
86 store a pointer to a heap object between C calls, we must be careful
87 when passing heap objects. Our solution is to keep a table of all
88 objects we've given to the C-world and to make sure that the garbage
89 collector collects these objects --- updating the table as required to
90 make sure we can still find the object.
93 snEntry *stable_ptr_table = NULL;
94 static snEntry *stable_ptr_free = NULL;
96 static unsigned int SPT_size = 0;
98 /* This hash table maps Haskell objects to stable names, so that every
99 * call to lookupStableName on a given object will return the same
102 * OLD COMMENTS about reference counting follow. The reference count
103 * in a stable name entry is now just a counter.
107 * A plain stable name entry has a zero reference count, which means
108 * the entry will dissappear when the object it points to is
109 * unreachable. For stable pointers, we need an entry that sticks
110 * around and keeps the object it points to alive, so each stable name
111 * entry has an associated reference count.
113 * A stable pointer has a weighted reference count N attached to it
114 * (actually in its upper 5 bits), which represents the weight
115 * 2^(N-1). The stable name entry keeps a 32-bit reference count, which
116 * represents any weight between 1 and 2^32 (represented as zero).
117 * When the weight is 2^32, the stable name table owns "all" of the
118 * stable pointers to this object, and the entry can be garbage
119 * collected if the object isn't reachable.
121 * A new stable pointer is given the weight log2(W/2), where W is the
122 * weight stored in the table entry. The new weight in the table is W
125 * A stable pointer can be "split" into two stable pointers, by
126 * dividing the weight by 2 and giving each pointer half.
127 * When freeing a stable pointer, the weight of the pointer is added
128 * to the weight stored in the table entry.
131 static HashTable *addrToStableHash = NULL;
133 #define INIT_SPT_SIZE 64
136 initFreeList(snEntry *table, nat n, snEntry *free)
140 for (p = table + n - 1; p >= table; p--) {
147 stable_ptr_free = table;
151 initStablePtrTable(void)
154 // the table will be allocated the first time makeStablePtr is
155 // called, and we want the table to persist through multiple inits.
159 * get at the real stuff...remove indirections.
161 * ToDo: move to a better home.
165 removeIndirections(StgClosure* p)
169 while (get_itbl(q)->type == IND ||
170 get_itbl(q)->type == IND_STATIC ||
171 get_itbl(q)->type == IND_OLDGEN ||
172 get_itbl(q)->type == IND_PERM ||
173 get_itbl(q)->type == IND_OLDGEN_PERM ) {
174 q = ((StgInd *)q)->indirectee;
180 lookupStableName(StgPtr p)
184 if (stable_ptr_free == NULL) {
185 enlargeStablePtrTable();
188 /* removing indirections increases the likelihood
189 * of finding a match in the stable name hash table.
191 p = (StgPtr)removeIndirections((StgClosure*)p);
193 (void *)sn = lookupHashTable(addrToStableHash,(W_)p);
196 ASSERT(stable_ptr_table[sn].addr == p);
197 IF_DEBUG(stable,fprintf(stderr,"cached stable name %d at %p\n",sn,p));
200 sn = stable_ptr_free - stable_ptr_table;
201 (P_)stable_ptr_free = stable_ptr_free->addr;
202 stable_ptr_table[sn].ref = 0;
203 stable_ptr_table[sn].addr = p;
204 stable_ptr_table[sn].sn_obj = NULL;
205 /* IF_DEBUG(stable,fprintf(stderr,"new stable name %d at
208 /* add the new stable name to the hash table */
209 insertHashTable(addrToStableHash, (W_)p, (void *)sn);
216 freeStableName(snEntry *sn)
218 ASSERT(sn->sn_obj == NULL);
219 if (sn->addr != NULL) {
220 removeHashTable(addrToStableHash, (W_)sn->addr, NULL);
222 sn->addr = (P_)stable_ptr_free;
223 stable_ptr_free = sn;
227 getStablePtr(StgPtr p)
231 sn = lookupStableName(p);
232 stable_ptr_table[sn].ref++;
233 return (StgStablePtr)(sn);
237 freeStablePtr(StgStablePtr sp)
239 snEntry *sn = &stable_ptr_table[(StgWord)sp];
241 ASSERT((StgWord)sp < SPT_size && sn->addr != NULL && sn->ref > 0);
245 // If this entry has no StableName attached, then just free it
246 // immediately. This is important; it might be a while before the
247 // next major GC which actually collects the entry.
248 if (sn->sn_obj == NULL && sn->ref == 0) {
254 enlargeStablePtrTable(void)
256 nat old_SPT_size = SPT_size;
260 SPT_size = INIT_SPT_SIZE;
261 stable_ptr_table = stgMallocBytes(SPT_size * sizeof(snEntry),
262 "enlargeStablePtrTable");
264 /* we don't use index 0 in the stable name table, because that
265 * would conflict with the hash table lookup operations which
266 * return NULL if an entry isn't found in the hash table.
268 initFreeList(stable_ptr_table+1,INIT_SPT_SIZE-1,NULL);
269 addrToStableHash = allocHashTable();
272 // 2nd and subsequent times
275 stgReallocBytes(stable_ptr_table,
276 SPT_size * sizeof(snEntry),
277 "enlargeStablePtrTable");
279 initFreeList(stable_ptr_table + old_SPT_size, old_SPT_size, NULL);
283 /* -----------------------------------------------------------------------------
284 * Treat stable pointers as roots for the garbage collector.
286 * A stable pointer is any stable name entry with a ref > 0. We'll
287 * take the opportunity to zero the "keep" flags at the same time.
288 * -------------------------------------------------------------------------- */
291 markStablePtrTable(evac_fn evac)
293 snEntry *p, *end_stable_ptr_table;
296 end_stable_ptr_table = &stable_ptr_table[SPT_size];
298 // Mark all the stable *pointers* (not stable names).
299 // _starting_ at index 1; index 0 is unused.
300 for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
303 // Internal pointers are free slots. If q == NULL, it's a
304 // stable name where the object has been GC'd, but the
305 // StableName object (sn_obj) is still alive.
306 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
308 // save the current addr away: we need to be able to tell
309 // whether the objects moved in order to be able to update
310 // the hash table later.
313 // if the ref is non-zero, treat addr as a root
315 evac((StgClosure **)&p->addr);
321 /* -----------------------------------------------------------------------------
322 * Thread the stable pointer table for compacting GC.
324 * Here we must call the supplied evac function for each pointer into
325 * the heap from the stable pointer table, because the compacting
326 * collector may move the object it points to.
327 * -------------------------------------------------------------------------- */
330 threadStablePtrTable( evac_fn evac )
332 snEntry *p, *end_stable_ptr_table;
335 end_stable_ptr_table = &stable_ptr_table[SPT_size];
337 for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
339 if (p->sn_obj != NULL) {
340 evac((StgClosure **)&p->sn_obj);
344 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
345 evac((StgClosure **)&p->addr);
350 /* -----------------------------------------------------------------------------
351 * Garbage collect any dead entries in the stable pointer table.
355 * - a zero reference count
358 * Both of these conditions must be true in order to re-use the stable
359 * name table entry. We can re-use stable name table entries for live
360 * heap objects, as long as the program has no StableName objects that
361 * refer to the entry.
362 * -------------------------------------------------------------------------- */
365 gcStablePtrTable( void )
367 snEntry *p, *end_stable_ptr_table;
370 end_stable_ptr_table = &stable_ptr_table[SPT_size];
372 // NOTE: _starting_ at index 1; index 0 is unused.
373 for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
375 // Update the pointer to the StableName object, if there is one
376 if (p->sn_obj != NULL) {
377 p->sn_obj = isAlive(p->sn_obj);
380 // Internal pointers are free slots. If q == NULL, it's a
381 // stable name where the object has been GC'd, but the
382 // StableName object (sn_obj) is still alive.
384 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
388 if (p->sn_obj == NULL) {
389 // StableName object is dead
391 IF_DEBUG(stable, fprintf(stderr,"GC'd Stable name %d\n",
392 p - stable_ptr_table));
396 (StgClosure *)p->addr = isAlive((StgClosure *)p->addr);
397 IF_DEBUG(stable, fprintf(stderr,"Stable name %d still alive at %p, ref %d\n", p - stable_ptr_table, p->addr, p->ref));
404 /* -----------------------------------------------------------------------------
405 * Update the StablePtr/StableName hash table
407 * The boolean argument 'full' indicates that a major collection is
408 * being done, so we might as well throw away the hash table and build
409 * a new one. For a minor collection, we just re-hash the elements
411 * -------------------------------------------------------------------------- */
414 updateStablePtrTable(rtsBool full)
416 snEntry *p, *end_stable_ptr_table;
418 if (full && addrToStableHash != NULL) {
419 freeHashTable(addrToStableHash,NULL);
420 addrToStableHash = allocHashTable();
423 end_stable_ptr_table = &stable_ptr_table[SPT_size];
425 // NOTE: _starting_ at index 1; index 0 is unused.
426 for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
428 if (p->addr == NULL) {
429 if (p->old != NULL) {
430 // The target has been garbage collected. Remove its
431 // entry from the hash table.
432 removeHashTable(addrToStableHash, (W_)p->old, NULL);
436 else if (p->addr < (P_)stable_ptr_table
437 || p->addr >= (P_)end_stable_ptr_table) {
438 // Target still alive, Re-hash this stable name
440 insertHashTable(addrToStableHash, (W_)p->addr,
441 (void *)(p - stable_ptr_table));
442 } else if (p->addr != p->old) {
443 removeHashTable(addrToStableHash, (W_)p->old, NULL);
444 insertHashTable(addrToStableHash, (W_)p->addr,
445 (void *)(p - stable_ptr_table));