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.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
61 = ForeignPtr ForeignObj# !(IORef [IO ()])
62 | MallocPtr (MutableByteArray# RealWorld) !(IORef [IO ()])
64 instance Eq (ForeignPtr a) where
65 p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
67 instance Ord (ForeignPtr a) where
68 compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
70 instance Show (ForeignPtr a) where
71 showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
73 -- |A Finalizer is represented as a pointer to a foreign function that, at
74 -- finalisation time, gets as an argument a plain pointer variant of the
75 -- foreign pointer that the finalizer is associated with.
77 type FinalizerPtr a = FunPtr (Ptr a -> IO ())
79 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
81 -- ^Turns a plain memory reference into a foreign object by
82 -- associating a finalizer - given by the monadic operation - with the
83 -- reference. The storage manager will start the finalizer, in a
84 -- separate thread, some time after the last reference to the
85 -- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
86 -- in fact there is no guarantee that the finalizer will eventually
89 newConcForeignPtr p finalizer
90 = do fObj <- newForeignPtr_ p
91 addForeignPtrConcFinalizer fObj finalizer
94 mallocForeignPtr :: Storable a => IO (ForeignPtr a)
95 -- ^ Allocate some memory and return a 'ForeignPtr' to it. The memory
96 -- will be released automatically when the 'ForeignPtr' is discarded.
98 -- 'mallocForeignPtr' is equivalent to
100 -- > do { p <- malloc; newForeignPtr finalizerFree p }
102 -- although it may be implemented differently internally: you may not
103 -- assume that the memory returned by 'mallocForeignPtr' has been
104 -- allocated with 'Foreign.Marshal.Alloc.malloc'.
105 mallocForeignPtr = doMalloc undefined
106 where doMalloc :: Storable b => b -> IO (ForeignPtr b)
110 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
111 (# s, MallocPtr mbarr# r #)
113 where (I# size) = sizeOf a
115 -- | This function is similar to 'mallocForeignPtr', except that the
116 -- size of the memory required is given explicitly as a number of bytes.
117 mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
118 mallocForeignPtrBytes (I# size) = do
121 case newPinnedByteArray# size s of { (# s, mbarr# #) ->
122 (# s, MallocPtr mbarr# r #)
125 addForeignPtrFinalizer :: FinalizerPtr a -> ForeignPtr a -> IO ()
126 -- ^This function adds a finalizer to the given foreign object. The
127 -- finalizer will run /before/ all other finalizers for the same
128 -- object which have already been registered.
129 addForeignPtrFinalizer finalizer fptr =
130 addForeignPtrConcFinalizer fptr
131 (mkFinalizer finalizer (unsafeForeignPtrToPtr fptr))
133 addForeignPtrConcFinalizer :: ForeignPtr a -> IO () -> IO ()
134 -- ^This function adds a finalizer to the given @ForeignPtr@. The
135 -- finalizer will run /before/ all other finalizers for the same
136 -- object which have already been registered.
138 -- This is a variant of @addForeignPtrFinalizer@, where the finalizer
139 -- is an arbitrary @IO@ action. When it is invoked, the finalizer
140 -- will run in a new thread.
142 -- NB. Be very careful with these finalizers. One common trap is that
143 -- if a finalizer references another finalized value, it does not
144 -- prevent that value from being finalized. In particular, 'Handle's
145 -- are finalized objects, so a finalizer should not refer to a 'Handle'
146 -- (including @stdout@, @stdin@ or @stderr@).
148 addForeignPtrConcFinalizer f@(ForeignPtr fo r) finalizer = do
150 writeIORef r (finalizer : fs)
153 let p = unsafeForeignPtrToPtr f in
154 case mkWeak# fo () (foreignPtrFinalizer r p) s of
155 (# s1, w #) -> (# s1, () #)
157 addForeignPtrConcFinalizer f@(MallocPtr fo r) finalizer = do
159 writeIORef r (finalizer : fs)
162 let p = unsafeForeignPtrToPtr f in
163 case mkWeak# fo () (do foreignPtrFinalizer r p
164 touchPinnedByteArray# fo) s of
165 (# s1, w #) -> (# s1, () #)
168 foreign import ccall "dynamic"
169 mkFinalizer :: FinalizerPtr a -> Ptr a -> IO ()
171 foreignPtrFinalizer :: IORef [IO ()] -> Ptr a -> IO ()
172 foreignPtrFinalizer r p = do
176 newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
177 -- ^Turns a plain memory reference into a foreign pointer that may be
178 -- associated with finalizers by using 'addForeignPtrFinalizer'.
179 newForeignPtr_ (Ptr obj) = do
182 case mkForeignObj# obj s# of
183 (# s1#, fo# #) -> (# s1#, ForeignPtr fo# r #)
185 touchPinnedByteArray# :: MutableByteArray# RealWorld -> IO ()
186 touchPinnedByteArray# ba# = IO $ \s -> case touch# ba# s of s -> (# s, () #)
188 touchForeignPtr :: ForeignPtr a -> IO ()
189 -- ^This function ensures that the foreign object in
190 -- question is alive at the given place in the sequence of IO
191 -- actions. In particular 'Foreign.ForeignPtr.withForeignPtr'
192 -- does a 'touchForeignPtr' after it
193 -- executes the user action.
195 -- Note that this function should not be used to express liveness
196 -- dependencies between 'ForeignPtr's. For example, if the finalizer
197 -- for a 'ForeignPtr' @F1@ calls 'touchForeignPtr' on a second
198 -- 'ForeignPtr' @F2@, then the only guarantee is that the finalizer
199 -- for @F2@ is never started before the finalizer for @F1@. They
200 -- might be started together if for example both @F1@ and @F2@ are
201 -- otherwise unreachable, and in that case the scheduler might end up
202 -- running the finalizer for @F2@ first.
204 -- In general, it is not recommended to use finalizers on separate
205 -- objects with ordering constraints between them. To express the
206 -- ordering robustly requires explicit synchronisation using @MVar@s
207 -- between the finalizers, but even then the runtime sometimes runs
208 -- multiple finalizers sequentially in a single thread (for
209 -- performance reasons), so synchronisation between finalizers could
210 -- result in artificial deadlock.
212 touchForeignPtr (ForeignPtr fo r)
213 = IO $ \s -> case touch# fo s of s -> (# s, () #)
214 touchForeignPtr (MallocPtr fo r)
215 = touchPinnedByteArray# fo
217 unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
218 -- ^This function extracts the pointer component of a foreign
219 -- pointer. This is a potentially dangerous operations, as if the
220 -- argument to 'unsafeForeignPtrToPtr' is the last usage
221 -- occurrence of the given foreign pointer, then its finalizer(s) will
222 -- be run, which potentially invalidates the plain pointer just
223 -- obtained. Hence, 'touchForeignPtr' must be used
224 -- wherever it has to be guaranteed that the pointer lives on - i.e.,
225 -- has another usage occurrence.
227 -- To avoid subtle coding errors, hand written marshalling code
228 -- should preferably use 'Foreign.ForeignPtr.withForeignPtr' rather
229 -- than combinations of 'unsafeForeignPtrToPtr' and
230 -- 'touchForeignPtr'. However, the later routines
231 -- are occasionally preferred in tool generated marshalling code.
232 unsafeForeignPtrToPtr (ForeignPtr fo r) = Ptr (foreignObjToAddr# fo)
233 unsafeForeignPtrToPtr (MallocPtr fo r) = Ptr (byteArrayContents# (unsafeCoerce# fo))
235 castForeignPtr :: ForeignPtr a -> ForeignPtr b
236 -- ^This function casts a 'ForeignPtr'
237 -- parameterised by one type into another type.
238 castForeignPtr f = unsafeCoerce# f
240 -- | Causes the finalizers associated with a foreign pointer to be run
242 finalizeForeignPtr :: ForeignPtr a -> IO ()
243 finalizeForeignPtr foreignPtr = do
244 finalizers <- readIORef refFinalizers
246 writeIORef refFinalizers []
248 refFinalizers = case foreignPtr of
249 (ForeignPtr _ ref) -> ref
250 (MallocPtr _ ref) -> ref