1 {-# OPTIONS_GHC -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 -----------------------------------------------------------------------------
23 mallocPlainForeignPtr,
24 mallocForeignPtrBytes,
25 mallocPlainForeignPtrBytes,
26 addForeignPtrFinalizer,
28 unsafeForeignPtrToPtr,
31 addForeignPtrConcFinalizer,
35 import Control.Monad ( sequence_ )
36 import Foreign.Storable
39 import GHC.List ( null )
42 import GHC.STRef ( STRef(..) )
43 import GHC.Ptr ( Ptr(..), FunPtr )
46 -- |The type 'ForeignPtr' represents references to objects that are
47 -- maintained in a foreign language, i.e., that are not part of the
48 -- data structures usually managed by the Haskell storage manager.
49 -- The essential difference between 'ForeignPtr's and vanilla memory
50 -- references of type @Ptr a@ is that the former may be associated
51 -- with /finalizers/. A finalizer is a routine that is invoked when
52 -- the Haskell storage manager detects that - within the Haskell heap
53 -- and stack - there are no more references left that are pointing to
54 -- the 'ForeignPtr'. Typically, the finalizer will, then, invoke
55 -- routines in the foreign language that free the resources bound by
56 -- the foreign object.
58 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
59 -- type argument of 'ForeignPtr' should normally be an instance of
62 data ForeignPtr a = ForeignPtr Addr# ForeignPtrContents
63 -- we cache the Addr# in the ForeignPtr object, but attach
64 -- the finalizer to the IORef (or the MutableByteArray# in
65 -- the case of a MallocPtr). The aim of the representation
66 -- is to make withForeignPtr efficient; in fact, withForeignPtr
67 -- should be just as efficient as unpacking a Ptr, and multiple
68 -- withForeignPtrs can share an unpacked ForeignPtr. Note
69 -- that touchForeignPtr only has to touch the ForeignPtrContents
70 -- object, because that ensures that whatever the finalizer is
71 -- attached to is kept alive.
73 data ForeignPtrContents
74 = PlainForeignPtr !(IORef [IO ()])
75 | MallocPtr (MutableByteArray# RealWorld) !(IORef [IO ()])
76 | PlainPtr (MutableByteArray# RealWorld)
78 instance Eq (ForeignPtr a) where
79 p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
81 instance Ord (ForeignPtr a) where
82 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
84 instance Show (ForeignPtr a) where
85 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
88 -- |A Finalizer is represented as a pointer to a foreign function that, at
89 -- finalisation time, gets as an argument a plain pointer variant of the
90 -- foreign pointer that the finalizer is associated with.
92 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
94 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
96 -- ^Turns a plain memory reference into a foreign object by
97 -- associating a finalizer - given by the monadic operation - with the
98 -- reference. The storage manager will start the finalizer, in a
99 -- separate thread, some time after the last reference to the
100 -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
101 -- in fact there is no guarantee that the finalizer will eventually
104 -- Note that references from a finalizer do not necessarily prevent
105 -- another object from being finalized. If A's finalizer refers to B
106 -- (perhaps using 'touchForeignPtr', then the only guarantee is that
107 -- B's finalizer will never be started before A's. If both A and B
108 -- are unreachable, then both finalizers will start together. See
109 -- 'touchForeignPtr' for more on finalizer ordering.
111 newConcForeignPtr p finalizer
112 = do fObj <- newForeignPtr_ p
113 addForeignPtrConcFinalizer fObj finalizer
116 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
117 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
118 -- will be released automatically when the 'ForeignPtr' is discarded.
120 -- 'mallocForeignPtr' is equivalent to
122 -- > do { p <- malloc; newForeignPtr finalizerFree p }
124 -- although it may be implemented differently internally: you may not
125 -- assume that the memory returned by 'mallocForeignPtr' has been
126 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
128 -- GHC notes: 'mallocForeignPtr' has a heavily optimised
129 -- implementation in GHC. It uses pinned memory in the garbage
130 -- collected heap, so the 'ForeignPtr' does not require a finalizer to
131 -- free the memory. Use of 'mallocForeignPtr' and associated
132 -- functions is strongly recommended in preference to 'newForeignPtr'
135 mallocForeignPtr = doMalloc undefined
136 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
140 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
141 (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
142 (MallocPtr mbarr# r) #)
144 where (I# size) = sizeOf a
146 -- | This function is similar to 'mallocForeignPtr', except that the
147 -- size of the memory required is given explicitly as a number of bytes.
148 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
149 mallocForeignPtrBytes (I# size) = do
152 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
153 (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
154 (MallocPtr mbarr# r) #)
157 -- | Allocate some memory and return a 'ForeignPtr' to it. The memory
158 -- will be released automatically when the 'ForeignPtr' is discarded.
160 -- GHC notes: 'mallocPlainForeignPtr' has a heavily optimised
161 -- implementation in GHC. It uses pinned memory in the garbage
162 -- collected heap, as for mallocForeignPtr. Unlike mallocForeignPtr, a
163 -- ForeignPtr created with mallocPlainForeignPtr carries no finalizers.
164 -- It is not possible to add a finalizer to a ForeignPtr created with
165 -- mallocPlainForeignPtr. This is useful for ForeignPtrs that will live
166 -- only inside Haskell (such as those created for packed strings).
167 -- Attempts to add a finalizer to a ForeignPtr created this way, or to
168 -- finalize such a pointer, will throw an exception.
170 mallocPlainForeignPtr :: Storable a => IO (ForeignPtr a)
171 mallocPlainForeignPtr = doMalloc undefined
172 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
173 doMalloc a = IO $ \s ->
174 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
175 (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
178 where (I# size) = sizeOf a
180 -- | This function is similar to 'mallocForeignPtrBytes', except that
181 -- the internally an optimised ForeignPtr representation with no
182 -- finalizer is used. Attempts to add a finalizer will cause an
183 -- exception to be thrown.
184 mallocPlainForeignPtrBytes :: Int -> IO (ForeignPtr a)
185 mallocPlainForeignPtrBytes (I# size) = IO $ \s ->
186 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
187 (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
191 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
192 -- ^This function adds a finalizer to the given foreign object. The
193 -- finalizer will run /before/ all other finalizers for the same
194 -- object which have already been registered.
195 addForeignPtrFinalizer finalizer fptr =
196 addForeignPtrConcFinalizer fptr
197 (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
199 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
200 -- ^This function adds a finalizer to the given @ForeignPtr@. The
201 -- finalizer will run /before/ all other finalizers for the same
202 -- object which have already been registered.
204 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
205 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
206 -- will run in a new thread.
208 -- NB. Be very careful with these finalizers. One common trap is that
209 -- if a finalizer references another finalized value, it does not
210 -- prevent that value from being finalized. In particular, 'Handle's
211 -- are finalized objects, so a finalizer should not refer to a 'Handle'
212 -- (including @stdout@, @stdin@ or @stderr@).
214 addForeignPtrConcFinalizer (ForeignPtr a c) finalizer =
215 addForeignPtrConcFinalizer_ c finalizer
217 addForeignPtrConcFinalizer_ f@(PlainForeignPtr r) finalizer = do
219 writeIORef r (finalizer : fs)
222 case r of { IORef (STRef r#) ->
223 case mkWeak# r# () (foreignPtrFinalizer r) s of { (# s1, w #) ->
226 addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do
228 writeIORef r (finalizer : fs)
231 case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
232 (# s1, w #) -> (# s1, () #)
235 addForeignPtrConcFinalizer_ _ _ =
236 error "GHC.ForeignPtr: attempt to add a finalizer to plain pointer"
238 foreign import ccall "dynamic"
239 mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
241 foreignPtrFinalizer :: IORef [IO ()] -> IO ()
242 foreignPtrFinalizer r = do fs <- readIORef r; sequence_ fs
244 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
245 -- ^Turns a plain memory reference into a foreign pointer that may be
246 -- associated with finalizers by using 'addForeignPtrFinalizer'.
247 newForeignPtr_ (Ptr obj) = do
249 return (ForeignPtr obj (PlainForeignPtr r))
251 touchForeignPtr :: ForeignPtr a -> IO ()
252 -- ^This function ensures that the foreign object in
253 -- question is alive at the given place in the sequence of IO
254 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
255 -- does a 'touchForeignPtr' after it
256 -- executes the user action.
258 -- Note that this function should not be used to express dependencies
259 -- between finalizers on 'ForeignPtr's. For example, if the finalizer
260 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
261 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
262 -- for @F2@ is never started before the finalizer for @F1@. They
263 -- might be started together if for example both @F1@ and @F2@ are
264 -- otherwise unreachable, and in that case the scheduler might end up
265 -- running the finalizer for @F2@ first.
267 -- In general, it is not recommended to use finalizers on separate
268 -- objects with ordering constraints between them. To express the
269 -- ordering robustly requires explicit synchronisation using @MVar@s
270 -- between the finalizers, but even then the runtime sometimes runs
271 -- multiple finalizers sequentially in a single thread (for
272 -- performance reasons), so synchronisation between finalizers could
273 -- result in artificial deadlock. Another alternative is to use
274 -- explicit reference counting.
276 touchForeignPtr (ForeignPtr fo r) = touch r
278 touch r = IO $ \s -> case touch# r s of s -> (# s, () #)
280 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
281 -- ^This function extracts the pointer component of a foreign
282 -- pointer. This is a potentially dangerous operations, as if the
283 -- argument to 'unsafeForeignPtrToPtr' is the last usage
284 -- occurrence of the given foreign pointer, then its finalizer(s) will
285 -- be run, which potentially invalidates the plain pointer just
286 -- obtained. Hence, 'touchForeignPtr' must be used
287 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
288 -- has another usage occurrence.
290 -- To avoid subtle coding errors, hand written marshalling code
291 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
292 -- than combinations of 'unsafeForeignPtrToPtr' and
293 -- 'touchForeignPtr'. However, the later routines
294 -- are occasionally preferred in tool generated marshalling code.
295 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr fo
297 castForeignPtr :: ForeignPtr a -> ForeignPtr b
298 -- ^This function casts a 'ForeignPtr'
299 -- parameterised by one type into another type.
300 castForeignPtr f = unsafeCoerce# f
302 -- | Causes the finalizers associated with a foreign pointer to be run
304 finalizeForeignPtr :: ForeignPtr a -> IO ()
305 finalizeForeignPtr (ForeignPtr _ (PlainPtr _)) = return () -- no effect
306 finalizeForeignPtr (ForeignPtr _ foreignPtr) = do
307 finalizers <- readIORef refFinalizers
309 writeIORef refFinalizers []
311 refFinalizers = case foreignPtr of
312 (PlainForeignPtr ref) -> ref
313 (MallocPtr _ ref) -> ref