1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2002
5 * Stable names and stable pointers.
7 * ---------------------------------------------------------------------------*/
9 // Make static versions of inline functions in Stable.h:
12 #include "PosixSource.h"
20 /* Comment from ADR's implementation in old RTS:
22 This files (together with @ghc/runtime/storage/PerformIO.lhc@ and a
23 small change in @HpOverflow.lc@) consists of the changes in the
24 runtime system required to implement "Stable Pointers". But we're
25 getting a bit ahead of ourselves --- what is a stable pointer and what
28 When Haskell calls C, it normally just passes over primitive integers,
29 floats, bools, strings, etc. This doesn't cause any problems at all
30 for garbage collection because the act of passing them makes a copy
31 from the heap, stack or wherever they are onto the C-world stack.
32 However, if we were to pass a heap object such as a (Haskell) @String@
33 and a garbage collection occured before we finished using it, we'd run
34 into problems since the heap object might have been moved or even
37 So, if a C call is able to cause a garbage collection or we want to
38 store a pointer to a heap object between C calls, we must be careful
39 when passing heap objects. Our solution is to keep a table of all
40 objects we've given to the C-world and to make sure that the garbage
41 collector collects these objects --- updating the table as required to
42 make sure we can still find the object.
45 Of course, all this rather begs the question: why would we want to
48 One very good reason is to preserve laziness across the language
49 interface. Rather than evaluating an integer or a string because it
50 {\em might\/} be required by the C function, we can wait until the C
51 function actually wants the value and then force an evaluation.
53 Another very good reason (the motivating reason!) is that the C code
54 might want to execute an object of sort $IO ()$ for the side-effects
55 it will produce. For example, this is used when interfacing to an X
56 widgets library to allow a direct implementation of callbacks.
59 The @makeStablePointer :: a -> IO (StablePtr a)@ function
60 converts a value into a stable pointer. It is part of the @PrimIO@
61 monad, because we want to be sure we don't allocate one twice by
62 accident, and then only free one of the copies.
65 makeStablePtr# :: a -> State# RealWorld -> (# RealWorld, a #)
66 freeStablePtr# :: StablePtr# a -> State# RealWorld -> State# RealWorld
67 deRefStablePtr# :: StablePtr# a -> State# RealWorld ->
68 (# State# RealWorld, a #)
71 There may be additional functions on the C side to allow evaluation,
72 application, etc of a stable pointer.
76 snEntry *stable_ptr_table = NULL;
77 static snEntry *stable_ptr_free = NULL;
79 static unsigned int SPT_size = 0;
81 /* This hash table maps Haskell objects to stable names, so that every
82 * call to lookupStableName on a given object will return the same
85 * OLD COMMENTS about reference counting follow. The reference count
86 * in a stable name entry is now just a counter.
90 * A plain stable name entry has a zero reference count, which means
91 * the entry will dissappear when the object it points to is
92 * unreachable. For stable pointers, we need an entry that sticks
93 * around and keeps the object it points to alive, so each stable name
94 * entry has an associated reference count.
96 * A stable pointer has a weighted reference count N attached to it
97 * (actually in its upper 5 bits), which represents the weight
98 * 2^(N-1). The stable name entry keeps a 32-bit reference count, which
99 * represents any weight between 1 and 2^32 (represented as zero).
100 * When the weight is 2^32, the stable name table owns "all" of the
101 * stable pointers to this object, and the entry can be garbage
102 * collected if the object isn't reachable.
104 * A new stable pointer is given the weight log2(W/2), where W is the
105 * weight stored in the table entry. The new weight in the table is W
108 * A stable pointer can be "split" into two stable pointers, by
109 * dividing the weight by 2 and giving each pointer half.
110 * When freeing a stable pointer, the weight of the pointer is added
111 * to the weight stored in the table entry.
114 static HashTable *addrToStableHash = NULL;
116 #define INIT_SPT_SIZE 64
119 initFreeList(snEntry *table, nat n, snEntry *free)
123 for (p = table + n - 1; p >= table; p--) {
130 stable_ptr_free = table;
134 initStablePtrTable(void)
137 // the table will be allocated the first time makeStablePtr is
138 // called, and we want the table to persist through multiple inits.
142 * get at the real stuff...remove indirections.
144 * ToDo: move to a better home.
148 removeIndirections(StgClosure* p)
152 while (get_itbl(q)->type == IND ||
153 get_itbl(q)->type == IND_STATIC ||
154 get_itbl(q)->type == IND_OLDGEN ||
155 get_itbl(q)->type == IND_PERM ||
156 get_itbl(q)->type == IND_OLDGEN_PERM ) {
157 q = ((StgInd *)q)->indirectee;
163 lookupStableName(StgPtr p)
168 if (stable_ptr_free == NULL) {
169 enlargeStablePtrTable();
172 /* removing indirections increases the likelihood
173 * of finding a match in the stable name hash table.
175 p = (StgPtr)removeIndirections((StgClosure*)p);
177 sn_tmp = lookupHashTable(addrToStableHash,(W_)p);
178 sn = (StgWord)sn_tmp;
181 ASSERT(stable_ptr_table[sn].addr == p);
182 IF_DEBUG(stable,debugBelch("cached stable name %d at %p\n",sn,p));
185 sn = stable_ptr_free - stable_ptr_table;
186 stable_ptr_free = (snEntry*)(stable_ptr_free->addr);
187 stable_ptr_table[sn].ref = 0;
188 stable_ptr_table[sn].addr = p;
189 stable_ptr_table[sn].sn_obj = NULL;
190 /* IF_DEBUG(stable,debugBelch("new stable name %d at %p\n",sn,p)); */
192 /* add the new stable name to the hash table */
193 insertHashTable(addrToStableHash, (W_)p, (void *)sn);
200 freeStableName(snEntry *sn)
202 ASSERT(sn->sn_obj == NULL);
203 if (sn->addr != NULL) {
204 removeHashTable(addrToStableHash, (W_)sn->addr, NULL);
206 sn->addr = (P_)stable_ptr_free;
207 stable_ptr_free = sn;
211 getStablePtr(StgPtr p)
215 sn = lookupStableName(p);
216 stable_ptr_table[sn].ref++;
217 return (StgStablePtr)(sn);
221 freeStablePtr(StgStablePtr sp)
223 snEntry *sn = &stable_ptr_table[(StgWord)sp];
225 ASSERT((StgWord)sp < SPT_size && sn->addr != NULL && sn->ref > 0);
229 // If this entry has no StableName attached, then just free it
230 // immediately. This is important; it might be a while before the
231 // next major GC which actually collects the entry.
232 if (sn->sn_obj == NULL && sn->ref == 0) {
238 enlargeStablePtrTable(void)
240 nat old_SPT_size = SPT_size;
244 SPT_size = INIT_SPT_SIZE;
245 stable_ptr_table = stgMallocBytes(SPT_size * sizeof(snEntry),
246 "enlargeStablePtrTable");
248 /* we don't use index 0 in the stable name table, because that
249 * would conflict with the hash table lookup operations which
250 * return NULL if an entry isn't found in the hash table.
252 initFreeList(stable_ptr_table+1,INIT_SPT_SIZE-1,NULL);
253 addrToStableHash = allocHashTable();
256 // 2nd and subsequent times
259 stgReallocBytes(stable_ptr_table,
260 SPT_size * sizeof(snEntry),
261 "enlargeStablePtrTable");
263 initFreeList(stable_ptr_table + old_SPT_size, old_SPT_size, NULL);
267 /* -----------------------------------------------------------------------------
268 * Treat stable pointers as roots for the garbage collector.
270 * A stable pointer is any stable name entry with a ref > 0. We'll
271 * take the opportunity to zero the "keep" flags at the same time.
272 * -------------------------------------------------------------------------- */
275 markStablePtrTable(evac_fn evac)
277 snEntry *p, *end_stable_ptr_table;
280 end_stable_ptr_table = &stable_ptr_table[SPT_size];
282 // Mark all the stable *pointers* (not stable names).
283 // _starting_ at index 1; index 0 is unused.
284 for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
287 // Internal pointers are free slots. If q == NULL, it's a
288 // stable name where the object has been GC'd, but the
289 // StableName object (sn_obj) is still alive.
290 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
292 // save the current addr away: we need to be able to tell
293 // whether the objects moved in order to be able to update
294 // the hash table later.
297 // if the ref is non-zero, treat addr as a root
299 evac((StgClosure **)&p->addr);
305 /* -----------------------------------------------------------------------------
306 * Thread the stable pointer table for compacting GC.
308 * Here we must call the supplied evac function for each pointer into
309 * the heap from the stable pointer table, because the compacting
310 * collector may move the object it points to.
311 * -------------------------------------------------------------------------- */
314 threadStablePtrTable( evac_fn evac )
316 snEntry *p, *end_stable_ptr_table;
319 end_stable_ptr_table = &stable_ptr_table[SPT_size];
321 for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
323 if (p->sn_obj != NULL) {
324 evac((StgClosure **)&p->sn_obj);
328 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
329 evac((StgClosure **)&p->addr);
334 /* -----------------------------------------------------------------------------
335 * Garbage collect any dead entries in the stable pointer table.
339 * - a zero reference count
342 * Both of these conditions must be true in order to re-use the stable
343 * name table entry. We can re-use stable name table entries for live
344 * heap objects, as long as the program has no StableName objects that
345 * refer to the entry.
346 * -------------------------------------------------------------------------- */
349 gcStablePtrTable( void )
351 snEntry *p, *end_stable_ptr_table;
354 end_stable_ptr_table = &stable_ptr_table[SPT_size];
356 // NOTE: _starting_ at index 1; index 0 is unused.
357 for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
359 // Update the pointer to the StableName object, if there is one
360 if (p->sn_obj != NULL) {
361 p->sn_obj = isAlive(p->sn_obj);
364 // Internal pointers are free slots. If q == NULL, it's a
365 // stable name where the object has been GC'd, but the
366 // StableName object (sn_obj) is still alive.
368 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
372 if (p->sn_obj == NULL) {
373 // StableName object is dead
375 IF_DEBUG(stable, debugBelch("GC'd Stable name %d\n",
376 p - stable_ptr_table));
380 p->addr = (StgPtr)isAlive((StgClosure *)p->addr);
381 IF_DEBUG(stable, debugBelch("Stable name %d still alive at %p, ref %d\n", p - stable_ptr_table, p->addr, p->ref));
388 /* -----------------------------------------------------------------------------
389 * Update the StablePtr/StableName hash table
391 * The boolean argument 'full' indicates that a major collection is
392 * being done, so we might as well throw away the hash table and build
393 * a new one. For a minor collection, we just re-hash the elements
395 * -------------------------------------------------------------------------- */
398 updateStablePtrTable(rtsBool full)
400 snEntry *p, *end_stable_ptr_table;
402 if (full && addrToStableHash != NULL) {
403 freeHashTable(addrToStableHash,NULL);
404 addrToStableHash = allocHashTable();
407 end_stable_ptr_table = &stable_ptr_table[SPT_size];
409 // NOTE: _starting_ at index 1; index 0 is unused.
410 for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
412 if (p->addr == NULL) {
413 if (p->old != NULL) {
414 // The target has been garbage collected. Remove its
415 // entry from the hash table.
416 removeHashTable(addrToStableHash, (W_)p->old, NULL);
420 else if (p->addr < (P_)stable_ptr_table
421 || p->addr >= (P_)end_stable_ptr_table) {
422 // Target still alive, Re-hash this stable name
424 insertHashTable(addrToStableHash, (W_)p->addr,
425 (void *)(p - stable_ptr_table));
426 } else if (p->addr != p->old) {
427 removeHashTable(addrToStableHash, (W_)p->old, NULL);
428 insertHashTable(addrToStableHash, (W_)p->addr,
429 (void *)(p - stable_ptr_table));