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 mallocForeignPtrBytes,
24 addForeignPtrFinalizer,
26 unsafeForeignPtrToPtr,
29 addForeignPtrConcFinalizer,
33 import Control.Monad ( sequence_ )
35 import Foreign.Storable
39 import GHC.STRef ( STRef(..) )
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
60 data ForeignPtr a = ForeignPtr Addr# ForeignPtrContents
61 -- we cache the Addr# in the ForeignPtr object, but attach
62 -- the finalizer to the IORef (or the MutableByteArray# in
63 -- the case of a MallocPtr). The aim of the representation
64 -- is to make withForeignPtr efficient; in fact, withForeignPtr
65 -- should be just as efficient as unpacking a Ptr, and multiple
66 -- withForeignPtrs can share an unpacked ForeignPtr. Note
67 -- that touchForeignPtr only has to touch the ForeignPtrContents
68 -- object, because that ensures that whatever the finalizer is
69 -- attached to is kept alive.
71 data ForeignPtrContents
73 | PlainWithFinalizer !(IORef [IO ()])
74 | MallocPtrNoFinalizer (MutableByteArray# RealWorld)
75 | MallocPtrWithFinalizer (MutableByteArray# RealWorld) !(IORef [IO ()])
76 -- we optimise the no-finalizer case, which is especially common
77 -- with a MallocPtr. mallocForeignPtr doesn't have to create an
78 -- IORef, or set up a weak pointer.
80 instance Eq (ForeignPtr a) where
81 p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
83 instance Ord (ForeignPtr a) where
84 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
86 instance Show (ForeignPtr a) where
87 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
89 -- |A Finalizer is represented as a pointer to a foreign function that, at
90 -- finalisation time, gets as an argument a plain pointer variant of the
91 -- foreign pointer that the finalizer is associated with.
93 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
95 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
97 -- ^Turns a plain memory reference into a foreign object by
98 -- associating a finalizer - given by the monadic operation - with the
99 -- reference. The storage manager will start the finalizer, in a
100 -- separate thread, some time after the last reference to the
101 -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
102 -- in fact there is no guarantee that the finalizer will eventually
105 -- Note that references from a finalizer do not necessarily prevent
106 -- another object from being finalized. If A's finalizer refers to B
107 -- (perhaps using 'touchForeignPtr', then the only guarantee is that
108 -- B's finalizer will never be started before A's. If both A and B
109 -- are unreachable, then both finalizers will start together. See
110 -- 'touchForeignPtr' for more on finalizer ordering.
112 newConcForeignPtr p finalizer
113 = do fObj <- newForeignPtr_ p
114 addForeignPtrConcFinalizer fObj finalizer
117 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
118 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
119 -- will be released automatically when the 'ForeignPtr' is discarded.
121 -- 'mallocForeignPtr' is equivalent to
123 -- > do { p <- malloc; newForeignPtr finalizerFree p }
125 -- although it may be implemented differently internally: you may not
126 -- assume that the memory returned by 'mallocForeignPtr' has been
127 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
128 mallocForeignPtr = doMalloc undefined
129 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
132 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
133 (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
134 (MallocPtrNoFinalizer mbarr#) #)
136 where (I# size) = sizeOf a
138 -- | This function is similar to 'mallocForeignPtr', except that the
139 -- size of the memory required is given explicitly as a number of bytes.
140 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
141 mallocForeignPtrBytes (I# size) = do
143 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
144 (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
145 (MallocPtrNoFinalizer mbarr#) #)
148 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
149 -- ^This function adds a finalizer to the given foreign object. The
150 -- finalizer will run /before/ all other finalizers for the same
151 -- object which have already been registered.
152 addForeignPtrFinalizer finalizer fptr =
153 addForeignPtrConcFinalizer fptr
154 (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
156 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
157 -- ^This function adds a finalizer to the given @ForeignPtr@. The
158 -- finalizer will run /before/ all other finalizers for the same
159 -- object which have already been registered.
161 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
162 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
163 -- will run in a new thread.
165 -- NB. Be very careful with these finalizers. One common trap is that
166 -- if a finalizer references another finalized value, it does not
167 -- prevent that value from being finalized. In particular, 'Handle's
168 -- are finalized objects, so a finalizer should not refer to a 'Handle'
169 -- (including @stdout@, @stdin@ or @stderr@).
171 addForeignPtrConcFinalizer (ForeignPtr a c) finalizer =
172 addForeignPtrConcFinalizer_ c finalizer
174 addForeignPtrConcFinalizer_ PlainNoFinalizer finalizer = do
176 IO $ \s -> case r of { IORef (STRef r#) ->
177 case mkWeak# r# () (foreignPtrFinalizer r) s of { (# s1, w #) ->
179 addForeignPtrConcFinalizer_ (PlainWithFinalizer r) finalizer
181 addForeignPtrConcFinalizer_ f@(PlainWithFinalizer r) finalizer = do
183 writeIORef r (finalizer : fs)
185 addForeignPtrConcFinalizer_ f@(MallocPtrNoFinalizer fo) finalizer = do
187 IO $ \s -> case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
188 (# s1, w #) -> (# s1, () #)
189 addForeignPtrConcFinalizer_ (MallocPtrWithFinalizer fo r) finalizer
191 addForeignPtrConcFinalizer_ f@(MallocPtrWithFinalizer fo r) finalizer = do
193 writeIORef r (finalizer : fs)
195 foreign import ccall "dynamic"
196 mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
198 foreignPtrFinalizer :: IORef [IO ()] -> IO ()
199 foreignPtrFinalizer r = do fs <- readIORef r; sequence_ fs
201 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
202 -- ^Turns a plain memory reference into a foreign pointer that may be
203 -- associated with finalizers by using 'addForeignPtrFinalizer'.
204 newForeignPtr_ (Ptr obj) = return (ForeignPtr obj PlainNoFinalizer)
206 touchForeignPtr :: ForeignPtr a -> IO ()
207 -- ^This function ensures that the foreign object in
208 -- question is alive at the given place in the sequence of IO
209 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
210 -- does a 'touchForeignPtr' after it
211 -- executes the user action.
213 -- Note that this function should not be used to express dependencies
214 -- between finalizers on 'ForeignPtr's. For example, if the finalizer
215 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
216 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
217 -- for @F2@ is never started before the finalizer for @F1@. They
218 -- might be started together if for example both @F1@ and @F2@ are
219 -- otherwise unreachable, and in that case the scheduler might end up
220 -- running the finalizer for @F2@ first.
222 -- In general, it is not recommended to use finalizers on separate
223 -- objects with ordering constraints between them. To express the
224 -- ordering robustly requires explicit synchronisation using @MVar@s
225 -- between the finalizers, but even then the runtime sometimes runs
226 -- multiple finalizers sequentially in a single thread (for
227 -- performance reasons), so synchronisation between finalizers could
228 -- result in artificial deadlock. Another alternative is to use
229 -- explicit reference counting.
231 touchForeignPtr (ForeignPtr fo r) = touch r
233 touch r = IO $ \s -> case touch# r s of s -> (# s, () #)
235 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
236 -- ^This function extracts the pointer component of a foreign
237 -- pointer. This is a potentially dangerous operations, as if the
238 -- argument to 'unsafeForeignPtrToPtr' is the last usage
239 -- occurrence of the given foreign pointer, then its finalizer(s) will
240 -- be run, which potentially invalidates the plain pointer just
241 -- obtained. Hence, 'touchForeignPtr' must be used
242 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
243 -- has another usage occurrence.
245 -- To avoid subtle coding errors, hand written marshalling code
246 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
247 -- than combinations of 'unsafeForeignPtrToPtr' and
248 -- 'touchForeignPtr'. However, the later routines
249 -- are occasionally preferred in tool generated marshalling code.
250 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr fo
252 castForeignPtr :: ForeignPtr a -> ForeignPtr b
253 -- ^This function casts a 'ForeignPtr'
254 -- parameterised by one type into another type.
255 castForeignPtr f = unsafeCoerce# f
257 -- | Causes the finalizers associated with a foreign pointer to be run
259 finalizeForeignPtr :: ForeignPtr a -> IO ()
260 finalizeForeignPtr (ForeignPtr _ contents) = do
262 PlainNoFinalizer -> return ()
263 PlainWithFinalizer r -> runFinalizers r
264 MallocPtrNoFinalizer _ -> return ()
265 MallocPtrWithFinalizer _ r -> runFinalizers r