Allocation & Marshalling Question (again)

Simon Marlow simonmar at microsoft.com
Thu May 29 09:47:03 EDT 2003


 
> On Wednesday 28 May 2003 10:32, Simon Marlow wrote:
> 
> > Even in GHC where we use garbage collected memory instead 
> of malloc, we
> > still make use of the IO monad to control the lifetime of 
> the allocated
> > memory.
> 
> Thanks for that info. I'm not to clear about what the 
> intended implementation
> is (if there is one) from reading the FFI spec. It seems to 
> me that if the
> IO monad is used to control the lifetime you could use stack 
> allocation quite
> easily. (Dunno if that would be any more efficient for the 
> ghc rts though.)
> Using the garbage collected heap but not actually using normal garbage
> collection mechanisms seems a bit strange to me :-)

I actually thought long and hard about how to implement allocaBytes
efficiently in GHC, before eventually coming up with the current scheme.
The problem with using stack allocation is that stacks move around in
GHC, and you need stable storage for allocaBytes because it passes the
pointer to a foreign call.  You could use a separate, stable, stack, but
then you also need to move the stack pointer back down at the end of the
alloca, and that needs to be done in an exeception-safe way, which is
also expensive.

The current idea is to use a pinned, but garbage-collectable allocation.
The pinned object is "touched" at the end of the alloca to ensure that
it cannot be garbage collected until then.  We don't need an exception
handler: if an exception is raised in the middle of the alloca, then the
pointer to the object will be simply dropped and the memory garbage
collected.

Cheers,
	Simon



More information about the FFI mailing list