1 /* -----------------------------------------------------------------------------
2 * $Id: Stable.c,v 1.9 1999/10/26 17:15:39 sewardj Exp $
4 * (c) The GHC Team, 1998-1999
6 * Stable names and stable pointers.
8 * ---------------------------------------------------------------------------*/
12 #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 #)
69 There is also a C procedure @FreeStablePtr@ which frees a stable pointer.
71 There may be additional functions on the C side to allow evaluation,
72 application, etc of a stable pointer.
74 When Haskell calls C, it normally just passes over primitive integers,
75 floats, bools, strings, etc. This doesn't cause any problems at all
76 for garbage collection because the act of passing them makes a copy
77 from the heap, stack or wherever they are onto the C-world stack.
78 However, if we were to pass a heap object such as a (Haskell) @String@
79 and a garbage collection occured before we finished using it, we'd run
80 into problems since the heap object might have been moved or even
83 So, if a C call is able to cause a garbage collection or we want to
84 store a pointer to a heap object between C calls, we must be careful
85 when passing heap objects. Our solution is to keep a table of all
86 objects we've given to the C-world and to make sure that the garbage
87 collector collects these objects --- updating the table as required to
88 make sure we can still find the object.
91 snEntry *stable_ptr_table;
92 snEntry *stable_ptr_free;
94 unsigned int SPT_size;
96 /* This hash table maps Haskell objects to stable names, so that every
97 * call to lookupStableName on a given object will return the same
102 * A plain stable name entry has a zero reference count, which means
103 * the entry will dissappear when the object it points to is
104 * unreachable. For stable pointers, we need an entry that sticks
105 * around and keeps the object it points to alive, so each stable name
106 * entry has an associated reference count.
108 * A stable pointer has a weighted reference count N attached to it
109 * (actually in its upper 5 bits), which represents the weight
110 * 2^N. The stable name entry keeps a 32-bit reference count, which
111 * represents any weight between 1 and 2^32 (represented as zero).
112 * When the weight is 2^32, the stable name table owns "all" of the
113 * stable pointers to this object, and the entry can be garbage
114 * collected if the object isn't reachable.
116 * A new stable pointer is given the weight log2(W/2), where W is the
117 * weight stored in the table entry. The new weight in the table is W
120 * A stable pointer can be "split" into two stable pointers, by
121 * dividing the weight by 2 and giving each pointer half.
122 * When freeing a stable pointer, the weight of the pointer is added
123 * to the weight stored in the table entry.
126 HashTable *addrToStableHash;
128 #define INIT_SPT_SIZE 64
131 initFreeList(snEntry *table, nat n, snEntry *free)
135 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 lookupStableName(StgPtr p)
160 if (stable_ptr_free == NULL) {
161 enlargeStablePtrTable();
164 (void *)sn = lookupHashTable(addrToStableHash,(W_)p);
167 ASSERT(stable_ptr_table[sn].addr == p);
168 IF_DEBUG(stable,fprintf(stderr,"cached stable name %d at %p\n",sn,p));
171 sn = stable_ptr_free - stable_ptr_table;
172 (P_)stable_ptr_free = stable_ptr_free->addr;
173 stable_ptr_table[sn].weight = 0;
174 stable_ptr_table[sn].addr = p;
175 stable_ptr_table[sn].sn_obj = NULL;
176 /* IF_DEBUG(stable,fprintf(stderr,"new stable name %d at
179 /* add the new stable name to the hash table */
180 insertHashTable(addrToStableHash, (W_)p, (void *)sn);
187 freeStableName(snEntry *sn)
189 ASSERT(sn->sn_obj == NULL);
190 if (sn->addr != NULL) {
191 removeHashTable(addrToStableHash, (W_)sn->addr, NULL);
193 sn->addr = (P_)stable_ptr_free;
194 stable_ptr_free = sn;
198 getStablePtr(StgPtr p)
200 StgWord sn = lookupStableName(p);
201 StgWord weight, weight_2;
202 weight = stable_ptr_table[sn].weight;
204 weight = (StgWord)1 << (BITS_IN(StgWord)-1);
205 stable_ptr_table[sn].weight = weight;
206 return (StgStablePtr)(sn + ((BITS_IN(StgWord)-1) << STABLEPTR_WEIGHT_SHIFT));
208 else if (weight == 1) {
209 barf("getStablePtr: too light");
213 /* find log2(weight) */
214 for (weight_2 = 1; weight != 1; weight_2++) {
217 stable_ptr_table[sn].weight -= 2^weight_2;
218 return (StgStablePtr)(sn + (weight_2 << STABLEPTR_WEIGHT_SHIFT));
223 enlargeStablePtrTable(void)
225 nat old_SPT_size = SPT_size;
229 SPT_size = INIT_SPT_SIZE;
230 stable_ptr_table = stgMallocWords(SPT_size * sizeof(snEntry),
231 "initStablePtrTable");
233 /* we don't use index 0 in the stable name table, because that
234 * would conflict with the hash table lookup operations which
235 * return NULL if an entry isn't found in the hash table.
237 initFreeList(stable_ptr_table+1,INIT_SPT_SIZE-1,NULL);
238 addrToStableHash = allocHashTable();
241 /* 2nd and subsequent times */
244 stgReallocWords(stable_ptr_table, SPT_size * sizeof(snEntry),
245 "enlargeStablePtrTable");
247 initFreeList(stable_ptr_table + old_SPT_size, old_SPT_size, NULL);
251 /* -----------------------------------------------------------------------------
252 * Treat stable pointers as roots for the garbage collector.
254 * A stable pointer is any stable name entry with a weight > 0. We'll
255 * take the opportunity to zero the "keep" flags at the same time.
256 * -------------------------------------------------------------------------- */
259 markStablePtrTable(rtsBool full)
261 snEntry *p, *end_stable_ptr_table;
269 freeHashTable(addrToStableHash,NULL);
270 addrToStableHash = allocHashTable();
273 end_stable_ptr_table = &stable_ptr_table[SPT_size];
275 /* Mark all the stable *pointers* (not stable names).
276 * _starting_ at index 1; index 0 is unused.
278 for (p = stable_ptr_table+1; p < end_stable_ptr_table; p++) {
280 /* internal pointers or NULL are free slots
282 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
283 if (p->weight != 0) {
284 new = MarkRoot((StgClosure *)q);
285 /* Update the hash table */
287 insertHashTable(addrToStableHash, (W_)new,
288 (void *)(p - stable_ptr_table));
289 (StgClosure *)p->addr = new;
290 } else if ((P_)new != q) {
291 removeHashTable(addrToStableHash, (W_)q, NULL);
292 if (!lookupHashTable(addrToStableHash, (W_)new)) {
293 insertHashTable(addrToStableHash, (W_)new,
294 (void *)(p - stable_ptr_table));
296 (StgClosure *)p->addr = new;
298 IF_DEBUG(stable, fprintf(stderr,"Stable ptr %d still alive at %p, weight %d\n", p - stable_ptr_table, new, p->weight));
304 /* -----------------------------------------------------------------------------
305 * Garbage collect any dead entries in the stable pointer table.
309 * - a weight of zero (i.e. 2^32)
312 * Both of these conditions must be true in order to re-use the stable
313 * name table entry. We can re-use stable name table entries for live
314 * heap objects, as long as the program has no StableName objects that
315 * refer to the entry.
317 * The boolean argument 'full' indicates that a major collection is
318 * being done, so we might as well throw away the hash table and build
319 * a new one. For a minor collection, we just re-hash the elements
321 * -------------------------------------------------------------------------- */
324 gcStablePtrTable(rtsBool full)
326 snEntry *p, *end_stable_ptr_table;
333 end_stable_ptr_table = &stable_ptr_table[SPT_size];
335 /* NOTE: _starting_ at index 1; index 0 is unused. */
336 for (p = stable_ptr_table + 1; p < end_stable_ptr_table; p++) {
338 /* Update the pointer to the StableName object, if there is one */
339 if (p->sn_obj != NULL) {
340 p->sn_obj = isAlive(p->sn_obj);
344 if (q && (q < (P_)stable_ptr_table || q >= (P_)end_stable_ptr_table)) {
346 /* We're only interested in Stable Names here. The weight != 0
347 * case is handled in markStablePtrTable above.
349 if (p->weight == 0) {
351 if (p->sn_obj == NULL) {
352 /* StableName object is dead */
354 IF_DEBUG(stable, fprintf(stderr,"GC'd Stable name %d\n", p - stable_ptr_table));
357 (StgClosure *)new = isAlive((StgClosure *)q);
358 IF_DEBUG(stable, fprintf(stderr,"Stable name %d still alive at %p, weight %d\n", p - stable_ptr_table, new, p->weight));
361 /* The target has been garbage collected. Remove its
362 * entry from the hash table.
364 removeHashTable(addrToStableHash, (W_)q, NULL);
367 /* Target still alive, Re-hash this stable name
370 insertHashTable(addrToStableHash, (W_)new, (void *)(p - stable_ptr_table));
371 } else if (new != q) {
372 removeHashTable(addrToStableHash, (W_)q, NULL);
373 insertHashTable(addrToStableHash, (W_)new, (void *)(p - stable_ptr_table));
377 /* finally update the address of the target to point to its