reallyUnsafePtrEquality# on constructors with no fields

社会主义新天地 提交于 2019-12-08 15:56:21

问题


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.



来源:https://stackoverflow.com/questions/24599067/reallyunsafeptrequality-on-constructors-with-no-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!