foundation icon indicating copy to clipboard operation
foundation copied to clipboard

withFinalPtr on FinalPtr is not safe

Open ndmitchell opened this issue 9 years ago • 4 comments

Specifically, you can't do https://github.com/haskell-foundation/foundation/blob/b56a79c7aeef7c57969b7fb2e3027dfbfa7841a0/Foundation/Primitive/FinalPtr.hs#L74. as GHC is at it's liberty to compile that function to:

withFinalPtr (FinalPtr (Ptr addr)) f = do
    r <- f (Ptr addr)
    primTouch (Ptr addr)
    return r

Now observe you are touching a different Ptr to the one you attached the finaliser too, and everything goes bad. I know this is a problem having just tracked down a segfault which only reproduced under -fhpc (where compiler optimisations are reduced) which used code very closely modelled on your code.

ndmitchell avatar Oct 23 '16 21:10 ndmitchell

That's an unfortunate "optimisation", any idea what's the reason ghc allow this to happen and how it's circumvented ?

Also, is there a way to reproduce with the test suite or a program using foundation code ?

vincenthz avatar Oct 25 '16 10:10 vincenthz

I have no reproducible test suite you can see, and nothing using foundation code from foundation - I had copied something very similar into my $WORK code and it blew up, taking quite a long time to track down. I think the general rule is that you shouldn't attach a finaliser to anything without identity, and pointers don't have that, but IORef's do.

ndmitchell avatar Oct 25 '16 10:10 ndmitchell

What's "anything without identity" ?

vincenthz avatar Oct 25 '16 10:10 vincenthz

The internals of an IORef cannot be arbitrarily cloned - they refer to a given IORef. If you duplicate that IORef the semantics have changed. In contrast something like Just 1 is indistinguishable from any other Just 1 value.

ndmitchell avatar Oct 25 '16 10:10 ndmitchell