Minor tweaks to ffi addendum

Alastair Reid reid at cs.utah.edu
Mon Jun 3 14:14:28 EDT 2002

>   - If we forced finalizers to be C functions because calling
> Haskell from the GC is inconvenient, then you have to add a
> constraint that the C function invoked from a finalizer can't call
> any functions foreign-exported from Haskell land.  That's an
> annoying constraint to have to add, because it means that C
> libraries can't be transparent w.r.t. whether they invoke Haskell
> code or not (actually the hs_init() problem that someone else
> brought up recently also has this side-effect).

What do finalizers do?

For the most part, all they do is call other finalizers then free up
the resources they directly hold.  A Haskell finalizers will usually
look like this:

  void freeFoo(Foo f)

So finalizers have to be able to invoke some Haskell runtime functions
but don't have to be able to invoke Haskell finalization code directly.

Btw the runtime functions we found it useful to export from Hugs were:

  void freeStablePtr(HsStablePtr);
  void garbageCollect();

I don't think there are any others.  I'm not sure if garbageCollect is
normally called by a finalizer but, if it were, I think we could
arrange for that limited form of reentrancy to work by exploiting the
fact that the GC invokes all finalizers at the end of the GC - so the
heap is in a nice clean state when it happens.

It's also possible that finalizers might 'do something' like close a
window (maybe showing an amusing animation while they do so).  

1) These are much rarer.

   I don't remember the last time I saw this being done.  In fact, I
   always considered it something of a mistake to rely on automatic
   finalizers to do anything with human visible consequences (though
   I seem to remember that Self or Smalltalk relied on this for
   closing windows and found it very effective).

2) C programmers are already familiar with the idea that not all code
   is reentrant and that you're especially likely to hit reentrancy
   problems in a finalizer.  So whilst it is a greater burden it is not
   a new burden unlike any they normally deal with.

3) If they're using GHC, they are free to specify that their imported
   finalizer is 'safe' (or threadsafe) and that 'safe' finalizer can
   happily call back info the runtime.

Alastair Reid        reid at cs.utah.edu        http://www.cs.utah.edu/~reid/

More information about the FFI mailing list