1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-1999
5 * Weak pointers / finalizers
7 * ---------------------------------------------------------------------------*/
9 #include "PosixSource.h"
20 // ForeignPtrs with C finalizers rely on weak pointers inside weak_ptr_list
21 // to always be in the same order.
23 StgWeak *weak_ptr_list;
26 runCFinalizer(StgVoid *fn, StgVoid *ptr, StgVoid *env, StgWord flag)
29 ((void (*)(void *, void *))fn)(env, ptr);
31 ((void (*)(void *))fn)(ptr);
35 runAllCFinalizers(StgWeak *list)
39 for (w = list; w; w = w->link) {
42 farr = (StgArrWords *)UNTAG_CLOSURE(w->cfinalizer);
44 if ((StgClosure *)farr != &stg_NO_FINALIZER_closure)
45 runCFinalizer((StgVoid *)farr->payload[0],
46 (StgVoid *)farr->payload[1],
47 (StgVoid *)farr->payload[2],
53 * scheduleFinalizers() is called on the list of weak pointers found
54 * to be dead after a garbage collection. It overwrites each object
55 * with DEAD_WEAK, and creates a new thread to run the pending finalizers.
57 * This function is called just after GC. The weak pointers on the
58 * argument list are those whose keys were found to be not reachable,
59 * however the value and finalizer fields have by now been marked live.
60 * The weak pointer object itself may not be alive - i.e. we may be
61 * looking at either an object in from-space or one in to-space. It
62 * doesn't really matter either way.
64 * Pre-condition: sched_mutex _not_ held.
68 scheduleFinalizers(Capability *cap, StgWeak *list)
75 // count number of finalizers, and kill all the weak pointers first...
77 for (w = list; w; w = w->link) {
80 // Better not be a DEAD_WEAK at this stage; the garbage
81 // collector removes DEAD_WEAKs from the weak pointer list.
82 ASSERT(w->header.info != &stg_DEAD_WEAK_info);
84 if (w->finalizer != &stg_NO_FINALIZER_closure) {
88 farr = (StgArrWords *)UNTAG_CLOSURE(w->cfinalizer);
90 if ((StgClosure *)farr != &stg_NO_FINALIZER_closure)
91 runCFinalizer((StgVoid *)farr->payload[0],
92 (StgVoid *)farr->payload[1],
93 (StgVoid *)farr->payload[2],
97 // A weak pointer is inherently used, so we do not need to call
100 // Furthermore, when PROFILING is turned on, dead weak
101 // pointers are exactly as large as weak pointers, so there is
102 // no need to fill the slop, either. See stg_DEAD_WEAK_info
103 // in StgMiscClosures.hc.
105 SET_HDR(w, &stg_DEAD_WEAK_info, w->header.prof.ccs);
108 // No finalizers to run?
111 debugTrace(DEBUG_weak, "weak: batching %d finalizers", n);
113 arr = (StgMutArrPtrs *)allocateLocal(cap, sizeofW(StgMutArrPtrs) + n);
114 TICK_ALLOC_PRIM(sizeofW(StgMutArrPtrs), n, 0);
115 SET_HDR(arr, &stg_MUT_ARR_PTRS_FROZEN_info, CCS_SYSTEM);
119 for (w = list; w; w = w->link) {
120 if (w->finalizer != &stg_NO_FINALIZER_closure) {
121 arr->payload[n] = w->finalizer;
126 t = createIOThread(cap,
127 RtsFlags.GcFlags.initialStkSize,
130 (StgClosure *)runFinalizerBatch_closure,
134 scheduleThread(cap,t);