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 )
46 import GHC.STRef ( STRef(..) )
47 import GHC.Ptr ( Ptr(..), FunPtr(..) )
52 -- |The type 'ForeignPtr' represents references to objects that are
53 -- maintained in a foreign language, i.e., that are not part of the
54 -- data structures usually managed by the Haskell storage manager.
55 -- The essential difference between 'ForeignPtr's and vanilla memory
56 -- references of type @Ptr a@ is that the former may be associated
57 -- with /finalizers/. A finalizer is a routine that is invoked when
58 -- the Haskell storage manager detects that - within the Haskell heap
59 -- and stack - there are no more references left that are pointing to
60 -- the 'ForeignPtr'. Typically, the finalizer will, then, invoke
61 -- routines in the foreign language that free the resources bound by
62 -- the foreign object.
64 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
65 -- type argument of 'ForeignPtr' should normally be an instance of
68 data ForeignPtr a = ForeignPtr Addr# ForeignPtrContents
69 -- we cache the Addr# in the ForeignPtr object, but attach
70 -- the finalizer to the IORef (or the MutableByteArray# in
71 -- the case of a MallocPtr). The aim of the representation
72 -- is to make withForeignPtr efficient; in fact, withForeignPtr
73 -- should be just as efficient as unpacking a Ptr, and multiple
74 -- withForeignPtrs can share an unpacked ForeignPtr. Note
75 -- that touchForeignPtr only has to touch the ForeignPtrContents
76 -- object, because that ensures that whatever the finalizer is
77 -- attached to is kept alive.
79 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
87 data ForeignPtrContents
88 = PlainForeignPtr !(IORef (Finalizers, [IO ()]))
89 | MallocPtr (MutableByteArray# RealWorld) !(IORef (Finalizers, [IO ()]))
90 | PlainPtr (MutableByteArray# RealWorld)
92 instance Eq (ForeignPtr a) where
93 p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
95 instance Ord (ForeignPtr a) where
96 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
98 instance Show (ForeignPtr a) where
99 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
102 -- |A Finalizer is represented as a pointer to a foreign function that, at
103 -- finalisation time, gets as an argument a plain pointer variant of the
104 -- foreign pointer that the finalizer is associated with.
106 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
107 type FinalizerEnvPtr env a = FunPtr (Ptr env -> Ptr a -> IO ())
109 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
111 -- ^Turns a plain memory reference into a foreign object by
112 -- associating a finalizer - given by the monadic operation - with the
113 -- reference. The storage manager will start the finalizer, in a
114 -- separate thread, some time after the last reference to the
115 -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
116 -- in fact there is no guarantee that the finalizer will eventually
119 -- Note that references from a finalizer do not necessarily prevent
120 -- another object from being finalized. If A's finalizer refers to B
121 -- (perhaps using 'touchForeignPtr', then the only guarantee is that
122 -- B's finalizer will never be started before A's. If both A and B
123 -- are unreachable, then both finalizers will start together. See
124 -- 'touchForeignPtr' for more on finalizer ordering.
126 newConcForeignPtr p finalizer
127 = do fObj <- newForeignPtr_ p
128 addForeignPtrConcFinalizer fObj finalizer
131 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
132 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
133 -- will be released automatically when the 'ForeignPtr' is discarded.
135 -- 'mallocForeignPtr' is equivalent to
137 -- > do { p <- malloc; newForeignPtr finalizerFree p }
139 -- although it may be implemented differently internally: you may not
140 -- assume that the memory returned by 'mallocForeignPtr' has been
141 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
143 -- GHC notes: 'mallocForeignPtr' has a heavily optimised
144 -- implementation in GHC. It uses pinned memory in the garbage
145 -- collected heap, so the 'ForeignPtr' does not require a finalizer to
146 -- free the memory. Use of 'mallocForeignPtr' and associated
147 -- functions is strongly recommended in preference to 'newForeignPtr'
150 mallocForeignPtr = doMalloc undefined
151 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
153 r <- newIORef (NoFinalizers, [])
155 case newPinnedByteArray# size s of { (# s', mbarr# #) ->
156 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
157 (MallocPtr mbarr# r) #)
159 where (I# size) = sizeOf a
161 -- | This function is similar to 'mallocForeignPtr', except that the
162 -- size of the memory required is given explicitly as a number of bytes.
163 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
164 mallocForeignPtrBytes (I# size) = do
165 r <- newIORef (NoFinalizers, [])
167 case newPinnedByteArray# size s of { (# s', mbarr# #) ->
168 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
169 (MallocPtr mbarr# r) #)
172 -- | Allocate some memory and return a 'ForeignPtr' to it. The memory
173 -- will be released automatically when the 'ForeignPtr' is discarded.
175 -- GHC notes: 'mallocPlainForeignPtr' has a heavily optimised
176 -- implementation in GHC. It uses pinned memory in the garbage
177 -- collected heap, as for mallocForeignPtr. Unlike mallocForeignPtr, a
178 -- ForeignPtr created with mallocPlainForeignPtr carries no finalizers.
179 -- It is not possible to add a finalizer to a ForeignPtr created with
180 -- mallocPlainForeignPtr. This is useful for ForeignPtrs that will live
181 -- only inside Haskell (such as those created for packed strings).
182 -- Attempts to add a finalizer to a ForeignPtr created this way, or to
183 -- finalize such a pointer, will throw an exception.
185 mallocPlainForeignPtr :: Storable a => IO (ForeignPtr a)
186 mallocPlainForeignPtr = doMalloc undefined
187 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
188 doMalloc a = IO $ \s ->
189 case newPinnedByteArray# size s of { (# s', mbarr# #) ->
190 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
193 where (I# size) = sizeOf a
195 -- | This function is similar to 'mallocForeignPtrBytes', except that
196 -- the internally an optimised ForeignPtr representation with no
197 -- finalizer is used. Attempts to add a finalizer will cause an
198 -- exception to be thrown.
199 mallocPlainForeignPtrBytes :: Int -> IO (ForeignPtr a)
200 mallocPlainForeignPtrBytes (I# size) = IO $ \s ->
201 case newPinnedByteArray# size s of { (# s', mbarr# #) ->
202 (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
206 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
207 -- ^This function adds a finalizer to the given foreign object. The
208 -- finalizer will run /before/ all other finalizers for the same
209 -- object which have already been registered.
210 addForeignPtrFinalizer (FunPtr fp) (ForeignPtr p c) = case c of
211 PlainForeignPtr r -> f r >> return ()
212 MallocPtr _ r -> f r >> return ()
213 _ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"
216 noMixing CFinalizers r $
218 case r of { IORef (STRef r#) ->
219 case mkWeakForeignEnv# r# () fp p 0# nullAddr# s of { (# s1, w #) ->
220 (# s1, finalizeForeign w #) }}
222 addForeignPtrFinalizerEnv ::
223 FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO ()
224 -- ^ like 'addForeignPtrFinalizerEnv' but allows the finalizer to be
225 -- passed an additional environment parameter to be passed to the
226 -- finalizer. The environment passed to the finalizer is fixed by the
227 -- second argument to 'addForeignPtrFinalizerEnv'
228 addForeignPtrFinalizerEnv (FunPtr fp) (Ptr ep) (ForeignPtr p c) = case c of
229 PlainForeignPtr r -> f r >> return ()
230 MallocPtr _ r -> f r >> return ()
231 _ -> error "GHC.ForeignPtr: attempt to add a finalizer to a plain pointer"
234 noMixing CFinalizers r $
236 case r of { IORef (STRef r#) ->
237 case mkWeakForeignEnv# r# () fp p 1# ep s of { (# s1, w #) ->
238 (# s1, finalizeForeign w #) }}
240 finalizeForeign :: Weak# () -> IO ()
241 finalizeForeign w = IO $ \s ->
242 case finalizeWeak# w s of
243 (# s1, 0#, _ #) -> (# s1, () #)
244 (# s1, _ , f #) -> f s1
246 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
247 -- ^This function adds a finalizer to the given @ForeignPtr@. The
248 -- finalizer will run /before/ all other finalizers for the same
249 -- object which have already been registered.
251 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
252 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
253 -- will run in a new thread.
255 -- NB. Be very careful with these finalizers. One common trap is that
256 -- if a finalizer references another finalized value, it does not
257 -- prevent that value from being finalized. In particular, 'Handle's
258 -- are finalized objects, so a finalizer should not refer to a 'Handle'
259 -- (including @stdout@, @stdin@ or @stderr@).
261 addForeignPtrConcFinalizer (ForeignPtr _ c) finalizer =
262 addForeignPtrConcFinalizer_ c finalizer
264 addForeignPtrConcFinalizer_ :: ForeignPtrContents -> IO () -> IO ()
265 addForeignPtrConcFinalizer_ (PlainForeignPtr r) finalizer = do
266 noFinalizers <- noMixing HaskellFinalizers r (return finalizer)
269 case r of { IORef (STRef r#) ->
270 case mkWeak# r# () (foreignPtrFinalizer r) s of { (# s1, _ #) ->
273 addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do
274 noFinalizers <- noMixing HaskellFinalizers r (return finalizer)
277 case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
278 (# s1, _ #) -> (# s1, () #)
281 addForeignPtrConcFinalizer_ _ _ =
282 error "GHC.ForeignPtr: attempt to add a finalizer to plain pointer"
285 Finalizers -> IORef (Finalizers, [IO ()]) -> IO (IO ()) -> IO Bool
286 noMixing ftype0 r mkF = do
287 (ftype, fs) <- readIORef r
288 if ftype /= NoFinalizers && ftype /= ftype0
289 then error ("GHC.ForeignPtr: attempt to mix Haskell and C finalizers " ++
290 "in the same ForeignPtr")
293 writeIORef r (ftype0, f : fs)
296 foreignPtrFinalizer :: IORef (Finalizers, [IO ()]) -> IO ()
297 foreignPtrFinalizer r = do (_, fs) <- readIORef r; sequence_ fs
299 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
300 -- ^Turns a plain memory reference into a foreign pointer that may be
301 -- associated with finalizers by using 'addForeignPtrFinalizer'.
302 newForeignPtr_ (Ptr obj) = do
303 r <- newIORef (NoFinalizers, [])
304 return (ForeignPtr obj (PlainForeignPtr r))
306 touchForeignPtr :: ForeignPtr a -> IO ()
307 -- ^This function ensures that the foreign object in
308 -- question is alive at the given place in the sequence of IO
309 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
310 -- does a 'touchForeignPtr' after it
311 -- executes the user action.
313 -- Note that this function should not be used to express dependencies
314 -- between finalizers on 'ForeignPtr's. For example, if the finalizer
315 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
316 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
317 -- for @F2@ is never started before the finalizer for @F1@. They
318 -- might be started together if for example both @F1@ and @F2@ are
319 -- otherwise unreachable, and in that case the scheduler might end up
320 -- running the finalizer for @F2@ first.
322 -- In general, it is not recommended to use finalizers on separate
323 -- objects with ordering constraints between them. To express the
324 -- ordering robustly requires explicit synchronisation using @MVar@s
325 -- between the finalizers, but even then the runtime sometimes runs
326 -- multiple finalizers sequentially in a single thread (for
327 -- performance reasons), so synchronisation between finalizers could
328 -- result in artificial deadlock. Another alternative is to use
329 -- explicit reference counting.
331 touchForeignPtr (ForeignPtr _ r) = touch r
333 touch :: ForeignPtrContents -> IO ()
334 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
336 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
337 -- ^This function extracts the pointer component of a foreign
338 -- pointer. This is a potentially dangerous operations, as if the
339 -- argument to 'unsafeForeignPtrToPtr' is the last usage
340 -- occurrence of the given foreign pointer, then its finalizer(s) will
341 -- be run, which potentially invalidates the plain pointer just
342 -- obtained. Hence, 'touchForeignPtr' must be used
343 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
344 -- has another usage occurrence.
346 -- To avoid subtle coding errors, hand written marshalling code
347 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
348 -- than combinations of 'unsafeForeignPtrToPtr' and
349 -- 'touchForeignPtr'. However, the later routines
350 -- are occasionally preferred in tool generated marshalling code.
351 unsafeForeignPtrToPtr (ForeignPtr fo _) = Ptr fo
353 castForeignPtr :: ForeignPtr a -> ForeignPtr b
354 -- ^This function casts a 'ForeignPtr'
355 -- parameterised by one type into another type.
356 castForeignPtr f = unsafeCoerce# f
358 -- | Causes the finalizers associated with a foreign pointer to be run
360 finalizeForeignPtr :: ForeignPtr a -> IO ()
361 finalizeForeignPtr (ForeignPtr _ (PlainPtr _)) = return () -- no effect
362 finalizeForeignPtr (ForeignPtr _ foreignPtr) = do
363 (ftype, finalizers) <- readIORef refFinalizers
365 writeIORef refFinalizers (ftype, [])
367 refFinalizers = case foreignPtr of
368 (PlainForeignPtr ref) -> ref
369 (MallocPtr _ ref) -> ref
371 error "finalizeForeignPtr PlainPtr"