Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reallyUnsafePtrEquality# on constructors with no fields

Tags:

haskell

ghc

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?

like image 818
jberryman Avatar asked Jul 06 '14 18:07

jberryman


1 Answers

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.

like image 124
Daniel Gratzer Avatar answered Sep 20 '22 03:09

Daniel Gratzer