1 /* -----------------------------------------------------------------------------
2 * $Id: Weak.c,v 1.31 2003/10/24 09:00:59 simonmar Exp $
4 * (c) The GHC Team, 1998-1999
6 * Weak pointers / finalizers
8 * ---------------------------------------------------------------------------*/
10 #include "PosixSource.h"
11 #define COMPILING_RTS_MAIN
21 StgWeak *weak_ptr_list;
24 * finalizeWeakPointersNow() is called just before the system is shut
25 * down. It runs the finalizer for each weak pointer still in the
28 * Careful here - rts_evalIO might cause a garbage collection, which
29 * might change weak_ptr_list. Must re-load weak_ptr_list each time
34 finalizeWeakPointersNow(void)
39 while ((w = weak_ptr_list)) {
40 weak_ptr_list = w->link;
41 if (w->header.info != &stg_DEAD_WEAK_info) {
42 w->header.info = &stg_DEAD_WEAK_info;
43 IF_DEBUG(weak,fprintf(stderr,"Finalising weak pointer at %p -> %p\n", w, w->key));
44 if (w->finalizer != &stg_NO_FINALIZER_closure) {
45 rts_evalLazyIO(w->finalizer,NULL);
55 * scheduleFinalizers() is called on the list of weak pointers found
56 * to be dead after a garbage collection. It overwrites each object
57 * with DEAD_WEAK, and creates a new thread to run the pending finalizers.
59 * This function is called just after GC. The weak pointers on the
60 * argument list are those whose keys were found to be not reachable,
61 * however the value and finalizer fields have by now been marked live.
62 * The weak pointer object itself may not be alive - i.e. we may be
63 * looking at either an object in from-space or one in to-space. It
64 * doesn't really matter either way.
66 * Pre-condition: sched_mutex _not_ held.
70 scheduleFinalizers(StgWeak *list)
77 // count number of finalizers, and kill all the weak pointers first...
79 for (w = list; w; w = w->link) {
81 // Better not be a DEAD_WEAK at this stage; the garbage
82 // collector removes DEAD_WEAKs from the weak pointer list.
83 ASSERT(w->header.info != &stg_DEAD_WEAK_info);
85 if (w->finalizer != &stg_NO_FINALIZER_closure) {
90 // A weak pointer is inherently used, so we do not need to call
93 // Furthermore, when PROFILING is turned on, dead weak
94 // pointers are exactly as large as weak pointers, so there is
95 // no need to fill the slop, either. See stg_DEAD_WEAK_info
96 // in StgMiscClosures.hc.
98 SET_HDR(w, &stg_DEAD_WEAK_info, w->header.prof.ccs);
101 // No finalizers to run?
104 IF_DEBUG(weak,fprintf(stderr,"weak: batching %d finalizers\n", n));
106 arr = (StgMutArrPtrs *)allocate(sizeofW(StgMutArrPtrs) + n);
107 TICK_ALLOC_PRIM(sizeofW(StgMutArrPtrs), n, 0);
108 SET_HDR(arr, &stg_MUT_ARR_PTRS_FROZEN_info, CCS_SYSTEM);
109 arr->mut_link = NULL;
113 for (w = list; w; w = w->link) {
114 if (w->finalizer != &stg_NO_FINALIZER_closure) {
115 arr->payload[n] = w->finalizer;
120 t = createIOThread(RtsFlags.GcFlags.initialStkSize,
123 (StgClosure *)runFinalizerBatch_closure,