1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
4 -- Module : GHC.ForeignPtr
5 -- Copyright : (c) The University of Glasgow, 1992-2003
6 -- License : see libraries/base/LICENSE
8 -- Maintainer : cvs-ghc@haskell.org
9 -- Stability : internal
10 -- Portability : non-portable (GHC extensions)
12 -- GHC's implementation of the 'ForeignPtr' data type.
14 -----------------------------------------------------------------------------
22 mallocForeignPtrBytes,
23 addForeignPtrFinalizer,
25 unsafeForeignPtrToPtr,
28 addForeignPtrConcFinalizer,
32 import Control.Monad ( sequence_ )
34 import Foreign.Storable
37 import GHC.List ( null )
40 import GHC.Ptr ( Ptr(..) )
44 -- |The type 'ForeignPtr' represents references to objects that are
45 -- maintained in a foreign language, i.e., that are not part of the
46 -- data structures usually managed by the Haskell storage manager.
47 -- The essential difference between 'ForeignPtr's and vanilla memory
48 -- references of type @Ptr a@ is that the former may be associated
49 -- with /finalizers/. A finalizer is a routine that is invoked when
50 -- the Haskell storage manager detects that - within the Haskell heap
51 -- and stack - there are no more references left that are pointing to
52 -- the 'ForeignPtr'. Typically, the finalizer will, then, invoke
53 -- routines in the foreign language that free the resources bound by
54 -- the foreign object.
56 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
57 -- type argument of 'ForeignPtr' should normally be an instance of
61 = ForeignPtr ForeignObj# !(IORef [IO ()])
62 | MallocPtr (MutableByteArray# RealWorld) !(IORef [IO ()])
64 instance Eq (ForeignPtr a) where
65 p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
67 instance Ord (ForeignPtr a) where
68 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
70 instance Show (ForeignPtr a) where
71 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
74 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
76 -- |A Finalizer is represented as a pointer to a foreign function that, at
77 -- finalisation time, gets as an argument a plain pointer variant of the
78 -- foreign pointer that the finalizer is associated with.
80 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
82 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
84 -- ^Turns a plain memory reference into a foreign object by
85 -- associating a finalizer - given by the monadic operation - with the
86 -- reference. The storage manager will start the finalizer, in a
87 -- separate thread, some time after the last reference to the
88 -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
89 -- in fact there is no guarantee that the finalizer will eventually
92 newConcForeignPtr p finalizer
93 = do fObj <- newForeignPtr_ p
94 addForeignPtrConcFinalizer fObj finalizer
97 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
98 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
99 -- will be released automatically when the 'ForeignPtr' is discarded.
101 -- 'mallocForeignPtr' is equivalent to
103 -- > do { p <- malloc; newForeignPtr finalizerFree p }
105 -- although it may be implemented differently internally: you may not
106 -- assume that the memory returned by 'mallocForeignPtr' has been
107 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
108 mallocForeignPtr = doMalloc undefined
109 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
113 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
114 (# s, MallocPtr mbarr# r #)
116 where (I# size) = sizeOf a
118 -- | This function is similar to 'mallocForeignPtr', except that the
119 -- size of the memory required is given explicitly as a number of bytes.
120 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
121 mallocForeignPtrBytes (I# size) = do
124 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
125 (# s, MallocPtr mbarr# r #)
128 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
129 -- ^This function adds a finalizer to the given foreign object. The
130 -- finalizer will run /before/ all other finalizers for the same
131 -- object which have already been registered.
132 addForeignPtrFinalizer finalizer fptr =
133 addForeignPtrConcFinalizer fptr
134 (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
136 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
137 -- ^This function adds a finalizer to the given @ForeignPtr@. The
138 -- finalizer will run /before/ all other finalizers for the same
139 -- object which have already been registered.
141 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
142 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
143 -- will run in a new thread.
145 -- NB. Be very careful with these finalizers. One common trap is that
146 -- if a finalizer references another finalized value, it does not
147 -- prevent that value from being finalized. In particular, 'Handle's
148 -- are finalized objects, so a finalizer should not refer to a 'Handle'
149 -- (including @stdout@, @stdin@ or @stderr@).
151 addForeignPtrConcFinalizer f@(ForeignPtr fo r) finalizer = do
153 writeIORef r (finalizer : fs)
156 let p = unsafeForeignPtrToPtr f in
157 case mkWeak# fo () (foreignPtrFinalizer r p) s of
158 (# s1, w #) -> (# s1, () #)
160 addForeignPtrConcFinalizer f@(MallocPtr fo r) finalizer = do
162 writeIORef r (finalizer : fs)
165 let p = unsafeForeignPtrToPtr f in
166 case mkWeak# fo () (do foreignPtrFinalizer r p
167 touchPinnedByteArray# fo) s of
168 (# s1, w #) -> (# s1, () #)
171 foreign import ccall "dynamic"
172 mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
174 foreignPtrFinalizer :: IORef [IO ()] -> Ptr a -> IO ()
175 foreignPtrFinalizer r p = do
179 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
180 -- ^Turns a plain memory reference into a foreign pointer that may be
181 -- associated with finalizers by using 'addForeignPtrFinalizer'.
182 newForeignPtr_ (Ptr obj) = do
185 case mkForeignObj# obj s# of
186 (# s1#, fo# #) -> (# s1#, ForeignPtr fo# r #)
188 touchPinnedByteArray# :: MutableByteArray# RealWorld -> IO ()
189 touchPinnedByteArray# ba# = IO $ \s -> case touch# ba# s of s -> (# s, () #)
191 touchForeignPtr :: ForeignPtr a -> IO ()
192 -- ^This function ensures that the foreign object in
193 -- question is alive at the given place in the sequence of IO
194 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
195 -- does a 'touchForeignPtr' after it
196 -- executes the user action.
198 -- Note that this function should not be used to express liveness
199 -- dependencies between 'ForeignPtr's. For example, if the finalizer
200 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
201 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
202 -- for @F2@ is never started before the finalizer for @F1@. They
203 -- might be started together if for example both @F1@ and @F2@ are
204 -- otherwise unreachable, and in that case the scheduler might end up
205 -- running the finalizer for @F2@ first.
207 -- In general, it is not recommended to use finalizers on separate
208 -- objects with ordering constraints between them. To express the
209 -- ordering robustly requires explicit synchronisation using @MVar@s
210 -- between the finalizers, but even then the runtime sometimes runs
211 -- multiple finalizers sequentially in a single thread (for
212 -- performance reasons), so synchronisation between finalizers could
213 -- result in artificial deadlock.
215 touchForeignPtr (ForeignPtr fo r)
216 = IO $ \s -> case touch# fo s of s -> (# s, () #)
217 touchForeignPtr (MallocPtr fo r)
218 = touchPinnedByteArray# fo
220 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
221 -- ^This function extracts the pointer component of a foreign
222 -- pointer. This is a potentially dangerous operations, as if the
223 -- argument to 'unsafeForeignPtrToPtr' is the last usage
224 -- occurrence of the given foreign pointer, then its finalizer(s) will
225 -- be run, which potentially invalidates the plain pointer just
226 -- obtained. Hence, 'touchForeignPtr' must be used
227 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
228 -- has another usage occurrence.
230 -- To avoid subtle coding errors, hand written marshalling code
231 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
232 -- than combinations of 'unsafeForeignPtrToPtr' and
233 -- 'touchForeignPtr'. However, the later routines
234 -- are occasionally preferred in tool generated marshalling code.
235 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr (foreignObjToAddr# fo)
236 unsafeForeignPtrToPtr (MallocPtr fo r) = Ptr (byteArrayContents# (unsafeCoerce# fo))
238 castForeignPtr :: ForeignPtr a -> ForeignPtr b
239 -- ^This function casts a 'ForeignPtr'
240 -- parameterised by one type into another type.
241 castForeignPtr f = unsafeCoerce# f
243 -- | Causes a the finalizers associated with a foreign pointer to be run
245 finalizeForeignPtr :: ForeignPtr a -> IO ()
246 finalizeForeignPtr foreignPtr = do
247 finalizers <- readIORef refFinalizers
249 writeIORef refFinalizers []
251 refFinalizers = case foreignPtr of
252 (ForeignPtr _ ref) -> ref
253 (MallocPtr _ ref) -> ref