1 /* -----------------------------------------------------------------------------
2 * $Id: Weak.c,v 1.23 2002/04/26 22:31:31 sof Exp $
4 * (c) The GHC Team, 1998-1999
6 * Weak pointers / finalizers
8 * ---------------------------------------------------------------------------*/
10 #include "PosixSource.h"
11 #define COMPILING_RTS_MAIN
20 StgWeak *weak_ptr_list;
23 * finalizeWeakPointersNow() is called just before the system is shut
24 * down. It runs the finalizer for each weak pointer still in the
27 * Careful here - rts_evalIO might cause a garbage collection, which
28 * might change weak_ptr_list. Must re-load weak_ptr_list each time
33 finalizeWeakPointersNow(void)
37 while ((w = weak_ptr_list)) {
38 weak_ptr_list = w->link;
39 if (w->header.info != &stg_DEAD_WEAK_info) {
40 w->header.info = &stg_DEAD_WEAK_info;
41 IF_DEBUG(weak,fprintf(stderr,"Finalising weak pointer at %p -> %p\n", w, w->key));
42 if (w->finalizer != &stg_NO_FINALIZER_closure) {
43 rts_mainEvalIO(w->finalizer,NULL);
50 * scheduleFinalizers() is called on the list of weak pointers found
51 * to be dead after a garbage collection. It overwrites each object
52 * with DEAD_WEAK, and creates a new thread to run the pending finalizers.
54 * This function is called just after GC. The weak pointers on the
55 * argument list are those whose keys were found to be not reachable,
56 * however the value and finalizer fields have by now been marked live.
57 * The weak pointer object itself may not be alive - i.e. we may be
58 * looking at either an object in from-space or one in to-space. It
59 * doesn't really matter either way.
61 * Pre-condition: sched_mutex _not_ held.
65 scheduleFinalizers(StgWeak *list)
72 /* count number of finalizers first... */
73 for (n = 0, w = list; w; w = w->link) {
74 if (w->header.info != &stg_DEAD_WEAK_info &&
75 w->finalizer != &stg_NO_FINALIZER_closure)
81 IF_DEBUG(weak,fprintf(stderr,"weak: batching %d finalizers\n", n));
83 arr = (StgMutArrPtrs *)allocate(sizeofW(StgMutArrPtrs) + n);
84 SET_HDR(arr, &stg_MUT_ARR_PTRS_FROZEN_info, CCS_SYSTEM);
87 for (n = 0, w = list; w; w = w->link) {
88 if (w->header.info != &stg_DEAD_WEAK_info &&
89 w->finalizer != &stg_NO_FINALIZER_closure) {
90 arr->payload[n] = w->finalizer;
95 // A weak pointer is inherently used, so we do not need to call
98 // Furthermore, when PROFILING is turned on, dead weak
99 // pointers are exactly as large as weak pointers, so there is
100 // no need to fill the slop, either. See stg_DEAD_WEAK_info
101 // in StgMiscClosures.hc.
103 SET_HDR(w, &stg_DEAD_WEAK_info, w->header.prof.ccs);
106 t = createIOThread(RtsFlags.GcFlags.initialStkSize,
109 (StgClosure *)runFinalizerBatch_closure,