reallyUnsafePtrEquality# on constructors with no f

2019-06-16 15:46发布

问题:

It's my understanding that the constructors of a type which have no fields are "statically allocated" and GHC shares these between all uses, and that the GC will not move these.

If that's correct then I would expect uses of reallyUnsafePtrEquality# on values like False and Nothing to be very safe (no false negatives or positives), because they can only be represented as identical pointers to the single instance of that constructor.

Is my reasoning correct? Are there any potential gotchas, or reasons to suspect that this could become unsafe in near future versions of GHC?

回答1:

I actually managed to get reallyUnsafePtrEquality to do the wrong thing.

Here's my minimal code example

{-# LANGUAGE MagicHash #-}
import GHC.Prim

-- Package it up nicely
ptrCmp :: a -> a -> Bool
ptrCmp a b = case (reallyUnsafePtrEquality# a b) of
  0# -> False
  1# -> True

main = do
  b <- readLn
  let a  = if b then Nothing else Just ()
      a' = Nothing
  print $ a == a'     -- Normal
  print $ ptrCmp a a' -- Evil

And doing something like

 $ ghc --version
   The Glorious Glasgow Haskell Compilation System, version 7.8.2
 $ ghc unsafe.hs
 $ ./unsafe
   True
   True
   False

So... yes, reallyUnsafePtrEquality is still evil.



标签: haskell ghc