Skip to content

Adding weak pointers to non-mutable unboxed values segfaults

Consider the following program:

{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}

module Main where

import Foreign
import GHC.Base
import GHC.IORef
import GHC.Ptr
import GHC.STRef
import System.Mem

main = do
    p@(Ptr p#) <- mallocBytes 10
    r@(IORef (STRef r#)) <- newIORef True
    IO $ \s -> case mkWeakNoFinalizer# r# () s of (# s1, w #) -> (# s1, () #)
    performGC

This program works fine. But if I mkWeakNoFinalizer# to #p instead of #r then it segfaults. That is, I can attach a weak pointer to a MutVar#, as well as to a MVar#, but not any other unboxed type, including pointer addresses.

The documentation says "Finalizers can be used reliably for types that are created explicitly and have identity, such as IORef and MVar". But a) I don't know that "types that have identity" is defined anywhere, b) this doesn't say that weak pointers cannot be used for anything else.

Should I be able to create weak pointers to any unboxed value? If not, I guess this is mostly a documentation bug.

Trac metadata
Trac field Value
Version 8.0.1
Type Bug
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component Compiler
Test case
Differential revisions
BlockedBy
Related
Blocking
CC facundominguez
Operating system
Architecture
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information