1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 {-# OPTIONS_HADDOCK hide #-}
3 -----------------------------------------------------------------------------
5 -- Module : GHC.ForeignPtr
6 -- Copyright : (c) The University of Glasgow, 1992-2003
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC extensions)
13 -- GHC's implementation of the 'ForeignPtr' data type.
15 -----------------------------------------------------------------------------
25 mallocPlainForeignPtr,
26 mallocForeignPtrBytes,
27 mallocPlainForeignPtrBytes,
28 addForeignPtrFinalizer,
29 addForeignPtrFinalizerEnv,
31 unsafeForeignPtrToPtr,
34 addForeignPtrConcFinalizer,
38 import Control.Monad ( sequence_ )
39 import Foreign.Storable
43 import GHC.List ( null )
47 import GHC.STRef ( STRef(..) )
48 import GHC.Ptr ( Ptr(..), FunPtr(..) )
53 -- |The type 'ForeignPtr' represents references to objects that are
54 -- maintained in a foreign language, i.e., that are not part of the
55 -- data structures usually managed by the Haskell storage manager.
56 -- The essential difference between 'ForeignPtr's and vanilla memory
57 -- references of type @Ptr a@ is that the former may be associated
58 -- with /finalizers/. A finalizer is a routine that is invoked when
59 -- the Haskell storage manager detects that - within the Haskell heap
60 -- and stack - there are no more references left that are pointing to
61 -- the 'ForeignPtr'. Typically, the finalizer will, then, invoke
62 -- routines in the foreign language that free the resources bound by
63 -- the foreign object.
65 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
66 -- type argument of 'ForeignPtr' should normally be an instance of
69 data ForeignPtr a = ForeignPtr Addr# ForeignPtrContents
70 -- we cache the Addr# in the ForeignPtr object, but attach
71 -- the finalizer to the IORef (or the MutableByteArray# in
72 -- the case of a MallocPtr). The aim of the representation
73 -- is to make withForeignPtr efficient; in fact, withForeignPtr
74 -- should be just as efficient as unpacking a Ptr, and multiple
75 -- withForeignPtrs can share an unpacked ForeignPtr. Note
76 -- that touchForeignPtr only has to touch the ForeignPtrContents
77 -- object, because that ensures that whatever the finalizer is
78 -- attached to is kept alive.
80 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
88 data ForeignPtrContents
89 = PlainForeignPtr !(IORef (Finalizers, [IO ()]))
90 | MallocPtr (MutableByteArray# RealWorld) !(IORef (Finalizers, [IO ()]))
91 | PlainPtr (MutableByteArray# RealWorld)
93 instance Eq (ForeignPtr a) where
94 p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
96 instance Ord (ForeignPtr a) where
97 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
99 instance Show (ForeignPtr a) where
100 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
103 -- |A Finalizer is represented as a pointer to a foreign function that, at
104 -- finalisation time, gets as an argument a plain pointer variant of the
105 -- foreign pointer that the finalizer is associated with.
107 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
108 type FinalizerEnvPtr env a = FunPtr (Ptr env -> Ptr a -> IO ())
110 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
112 -- ^Turns a plain memory reference into a foreign object by
113 -- associating a finalizer - given by the monadic operation - with the
114 -- reference. The storage manager will start the finalizer, in a
115 -- separate thread, some time after the last reference to the
116 -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
117 -- in fact there is no guarantee that the finalizer will eventually
120 -- Note that references from a finalizer do not necessarily prevent
121 -- another object from being finalized. If A's finalizer refers to B
122 -- (perhaps using 'touchForeignPtr', then the only guarantee is that
123 -- B's finalizer will never be started before A's. If both A and B
124 -- are unreachable, then both finalizers will start together. See
125 -- 'touchForeignPtr' for more on finalizer ordering.
127 newConcForeignPtr p finalizer
128 = do fObj <- newForeignPtr_ p
129 addForeignPtrConcFinalizer fObj finalizer
132 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
133 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
134 -- will be released automatically when the 'ForeignPtr' is discarded.
136 -- 'mallocForeignPtr' is equivalent to
138 -- > do { p <- malloc; newForeignPtr finalizerFree p }
140 -- although it may be implemented differently internally: you may not
141 -- assume that the memory returned by 'mallocForeignPtr' has been
142 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
144 -- GHC notes: 'mallocForeignPtr' has a heavily optimised
145 -- implementation in GHC. It uses pinned memory in the garbage
146 -- collected heap, so the 'ForeignPtr' does not require a finalizer to
147 -- free the memory. Use of 'mallocForeignPtr' and associated
148 -- functions is strongly recommended in preference to 'newForeignPtr'
151 mallocForeignPtr = doMalloc undefined
152 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
154 r <- newIORef (NoFinalizers, [])
156 case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
157 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
158 (MallocPtr mbarr# r) #)
160 where !(I# size) = sizeOf a
161 !(I# align) = alignment a
163 -- | This function is similar to 'mallocForeignPtr', except that the
164 -- size of the memory required is given explicitly as a number of bytes.
165 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
166 mallocForeignPtrBytes (I# size) = do
167 r <- newIORef (NoFinalizers, [])
169 case newPinnedByteArray# size s of { (# s', mbarr# #) ->
170 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
171 (MallocPtr mbarr# r) #)
174 -- | Allocate some memory and return a 'ForeignPtr' to it. The memory
175 -- will be released automatically when the 'ForeignPtr' is discarded.
177 -- GHC notes: 'mallocPlainForeignPtr' has a heavily optimised
178 -- implementation in GHC. It uses pinned memory in the garbage
179 -- collected heap, as for mallocForeignPtr. Unlike mallocForeignPtr, a
180 -- ForeignPtr created with mallocPlainForeignPtr carries no finalizers.
181 -- It is not possible to add a finalizer to a ForeignPtr created with
182 -- mallocPlainForeignPtr. This is useful for ForeignPtrs that will live
183 -- only inside Haskell (such as those created for packed strings).
184 -- Attempts to add a finalizer to a ForeignPtr created this way, or to
185 -- finalize such a pointer, will throw an exception.
187 mallocPlainForeignPtr :: Storable a => IO (ForeignPtr a)
188 mallocPlainForeignPtr = doMalloc undefined
189 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
190 doMalloc a = IO $ \s ->
191 case newAlignedPinnedByteArray# size align s of { (# s', mbarr# #) ->
192 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
195 where !(I# size) = sizeOf a
196 !(I# align) = alignment a
198 -- | This function is similar to 'mallocForeignPtrBytes', except that
199 -- the internally an optimised ForeignPtr representation with no
200 -- finalizer is used. Attempts to add a finalizer will cause an
201 -- exception to be thrown.
202 mallocPlainForeignPtrBytes :: Int -> IO (ForeignPtr a)
203 mallocPlainForeignPtrBytes (I# size) = IO $ \s ->
204 case newPinnedByteArray# size s of { (# s', mbarr# #) ->
205 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
209 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
210 -- ^This function adds a finalizer to the given foreign object. The
211 -- finalizer will run /before/ all other finalizers for the same
212 -- object which have already been registered.
213 addForeignPtrFinalizer (FunPtr fp) (ForeignPtr p c) = case c of
214 PlainForeignPtr r -> f r >> return ()
215 MallocPtr _ r -> f r >> return ()
216 _ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"
219 noMixing CFinalizers r $
221 case r of { IORef (STRef r#) ->
222 case mkWeakForeignEnv# r# () fp p 0# nullAddr# s of { (# s1, w #) ->
223 (# s1, finalizeForeign w #) }}
225 addForeignPtrFinalizerEnv ::
226 FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO ()
227 -- ^ like 'addForeignPtrFinalizerEnv' but allows the finalizer to be
228 -- passed an additional environment parameter to be passed to the
229 -- finalizer. The environment passed to the finalizer is fixed by the
230 -- second argument to 'addForeignPtrFinalizerEnv'
231 addForeignPtrFinalizerEnv (FunPtr fp) (Ptr ep) (ForeignPtr p c) = case c of
232 PlainForeignPtr r -> f r >> return ()
233 MallocPtr _ r -> f r >> return ()
234 _ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"
237 noMixing CFinalizers r $
239 case r of { IORef (STRef r#) ->
240 case mkWeakForeignEnv# r# () fp p 1# ep s of { (# s1, w #) ->
241 (# s1, finalizeForeign w #) }}
243 finalizeForeign :: Weak# () -> IO ()
244 finalizeForeign w = IO $ \s ->
245 case finalizeWeak# w s of
246 (# s1, 0#, _ #) -> (# s1, () #)
247 (# s1, _ , f #) -> f s1
249 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
250 -- ^This function adds a finalizer to the given @ForeignPtr@. The
251 -- finalizer will run /before/ all other finalizers for the same
252 -- object which have already been registered.
254 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
255 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
256 -- will run in a new thread.
258 -- NB. Be very careful with these finalizers. One common trap is that
259 -- if a finalizer references another finalized value, it does not
260 -- prevent that value from being finalized. In particular, 'Handle's
261 -- are finalized objects, so a finalizer should not refer to a 'Handle'
262 -- (including @stdout@, @stdin@ or @stderr@).
264 addForeignPtrConcFinalizer (ForeignPtr _ c) finalizer =
265 addForeignPtrConcFinalizer_ c finalizer
267 addForeignPtrConcFinalizer_ :: ForeignPtrContents -> IO () -> IO ()
268 addForeignPtrConcFinalizer_ (PlainForeignPtr r) finalizer = do
269 noFinalizers <- noMixing HaskellFinalizers r (return finalizer)
272 case r of { IORef (STRef r#) ->
273 case mkWeak# r# () (foreignPtrFinalizer r) s of { (# s1, _ #) ->
276 addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do
277 noFinalizers <- noMixing HaskellFinalizers r (return finalizer)
280 case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
281 (# s1, _ #) -> (# s1, () #)
284 addForeignPtrConcFinalizer_ _ _ =
285 error "GHC.ForeignPtr: attempt to add a finalizer to plain pointer"
288 Finalizers -> IORef (Finalizers, [IO ()]) -> IO (IO ()) -> IO Bool
289 noMixing ftype0 r mkF = do
290 (ftype, fs) <- readIORef r
291 if ftype /= NoFinalizers && ftype /= ftype0
292 then error ("GHC.ForeignPtr: attempt to mix Haskell and C finalizers " ++
293 "in the same ForeignPtr")
296 writeIORef r (ftype0, f : fs)
299 foreignPtrFinalizer :: IORef (Finalizers, [IO ()]) -> IO ()
300 foreignPtrFinalizer r = do (_, fs) <- readIORef r; sequence_ fs
302 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
303 -- ^Turns a plain memory reference into a foreign pointer that may be
304 -- associated with finalizers by using 'addForeignPtrFinalizer'.
305 newForeignPtr_ (Ptr obj) = do
306 r <- newIORef (NoFinalizers, [])
307 return (ForeignPtr obj (PlainForeignPtr r))
309 touchForeignPtr :: ForeignPtr a -> IO ()
310 -- ^This function ensures that the foreign object in
311 -- question is alive at the given place in the sequence of IO
312 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
313 -- does a 'touchForeignPtr' after it
314 -- executes the user action.
316 -- Note that this function should not be used to express dependencies
317 -- between finalizers on 'ForeignPtr's. For example, if the finalizer
318 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
319 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
320 -- for @F2@ is never started before the finalizer for @F1@. They
321 -- might be started together if for example both @F1@ and @F2@ are
322 -- otherwise unreachable, and in that case the scheduler might end up
323 -- running the finalizer for @F2@ first.
325 -- In general, it is not recommended to use finalizers on separate
326 -- objects with ordering constraints between them. To express the
327 -- ordering robustly requires explicit synchronisation using @MVar@s
328 -- between the finalizers, but even then the runtime sometimes runs
329 -- multiple finalizers sequentially in a single thread (for
330 -- performance reasons), so synchronisation between finalizers could
331 -- result in artificial deadlock. Another alternative is to use
332 -- explicit reference counting.
334 touchForeignPtr (ForeignPtr _ r) = touch r
336 touch :: ForeignPtrContents -> IO ()
337 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
339 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
340 -- ^This function extracts the pointer component of a foreign
341 -- pointer. This is a potentially dangerous operations, as if the
342 -- argument to 'unsafeForeignPtrToPtr' is the last usage
343 -- occurrence of the given foreign pointer, then its finalizer(s) will
344 -- be run, which potentially invalidates the plain pointer just
345 -- obtained. Hence, 'touchForeignPtr' must be used
346 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
347 -- has another usage occurrence.
349 -- To avoid subtle coding errors, hand written marshalling code
350 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
351 -- than combinations of 'unsafeForeignPtrToPtr' and
352 -- 'touchForeignPtr'. However, the later routines
353 -- are occasionally preferred in tool generated marshalling code.
354 unsafeForeignPtrToPtr (ForeignPtr fo _) = Ptr fo
356 castForeignPtr :: ForeignPtr a -> ForeignPtr b
357 -- ^This function casts a 'ForeignPtr'
358 -- parameterised by one type into another type.
359 castForeignPtr f = unsafeCoerce# f
361 -- | Causes the finalizers associated with a foreign pointer to be run
363 finalizeForeignPtr :: ForeignPtr a -> IO ()
364 finalizeForeignPtr (ForeignPtr _ (PlainPtr _)) = return () -- no effect
365 finalizeForeignPtr (ForeignPtr _ foreignPtr) = do
366 (ftype, finalizers) <- readIORef refFinalizers
368 writeIORef refFinalizers (ftype, [])
370 refFinalizers = case foreignPtr of
371 (PlainForeignPtr ref) -> ref
372 (MallocPtr _ ref) -> ref
374 error "finalizeForeignPtr PlainPtr"