FIX #1364: added support for C finalizers that run as soon as the value is no longer...
[ghc-base.git] / GHC / ForeignPtr.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 {-# OPTIONS_HADDOCK hide #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.ForeignPtr
6 -- Copyright   :  (c) The University of Glasgow, 1992-2003
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC extensions)
12 --
13 -- GHC's implementation of the 'ForeignPtr' data type.
14 -- 
15 -----------------------------------------------------------------------------
16
17 -- #hide
18 module GHC.ForeignPtr
19   (
20         ForeignPtr(..),
21         FinalizerPtr,
22         FinalizerEnvPtr,
23         newForeignPtr_,
24         mallocForeignPtr,
25         mallocPlainForeignPtr,
26         mallocForeignPtrBytes,
27         mallocPlainForeignPtrBytes,
28         addForeignPtrFinalizer,
29         addForeignPtrFinalizerEnv,
30         touchForeignPtr,
31         unsafeForeignPtrToPtr,
32         castForeignPtr,
33         newConcForeignPtr,
34         addForeignPtrConcFinalizer,
35         finalizeForeignPtr
36   ) where
37
38 import Control.Monad    ( sequence_ )
39 import Foreign.Storable
40 import Data.Typeable
41
42 import GHC.Show
43 import GHC.List         ( null )
44 import GHC.Base
45 import GHC.IOBase
46 import GHC.STRef        ( STRef(..) )
47 import GHC.Ptr          ( Ptr(..), FunPtr(..) )
48 import GHC.Err
49
50 #include "Typeable.h"
51
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.
63 --
64 -- The 'ForeignPtr' is parameterised in the same way as 'Ptr'.  The
65 -- type argument of 'ForeignPtr' should normally be an instance of
66 -- class 'Storable'.
67 --
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.
78
79 INSTANCE_TYPEABLE1(ForeignPtr,foreignPtrTc,"ForeignPtr")
80
81 data Finalizers
82   = NoFinalizers
83   | CFinalizers
84   | HaskellFinalizers
85     deriving Eq
86
87 data ForeignPtrContents
88   = PlainForeignPtr !(IORef (Finalizers, [IO ()]))
89   | MallocPtr      (MutableByteArray# RealWorld) !(IORef (Finalizers, [IO ()]))
90   | PlainPtr       (MutableByteArray# RealWorld)
91
92 instance Eq (ForeignPtr a) where
93     p == q  =  unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
94
95 instance Ord (ForeignPtr a) where
96     compare p q  =  compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
97
98 instance Show (ForeignPtr a) where
99     showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
100
101
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.
105 -- 
106 type FinalizerPtr a        = FunPtr (Ptr a -> IO ())
107 type FinalizerEnvPtr env a = FunPtr (Ptr env -> Ptr a -> IO ())
108
109 newConcForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
110 --
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
117 -- run at all.
118 --
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.
125 --
126 newConcForeignPtr p finalizer
127   = do fObj <- newForeignPtr_ p
128        addForeignPtrConcFinalizer fObj finalizer
129        return fObj
130
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.
134 --
135 -- 'mallocForeignPtr' is equivalent to
136 --
137 -- >    do { p <- malloc; newForeignPtr finalizerFree p }
138 -- 
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'.
142 --
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'
148 -- with a finalizer.
149 -- 
150 mallocForeignPtr = doMalloc undefined
151   where doMalloc :: Storable b => b -> IO (ForeignPtr b)
152         doMalloc a = do
153           r <- newIORef (NoFinalizers, [])
154           IO $ \s ->
155             case newPinnedByteArray# size s of { (# s', mbarr# #) ->
156              (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
157                                (MallocPtr mbarr# r) #)
158             }
159             where (I# size) = sizeOf a
160
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, [])
166   IO $ \s ->
167      case newPinnedByteArray# size s      of { (# s', mbarr# #) ->
168        (# s', ForeignPtr (byteArrayContents# (unsafeCoerce# mbarr#))
169                          (MallocPtr mbarr# r) #)
170      }
171
172 -- | Allocate some memory and return a 'ForeignPtr' to it.  The memory
173 -- will be released automatically when the 'ForeignPtr' is discarded.
174 --
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.
184 -- 
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#))
191                                (PlainPtr mbarr#) #)
192             }
193             where (I# size) = sizeOf a
194
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#))
203                          (PlainPtr mbarr#) #)
204      }
205
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"
214   where
215     f r =
216       noMixing CFinalizers r $
217         IO $ \s ->
218           case r of { IORef (STRef r#) ->
219           case mkWeakForeignEnv# r# () fp p 0# nullAddr# s of { (# s1, w #) ->
220           (# s1, finalizeForeign w #) }}
221
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"
232   where
233     f r =
234       noMixing CFinalizers r $
235         IO $ \s ->
236           case r of { IORef (STRef r#) ->
237           case mkWeakForeignEnv# r# () fp p 1# ep s of { (# s1, w #) ->
238           (# s1, finalizeForeign w #) }}
239
240 finalizeForeign :: Weak# () -> IO ()
241 finalizeForeign w = IO $ \s ->
242   case finalizeWeak# w s of
243     (# s1, 0#, _ #) -> (# s1, () #)
244     (# s1, _ , f #) -> f s1
245
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.
250 --
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.
254 --
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@).
260 --
261 addForeignPtrConcFinalizer (ForeignPtr _ c) finalizer = 
262   addForeignPtrConcFinalizer_ c finalizer
263
264 addForeignPtrConcFinalizer_ :: ForeignPtrContents -> IO () -> IO ()
265 addForeignPtrConcFinalizer_ (PlainForeignPtr r) finalizer = do
266   noFinalizers <- noMixing HaskellFinalizers r (return finalizer)
267   if noFinalizers
268      then IO $ \s ->
269               case r of { IORef (STRef r#) ->
270               case mkWeak# r# () (foreignPtrFinalizer r) s of {  (# s1, _ #) ->
271               (# s1, () #) }}
272      else return ()
273 addForeignPtrConcFinalizer_ f@(MallocPtr fo r) finalizer = do
274   noFinalizers <- noMixing HaskellFinalizers r (return finalizer)
275   if noFinalizers
276      then  IO $ \s -> 
277                case mkWeak# fo () (do foreignPtrFinalizer r; touch f) s of
278                   (# s1, _ #) -> (# s1, () #)
279      else return ()
280
281 addForeignPtrConcFinalizer_ _ _ =
282   error "GHC.ForeignPtr: attempt to add a finalizer to plain pointer"
283
284 noMixing ::
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")
291      else do
292        f <- mkF
293        writeIORef r (ftype0, f : fs)
294        return (null fs)
295
296 foreignPtrFinalizer :: IORef (Finalizers, [IO ()]) -> IO ()
297 foreignPtrFinalizer r = do (_, fs) <- readIORef r; sequence_ fs
298
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))
305
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.
312 -- 
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.
321 --
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.
330 --
331 touchForeignPtr (ForeignPtr _ r) = touch r
332
333 touch :: ForeignPtrContents -> IO ()
334 touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
335
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.
345 --
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
352
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
357
358 -- | Causes the finalizers associated with a foreign pointer to be run
359 -- immediately.
360 finalizeForeignPtr :: ForeignPtr a -> IO ()
361 finalizeForeignPtr (ForeignPtr _ (PlainPtr _)) = return () -- no effect
362 finalizeForeignPtr (ForeignPtr _ foreignPtr) = do
363         (ftype, finalizers) <- readIORef refFinalizers
364         sequence_ finalizers
365         writeIORef refFinalizers (ftype, [])
366         where
367                 refFinalizers = case foreignPtr of
368                         (PlainForeignPtr ref) -> ref
369                         (MallocPtr     _ ref) -> ref
370                         PlainPtr _            ->
371                             error "finalizeForeignPtr PlainPtr"
372