Finalizers strike back

Malcolm Wallace Malcolm.Wallace at
Fri Oct 11 12:01:23 EDT 2002

George Russell <ger at> writes:

> If instant finalizers are desired, there is of course no
> reason we should not also have an addUnsafeForeignFinalizer function
> with the existing behaviour.

I think I would be in favour of permitting both Haskell finalisers and
foreign language finalisers.  At the moment, it is rather convenient
in the internals of nhc98's runtime system to have finalisers (e.g. for
Handles) implemented purely in C, for efficiency if nothing else.

On the other hand I can entirely see why Haskell finalisers are
desirable.  They are useful for debugging purposes, and they can help
avoid space leaks.

> What is the situation with NHC?

I'm sure the details of nhc98's implementation are largely irrelevant
since we need to settle on a correct design regardless of the current
state of play.

But in case you are interested, at the moment, ForeignPtr uses a C-only
finaliser :: FunPtr (Ptr a -> IO ())  whilst ForeignObj (deprecated)
uses a Haskell finaliser :: IO ().  Haskell finalisers are re-entry
safe (i.e. you can go into foreign-land and back into Haskell),
but C finalisers are currently not (you cannot safely call Haskell
from a C finaliser, although it would only take a little tweaking to
fix this).  It is safe for a C finaliser to mess with shared state
in the C world.  It is not safe for a Haskell finaliser to mess with
shared state in Haskell, because there are no locking mechanisms.
(And if you try to use MVars, you'll get a compile time error because
we don't provide them.)  However it is safe for the Haskell finaliser
to call C routines that manipulate shared state in the C world.


More information about the FFI mailing list