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
37 import GHC.List ( null )
40 import GHC.STRef ( STRef(..) )
41 import GHC.Ptr ( Ptr(..) )
45 -- |The type 'ForeignPtr' represents references to objects that are
46 -- maintained in a foreign language, i.e., that are not part of the
47 -- data structures usually managed by the Haskell storage manager.
48 -- The essential difference between 'ForeignPtr's and vanilla memory
49 -- references of type @Ptr a@ is that the former may be associated
50 -- with /finalizers/. A finalizer is a routine that is invoked when
51 -- the Haskell storage manager detects that - within the Haskell heap
52 -- and stack - there are no more references left that are pointing to
53 -- the 'ForeignPtr'. Typically, the finalizer will, then, invoke
54 -- routines in the foreign language that free the resources bound by
55 -- the foreign object.
57 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'. The
58 -- type argument of 'ForeignPtr' should normally be an instance of
61 data ForeignPtr a = ForeignPtr Addr# ForeignPtrContents
62 -- we cache the Addr# in the ForeignPtr object, but attach
63 -- the finalizer to the IORef (or the MutableByteArray# in
64 -- the case of a MallocPtr). The aim of the representation
65 -- is to make withForeignPtr efficient; in fact, withForeignPtr
66 -- should be just as efficient as unpacking a Ptr, and multiple
67 -- withForeignPtrs can share an unpacked ForeignPtr. Note
68 -- that touchForeignPtr only has to touch the ForeignPtrContents
69 -- object, because that ensures that whatever the finalizer is
70 -- attached to is kept alive.
72 data ForeignPtrContents
73 = PlainForeignPtr !(IORef [IO ()])
74 | MallocPtr (MutableByteArray# RealWorld) !(IORef [IO ()])
76 instance Eq (ForeignPtr a) where
77 p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
79 instance Ord (ForeignPtr a) where
80 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
82 instance Show (ForeignPtr a) where
83 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
85 -- |A Finalizer is represented as a pointer to a foreign function that, at
86 -- finalisation time, gets as an argument a plain pointer variant of the
87 -- foreign pointer that the finalizer is associated with.
89 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
91 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
93 -- ^Turns a plain memory reference into a foreign object by
94 -- associating a finalizer - given by the monadic operation - with the
95 -- reference. The storage manager will start the finalizer, in a
96 -- separate thread, some time after the last reference to the
97 -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
98 -- in fact there is no guarantee that the finalizer will eventually
101 -- Note that references from a finalizer do not necessarily prevent
102 -- another object from being finalized. If A's finalizer refers to B
103 -- (perhaps using 'touchForeignPtr', then the only guarantee is that
104 -- B's finalizer will never be started before A's. If both A and B
105 -- are unreachable, then both finalizers will start together. See
106 -- 'touchForeignPtr' for more on finalizer ordering.
108 newConcForeignPtr p finalizer
109 = do fObj <- newForeignPtr_ p
110 addForeignPtrConcFinalizer fObj finalizer
113 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
114 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
115 -- will be released automatically when the 'ForeignPtr' is discarded.
117 -- 'mallocForeignPtr' is equivalent to
119 -- > do { p <- malloc; newForeignPtr finalizerFree p }
121 -- although it may be implemented differently internally: you may not
122 -- assume that the memory returned by 'mallocForeignPtr' has been
123 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
125 -- GHC notes: 'mallocForeignPtr' has a heavily optimised
126 -- implementation in GHC. It uses pinned memory in the garbage
127 -- collected heap, so the 'ForeignPtr' does not require a finalizer to
128 -- free the memory. Use of 'mallocForeignPtr' and associated
129 -- functions is strongly recommended in preference to 'newForeignPtr'
132 mallocForeignPtr = doMalloc undefined
133 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
137 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
138 (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
139 (MallocPtr mbarr# r) #)
141 where (I# size) = sizeOf a
143 -- | This function is similar to 'mallocForeignPtr', except that the
144 -- size of the memory required is given explicitly as a number of bytes.
145 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
146 mallocForeignPtrBytes (I# size) = do
149 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
150 (# s, ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
151 (MallocPtr mbarr# r) #)
154 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
155 -- ^This function adds a finalizer to the given foreign object. The
156 -- finalizer will run /before/ all other finalizers for the same
157 -- object which have already been registered.
158 addForeignPtrFinalizer finalizer fptr =
159 addForeignPtrConcFinalizer fptr
160 (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
162 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
163 -- ^This function adds a finalizer to the given @ForeignPtr@. The
164 -- finalizer will run /before/ all other finalizers for the same
165 -- object which have already been registered.
167 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
168 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
169 -- will run in a new thread.
171 -- NB. Be very careful with these finalizers. One common trap is that
172 -- if a finalizer references another finalized value, it does not
173 -- prevent that value from being finalized. In particular, 'Handle's
174 -- are finalized objects, so a finalizer should not refer to a 'Handle'
175 -- (including @stdout@, @stdin@ or @stderr@).
177 addForeignPtrConcFinalizer (ForeignPtr a c) finalizer =
178 addForeignPtrConcFinalizer_ c finalizer
180 addForeignPtrConcFinalizer_ f@(PlainForeignPtr r) finalizer = do
182 writeIORef r (finalizer : fs)
185 case r of { IORef (STRef r#) ->
186 case mkWeak# r# () (foreignPtrFinalizer r) s of { (# s1, w #) ->
189 addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do
191 writeIORef r (finalizer : fs)
194 case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
195 (# s1, w #) -> (# s1, () #)
198 foreign import ccall "dynamic"
199 mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
201 foreignPtrFinalizer :: IORef [IO ()] -> IO ()
202 foreignPtrFinalizer r = do fs <- readIORef r; sequence_ fs
204 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
205 -- ^Turns a plain memory reference into a foreign pointer that may be
206 -- associated with finalizers by using 'addForeignPtrFinalizer'.
207 newForeignPtr_ (Ptr obj) = do
209 return (ForeignPtr obj (PlainForeignPtr r))
211 touchForeignPtr :: ForeignPtr a -> IO ()
212 -- ^This function ensures that the foreign object in
213 -- question is alive at the given place in the sequence of IO
214 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
215 -- does a 'touchForeignPtr' after it
216 -- executes the user action.
218 -- Note that this function should not be used to express dependencies
219 -- between finalizers on 'ForeignPtr's. For example, if the finalizer
220 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
221 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
222 -- for @F2@ is never started before the finalizer for @F1@. They
223 -- might be started together if for example both @F1@ and @F2@ are
224 -- otherwise unreachable, and in that case the scheduler might end up
225 -- running the finalizer for @F2@ first.
227 -- In general, it is not recommended to use finalizers on separate
228 -- objects with ordering constraints between them. To express the
229 -- ordering robustly requires explicit synchronisation using @MVar@s
230 -- between the finalizers, but even then the runtime sometimes runs
231 -- multiple finalizers sequentially in a single thread (for
232 -- performance reasons), so synchronisation between finalizers could
233 -- result in artificial deadlock. Another alternative is to use
234 -- explicit reference counting.
236 touchForeignPtr (ForeignPtr fo r) = touch r
238 touch r = IO $ \s -> case touch# r s of s -> (# s, () #)
240 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
241 -- ^This function extracts the pointer component of a foreign
242 -- pointer. This is a potentially dangerous operations, as if the
243 -- argument to 'unsafeForeignPtrToPtr' is the last usage
244 -- occurrence of the given foreign pointer, then its finalizer(s) will
245 -- be run, which potentially invalidates the plain pointer just
246 -- obtained. Hence, 'touchForeignPtr' must be used
247 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
248 -- has another usage occurrence.
250 -- To avoid subtle coding errors, hand written marshalling code
251 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
252 -- than combinations of 'unsafeForeignPtrToPtr' and
253 -- 'touchForeignPtr'. However, the later routines
254 -- are occasionally preferred in tool generated marshalling code.
255 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr fo
257 castForeignPtr :: ForeignPtr a -> ForeignPtr b
258 -- ^This function casts a 'ForeignPtr'
259 -- parameterised by one type into another type.
260 castForeignPtr f = unsafeCoerce# f
262 -- | Causes the finalizers associated with a foreign pointer to be run
264 finalizeForeignPtr :: ForeignPtr a -> IO ()
265 finalizeForeignPtr (ForeignPtr _ foreignPtr) = do
266 finalizers <- readIORef refFinalizers
268 writeIORef refFinalizers []
270 refFinalizers = case foreignPtr of
271 (PlainForeignPtr ref) -> ref
272 (MallocPtr _ ref) -> ref